text
stringlengths
478
483k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: getftp (struct url *u, struct url *original_url, 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 = NULL; 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; int flags; wgint rd_size, previous_rd_size = 0; char type_char; bool try_again; bool list_a_used = false; #ifdef HAVE_SSL enum prot_level prot = (opt.ftps_clear_data_connection ? PROT_CLEAR : PROT_PRIVATE); /* these variables tell whether the target server * accepts the security extensions (RFC 2228) or not, * and whether we're actually using any of them * (encryption at the control connection only, * or both at control and data connections) */ bool using_control_security = false, using_data_security = false; #endif 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; /* Find the username with priority */ if (u->user) user = u->user; else if (opt.user && (opt.use_askpass || opt.ask_passwd)) user = opt.user; else if (opt.ftp_user) user = opt.ftp_user; else if (opt.user) user = opt.user; else user = NULL; /* Find the password with priority */ if (u->passwd) passwd = u->passwd; else if (opt.passwd && (opt.use_askpass || opt.ask_passwd)) passwd = opt.passwd; else if (opt.ftp_passwd) passwd = opt.ftp_passwd; else if (opt.passwd) passwd = opt.passwd; else passwd = NULL; /* Check for ~/.netrc if none of the above match */ if (opt.netrc && (!user || !passwd)) search_netrc (u->host, (const char **) &user, (const char **) &passwd, 1, NULL); if (!user) user = "anonymous"; if (!passwd) passwd = "-wget@"; dtsock = -1; local_sock = -1; con->dltime = 0; #ifdef HAVE_SSL if (u->scheme == SCHEME_FTPS) { /* Initialize SSL layer first */ if (!ssl_init ()) { scheme_disable (SCHEME_FTPS); logprintf (LOG_NOTQUIET, _("Could not initialize SSL. It will be disabled.")); err = SSLINITFAILED; return err; } /* If we're using the default FTP port and implicit FTPS was requested, * rewrite the port to the default *implicit* FTPS port. */ if (opt.ftps_implicit && u->port == DEFAULT_FTP_PORT) { DEBUGP (("Implicit FTPS was specified. Rewriting default port to %d.\n", DEFAULT_FTPS_IMPLICIT_PORT)); u->port = DEFAULT_FTPS_IMPLICIT_PORT; } } #endif if (!(cmd & DO_LOGIN)) { csock = con->csock; #ifdef HAVE_SSL using_data_security = con->st & DATA_CHANNEL_SECURITY; #endif } 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; #ifdef HAVE_SSL if (u->scheme == SCHEME_FTPS) { /* If we're in implicit FTPS mode, we have to set up SSL/TLS before everything else. * Otherwise we first read the server's greeting, and then send an "AUTH TLS". */ if (opt.ftps_implicit) { err = init_control_ssl_connection (csock, u, &using_control_security); if (err != NOCONERROR) return err; err = get_ftp_greeting (csock, con); if (err != FTPOK) return err; } else { err = get_ftp_greeting (csock, con); if (err != FTPOK) return err; err = init_control_ssl_connection (csock, u, &using_control_security); if (err != NOCONERROR) return err; } } else { err = get_ftp_greeting (csock, con); if (err != FTPOK) return err; } #else err = get_ftp_greeting (csock, con); if (err != FTPOK) return err; #endif /* 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 (); } #ifdef HAVE_SSL if (using_control_security) { /* Send the PBSZ and PROT commands, in that order. * If we are here it means that the server has already accepted * some form of FTPS. Thus, these commands must work. * If they don't work, that's an error. There's no sense in honoring * --ftps-fallback-to-ftp or similar options. */ if (u->scheme == SCHEME_FTPS) { if (!opt.server_response) logputs (LOG_VERBOSE, "==> PBSZ 0 ... "); if ((err = ftp_pbsz (csock, 0)) == FTPNOPBSZ) { logputs (LOG_NOTQUIET, _("Server did not accept the 'PBSZ 0' command.\n")); return err; } if (!opt.server_response) logputs (LOG_VERBOSE, "done."); if (!opt.server_response) logprintf (LOG_VERBOSE, " ==> PROT %c ... ", (int) prot); if ((err = ftp_prot (csock, prot)) == FTPNOPROT) { logprintf (LOG_NOTQUIET, _("Server did not accept the 'PROT %c' command.\n"), (int) prot); return err; } if (!opt.server_response) logputs (LOG_VERBOSE, "done.\n"); if (prot != PROT_CLEAR) { using_data_security = true; con->st |= DATA_CHANNEL_SECURITY; } } } #endif /* 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)); return (retryable_socket_connect_error (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, FTPPORTERR */ 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 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; bool all_exist = true; struct fileinfo *f; uerr_t _res = ftp_get_listing (u, original_url, 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; } else { all_exist = false; } 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); if (all_exist) { return RETRFINISHED; } else { return FTPNSFOD; } } 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 (!opt.ftp_pasv) /* we are not using passive mode so we need to accept */ { /* Wait for the server to connect to the address we're waiting at. */ dtsock = accept_connection (local_sock); if (dtsock < 0) { logprintf (LOG_NOTQUIET, "accept: %s\n", strerror (errno)); return CONERROR; } } /* Open the file -- if output_stream is set, use it instead. */ /* 2005-04-17 SMS. Note that having the output_stream ("-O") file opened in main (main.c) rather limits the ability in VMS to open the file differently for ASCII versus binary FTP here. (Of course, doing it there allows a open failure to be detected immediately, without first connecting to the server.) */ if (!output_stream || con->cmd & DO_LIST) { /* On VMS, alter the name as required. */ #ifdef __VMS char *targ; targ = ods_conform (con->target); if (targ != con->target) { xfree (con->target); con->target = targ; } #endif /* def __VMS */ mkalldirs (con->target); if (opt.backups) rotate_backups (con->target); /* 2005-04-15 SMS. For VMS, define common fopen() optional arguments, and a handy macro for use as a variable "binary" flag. Elsewhere, define a constant "binary" flag. Isn't it nice to have distinct text and binary file types? */ /* 2011-09-30 SMS. Added listing files to the set of non-"binary" (text, Stream_LF) files. (Wget works either way, but other programs, like, say, text editors, work better on listing files which have text attributes.) Now we use "binary" attributes for a binary ("IMAGE") transfer, unless "--ftp-stmlf" was specified, and we always use non-"binary" (text, Stream_LF) attributes for a listing file, or for an ASCII transfer. Tidied the VMS-specific BIN_TYPE_xxx macros, and changed the call to fopen_excl() (restored?) to use BIN_TYPE_FILE instead of "true". */ #ifdef __VMS # define BIN_TYPE_TRANSFER (type_char != 'A') # define BIN_TYPE_FILE \ ((!(cmd & DO_LIST)) && BIN_TYPE_TRANSFER && (opt.ftp_stmlf == 0)) # define FOPEN_OPT_ARGS "fop=sqo", "acc", acc_cb, &open_id # define FOPEN_OPT_ARGS_BIN "ctx=bin,stm", "rfm=fix", "mrs=512" FOPEN_OPT_ARGS #else /* def __VMS */ # define BIN_TYPE_FILE true #endif /* def __VMS [else] */ if (restval && !(con->cmd & DO_LIST)) { #ifdef __VMS int open_id; if (BIN_TYPE_FILE) { open_id = 3; fp = fopen (con->target, "ab", FOPEN_OPT_ARGS_BIN); } else { open_id = 4; fp = fopen (con->target, "a", FOPEN_OPT_ARGS); } #else /* def __VMS */ fp = fopen (con->target, "ab"); #endif /* def __VMS [else] */ } else if (opt.noclobber || opt.always_rest || opt.timestamping || opt.dirstruct || opt.output_document || count > 0) { if (opt.unlink_requested && file_exists_p (con->target, NULL)) { if (unlink (con->target) < 0) { logprintf (LOG_NOTQUIET, "%s: %s\n", con->target, strerror (errno)); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return UNLINKERR; } } #ifdef __VMS int open_id; if (BIN_TYPE_FILE) { open_id = 5; fp = fopen (con->target, "wb", FOPEN_OPT_ARGS_BIN); } else { open_id = 6; fp = fopen (con->target, "w", FOPEN_OPT_ARGS); } #else /* def __VMS */ fp = fopen (con->target, "wb"); #endif /* def __VMS [else] */ } else { fp = fopen_excl (con->target, BIN_TYPE_FILE); if (!fp && errno == EEXIST) { /* We cannot just invent a new name and use it (which is what functions like unique_create typically do) because we told the user we'd use this name. Instead, return and retry the download. */ logprintf (LOG_NOTQUIET, _("%s has sprung into existence.\n"), con->target); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return FOPEN_EXCL_ERR; } } if (!fp) { logprintf (LOG_NOTQUIET, "%s: %s\n", con->target, strerror (errno)); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return FOPENERR; } } else fp = output_stream; if (passed_expected_bytes) { print_length (passed_expected_bytes, restval, true); expected_bytes = passed_expected_bytes; /* for fd_read_body's progress bar */ } else if (expected_bytes) print_length (expected_bytes, restval, false); #ifdef HAVE_SSL if (u->scheme == SCHEME_FTPS && using_data_security) { /* We should try to restore the existing SSL session in the data connection * and fall back to establishing a new session if the server doesn't want to restore it. */ if (!opt.ftps_resume_ssl || !ssl_connect_wget (dtsock, u->host, &csock)) { if (opt.ftps_resume_ssl) logputs (LOG_NOTQUIET, "Server does not want to resume the SSL session. Trying with a new one.\n"); if (!ssl_connect_wget (dtsock, u->host, NULL)) { fd_close (csock); fd_close (dtsock); err = CONERROR; logputs (LOG_NOTQUIET, "Could not perform SSL handshake.\n"); goto exit_error; } } else logputs (LOG_NOTQUIET, "Resuming SSL session in data connection.\n"); if (!ssl_check_certificate (dtsock, u->host)) { fd_close (csock); fd_close (dtsock); err = CONERROR; goto exit_error; } } #endif /* Get the contents of the document. */ flags = 0; if (restval && rest_failed) flags |= rb_skip_startpos; rd_size = 0; res = fd_read_body (con->target, dtsock, fp, expected_bytes ? expected_bytes - restval : 0, restval, &rd_size, qtyread, &con->dltime, flags, warc_tmp); tms = datetime_str (time (NULL)); tmrate = retr_rate (rd_size, con->dltime); total_download_time += con->dltime; #ifdef ENABLE_XATTR if (opt.enable_xattr) set_file_metadata (u->url, NULL, fp); #endif fd_close (local_sock); /* Close the local file. */ if (!output_stream || con->cmd & DO_LIST) fclose (fp); /* If fd_read_body couldn't write to fp or warc_tmp, bail out. */ if (res == -2 || (warc_tmp != NULL && res == -3)) { logprintf (LOG_NOTQUIET, _("%s: %s, closing control connection.\n"), con->target, strerror (errno)); fd_close (csock); con->csock = -1; fd_close (dtsock); if (res == -2) return FWRITEERR; else if (res == -3) return WARC_TMP_FWRITEERR; } else if (res == -1) { logprintf (LOG_NOTQUIET, _("%s (%s) - Data connection: %s; "), tms, tmrate, fd_errstr (dtsock)); if (opt.server_response) logputs (LOG_ALWAYS, "\n"); } fd_close (dtsock); /* Get the server to tell us if everything is retrieved. */ err = ftp_response (csock, &respline); if (err != FTPOK) { /* The control connection is decidedly closed. Print the time only if it hasn't already been printed. */ if (res != -1) logprintf (LOG_NOTQUIET, "%s (%s) - ", tms, tmrate); logputs (LOG_NOTQUIET, _("Control connection closed.\n")); /* If there is an error on the control connection, close it, but return FTPRETRINT, since there is a possibility that the whole file was retrieved nevertheless (but that is for ftp_loop_internal to decide). */ fd_close (csock); con->csock = -1; return FTPRETRINT; } /* err != FTPOK */ *last_expected_bytes = ftp_expected_bytes (respline); /* If retrieval failed for any reason, return FTPRETRINT, but do not close socket, since the control connection is still alive. If there is something wrong with the control connection, it will become apparent later. */ if (*respline != '2') { if (res != -1) logprintf (LOG_NOTQUIET, "%s (%s) - ", tms, tmrate); logputs (LOG_NOTQUIET, _("Data transfer aborted.\n")); #ifdef HAVE_SSL if (!c_strncasecmp (respline, "425", 3) && u->scheme == SCHEME_FTPS) { logputs (LOG_NOTQUIET, "FTPS server rejects new SSL sessions in the data connection.\n"); xfree (respline); return FTPRESTFAIL; } #endif xfree (respline); return FTPRETRINT; } xfree (respline); if (res == -1) { /* What now? The data connection was erroneous, whereas the response says everything is OK. We shall play it safe. */ return FTPRETRINT; } if (!(cmd & LEAVE_PENDING)) { /* Closing the socket is faster than sending 'QUIT' and the effect is the same. */ fd_close (csock); con->csock = -1; } /* If it was a listing, and opt.server_response is true, print it out. */ if (con->cmd & DO_LIST) { if (opt.server_response) { /* 2005-02-25 SMS. Much of this work may already have been done, but repeating it should do no damage beyond wasting time. */ /* On VMS, alter the name as required. */ #ifdef __VMS char *targ; targ = ods_conform (con->target); if (targ != con->target) { xfree (con->target); con->target = targ; } #endif /* def __VMS */ mkalldirs (con->target); fp = fopen (con->target, "r"); if (!fp) logprintf (LOG_ALWAYS, "%s: %s\n", con->target, strerror (errno)); else { char *line = NULL; size_t bufsize = 0; ssize_t len; /* The lines are being read with getline because of no-buffering on opt.lfile. */ while ((len = getline (&line, &bufsize, fp)) > 0) { while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) line[--len] = '\0'; logprintf (LOG_ALWAYS, "%s\n", quotearg_style (escape_quoting_style, line)); } xfree (line); fclose (fp); } } /* server_response */ /* 2013-10-17 Andrea Urbani (matfanjol) < __LIST_A_EXPLANATION__ > After the SYST command, looks if it knows that system. If yes, wget will force the use of "LIST" or "LIST -a". If no, wget will try, only the first time of each session, before the "LIST -a" command and after the "LIST". If "LIST -a" works and returns more or equal data of the "LIST", "LIST -a" will be the standard list command for all the session. If "LIST -a" fails or returns less data than "LIST" (think on the case of an existing file called "-a"), "LIST" will be the standard list command for all the session. ("LIST -a" is used to get also the hidden files) */ if (!(con->st & LIST_AFTER_LIST_A_CHECK_DONE)) { /* We still have to check "LIST" after the first "LIST -a" to see if with "LIST" we get more data than "LIST -a", that means "LIST -a" returned files/folders with "-a" name. */ if (con->st & AVOID_LIST_A) { /* LIST was used in this cycle. Let's see the result. */ if (rd_size > previous_rd_size) { /* LIST returns more data than "LIST -a". "LIST" is the official command to use. */ con->st |= LIST_AFTER_LIST_A_CHECK_DONE; DEBUGP (("LIST returned more data than \"LIST -a\": " "I will use \"LIST\" as standard list command\n")); } else if (previous_rd_size > rd_size) { /* "LIST -a" returned more data then LIST. "LIST -a" is the official command to use. */ con->st |= LIST_AFTER_LIST_A_CHECK_DONE; con->st |= AVOID_LIST; con->st &= ~AVOID_LIST_A; /* Sorry, please, download again the "LIST -a"... */ try_again = true; DEBUGP (("LIST returned less data than \"LIST -a\": I will " "use \"LIST -a\" as standard list command\n")); } else { /* LIST and "LIST -a" return the same data. */ if (rd_size == 0) { /* Same empty data. We will check both again because we cannot check if "LIST -a" has returned an empty folder instead of a folder content. */ con->st &= ~AVOID_LIST_A; } else { /* Same data, so, better to take "LIST -a" that shows also hidden files/folders (when present) */ con->st |= LIST_AFTER_LIST_A_CHECK_DONE; con->st |= AVOID_LIST; con->st &= ~AVOID_LIST_A; DEBUGP (("LIST returned the same amount of data of " "\"LIST -a\": I will use \"LIST -a\" as standard " "list command\n")); } } } else { /* In this cycle "LIST -a" should being used. Is it true? */ if (list_a_used) { /* Yes, it is. OK, let's save the amount of data and try again with LIST */ previous_rd_size = rd_size; try_again = true; con->st |= AVOID_LIST_A; } else { /* No: something happens and LIST was used. This means "LIST -a" raises an error. */ con->st |= LIST_AFTER_LIST_A_CHECK_DONE; con->st |= AVOID_LIST_A; DEBUGP (("\"LIST -a\" failed: I will use \"LIST\" " "as standard list command\n")); } } } } } while (try_again); return RETRFINISHED; exit_error: /* If fp is a regular file, close and try to remove it */ if (fp && (!output_stream || con->cmd & DO_LIST)) fclose (fp); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Don't save user/pw with --xattr Also the Referer info is reduced to scheme+host+port. * src/ftp.c (getftp): Change params of set_file_metadata() * src/http.c (gethttp): Change params of set_file_metadata() * src/xattr.c (set_file_metadata): Remove user/password from origin URL, reduce Referer value to scheme/host/port. * src/xattr.h: Change prototype of set_file_metadata()'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy, struct iri *iri, int count) { struct request *req = NULL; char *type = NULL; char *user, *passwd; char *proxyauth; int statcode; int write_error; wgint contlen, contrange; struct url *conn; FILE *fp; int err; uerr_t retval; #ifdef HAVE_HSTS #ifdef TESTING /* we don't link against main.o when we're testing */ hsts_store_t hsts_store = NULL; #else extern hsts_store_t hsts_store; #endif const char *hsts_params; time_t max_age; bool include_subdomains; #endif int sock = -1; /* Set to 1 when the authorization has already been sent and should not be tried again. */ bool auth_finished = false; /* Set to 1 when just globally-set Basic authorization has been sent; * should prevent further Basic negotiations, but not other * mechanisms. */ bool basic_auth_finished = false; /* Whether NTLM authentication is used for this request. */ bool ntlm_seen = false; /* Whether our connection to the remote host is through SSL. */ bool using_ssl = false; /* Whether a HEAD request will be issued (as opposed to GET or POST). */ bool head_only = !!(*dt & HEAD_ONLY); /* Whether conditional get request will be issued. */ bool cond_get = !!(*dt & IF_MODIFIED_SINCE); #ifdef HAVE_METALINK /* Are we looking for metalink info in HTTP headers? */ bool metalink = !!(*dt & METALINK_METADATA); #endif char *head = NULL; struct response *resp = NULL; char hdrval[512]; char *message = NULL; /* Declare WARC variables. */ bool warc_enabled = (opt.warc_filename != NULL); FILE *warc_tmp = NULL; char warc_timestamp_str [21]; char warc_request_uuid [48]; ip_address *warc_ip = NULL; off_t warc_payload_offset = -1; /* Whether this connection will be kept alive after the HTTP request is done. */ bool keep_alive; /* Is the server using the chunked transfer encoding? */ bool chunked_transfer_encoding = false; /* Whether keep-alive should be inhibited. */ bool inhibit_keep_alive = !opt.http_keep_alive || opt.ignore_length; /* Headers sent when using POST. */ wgint body_data_size = 0; #ifdef HAVE_SSL if (u->scheme == SCHEME_HTTPS) { /* Initialize the SSL context. After this has once been done, it becomes a no-op. */ if (!ssl_init ()) { scheme_disable (SCHEME_HTTPS); logprintf (LOG_NOTQUIET, _("Disabling SSL due to encountered errors.\n")); retval = SSLINITFAILED; goto cleanup; } } #endif /* HAVE_SSL */ /* Initialize certain elements of struct http_stat. */ hs->len = 0; hs->contlen = -1; hs->res = -1; hs->rderrmsg = NULL; hs->newloc = NULL; xfree(hs->remote_time); hs->error = NULL; hs->message = NULL; conn = u; { uerr_t ret; req = initialize_request (u, hs, dt, proxy, inhibit_keep_alive, &basic_auth_finished, &body_data_size, &user, &passwd, &ret); if (req == NULL) { retval = ret; goto cleanup; } } retry_with_auth: /* We need to come back here when the initial attempt to retrieve without authorization header fails. (Expected to happen at least for the Digest authorization scheme.) */ if (opt.cookies) request_set_header (req, "Cookie", cookie_header (wget_cookie_jar, u->host, u->port, u->path, #ifdef HAVE_SSL u->scheme == SCHEME_HTTPS #else 0 #endif ), rel_value); /* Add the user headers. */ if (opt.user_headers) { int i; for (i = 0; opt.user_headers[i]; i++) request_set_user_header (req, opt.user_headers[i]); } proxyauth = NULL; if (proxy) { conn = proxy; initialize_proxy_configuration (u, req, proxy, &proxyauth); } keep_alive = true; /* Establish the connection. */ if (inhibit_keep_alive) keep_alive = false; { uerr_t conn_err = establish_connection (u, &conn, hs, proxy, &proxyauth, &req, &using_ssl, inhibit_keep_alive, &sock); if (conn_err != RETROK) { retval = conn_err; goto cleanup; } } /* Open the temporary file where we will write the request. */ if (warc_enabled) { warc_tmp = warc_tempfile (); if (warc_tmp == NULL) { CLOSE_INVALIDATE (sock); retval = WARC_TMP_FOPENERR; goto cleanup; } if (! proxy) { warc_ip = (ip_address *) alloca (sizeof (ip_address)); socket_ip_address (sock, warc_ip, ENDPOINT_PEER); } } /* Send the request to server. */ write_error = request_send (req, sock, warc_tmp); if (write_error >= 0) { if (opt.body_data) { DEBUGP (("[BODY data: %s]\n", opt.body_data)); write_error = fd_write (sock, opt.body_data, body_data_size, -1); if (write_error >= 0 && warc_tmp != NULL) { int warc_tmp_written; /* Remember end of headers / start of payload. */ warc_payload_offset = ftello (warc_tmp); /* Write a copy of the data to the WARC record. */ warc_tmp_written = fwrite (opt.body_data, 1, body_data_size, warc_tmp); if (warc_tmp_written != body_data_size) write_error = -2; } } else if (opt.body_file && body_data_size != 0) { if (warc_tmp != NULL) /* Remember end of headers / start of payload */ warc_payload_offset = ftello (warc_tmp); write_error = body_file_send (sock, opt.body_file, body_data_size, warc_tmp); } } if (write_error < 0) { CLOSE_INVALIDATE (sock); if (warc_tmp != NULL) fclose (warc_tmp); if (write_error == -2) retval = WARC_TMP_FWRITEERR; else retval = WRITEFAILED; goto cleanup; } logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "), proxy ? "Proxy" : "HTTP"); contlen = -1; contrange = 0; *dt &= ~RETROKF; if (warc_enabled) { bool warc_result; /* Generate a timestamp and uuid for this request. */ warc_timestamp (warc_timestamp_str, sizeof(warc_timestamp_str)); warc_uuid_str (warc_request_uuid); /* Create a request record and store it in the WARC file. */ warc_result = warc_write_request_record (u->url, warc_timestamp_str, warc_request_uuid, warc_ip, warc_tmp, warc_payload_offset); if (! warc_result) { CLOSE_INVALIDATE (sock); retval = WARC_ERR; goto cleanup; } /* warc_write_request_record has also closed warc_tmp. */ } /* Repeat while we receive a 10x response code. */ { bool _repeat; do { head = read_http_response_head (sock); if (!head) { if (errno == 0) { logputs (LOG_NOTQUIET, _("No data received.\n")); CLOSE_INVALIDATE (sock); retval = HEOF; } else { logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"), fd_errstr (sock)); CLOSE_INVALIDATE (sock); retval = HERR; } goto cleanup; } DEBUGP (("\n---response begin---\n%s---response end---\n", head)); resp = resp_new (head); /* Check for status line. */ xfree(message); statcode = resp_status (resp, &message); if (statcode < 0) { char *tms = datetime_str (time (NULL)); logprintf (LOG_VERBOSE, "%d\n", statcode); logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"), tms, statcode, quotearg_style (escape_quoting_style, _("Malformed status line"))); CLOSE_INVALIDATE (sock); retval = HERR; goto cleanup; } if (H_10X (statcode)) { xfree (head); resp_free (&resp); _repeat = true; DEBUGP (("Ignoring response\n")); } else { _repeat = false; } } while (_repeat); } xfree(hs->message); hs->message = xstrdup (message); if (!opt.server_response) logprintf (LOG_VERBOSE, "%2d %s\n", statcode, message ? quotearg_style (escape_quoting_style, message) : ""); else { logprintf (LOG_VERBOSE, "\n"); print_server_response (resp, " "); } if (!opt.ignore_length && resp_header_copy (resp, "Content-Length", hdrval, sizeof (hdrval))) { wgint parsed; errno = 0; parsed = str_to_wgint (hdrval, NULL, 10); if (parsed == WGINT_MAX && errno == ERANGE) { /* Out of range. #### If Content-Length is out of range, it most likely means that the file is larger than 2G and that we're compiled without LFS. In that case we should probably refuse to even attempt to download the file. */ contlen = -1; } else if (parsed < 0) { /* Negative Content-Length; nonsensical, so we can't assume any information about the content to receive. */ contlen = -1; } else contlen = parsed; } /* Check for keep-alive related responses. */ if (!inhibit_keep_alive) { if (resp_header_copy (resp, "Connection", hdrval, sizeof (hdrval))) { if (0 == c_strcasecmp (hdrval, "Close")) keep_alive = false; } } chunked_transfer_encoding = false; if (resp_header_copy (resp, "Transfer-Encoding", hdrval, sizeof (hdrval)) && 0 == c_strcasecmp (hdrval, "chunked")) chunked_transfer_encoding = true; /* Handle (possibly multiple instances of) the Set-Cookie header. */ if (opt.cookies) { int scpos; const char *scbeg, *scend; /* The jar should have been created by now. */ assert (wget_cookie_jar != NULL); for (scpos = 0; (scpos = resp_header_locate (resp, "Set-Cookie", scpos, &scbeg, &scend)) != -1; ++scpos) { char *set_cookie; BOUNDED_TO_ALLOCA (scbeg, scend, set_cookie); cookie_handle_set_cookie (wget_cookie_jar, u->host, u->port, u->path, set_cookie); } } if (keep_alive) /* The server has promised that it will not close the connection when we're done. This means that we can register it. */ register_persistent (conn->host, conn->port, sock, using_ssl); #ifdef HAVE_METALINK /* We need to check for the Metalink data in the very first response we get from the server (before redirectionrs, authorization, etc.). */ if (metalink) { hs->metalink = metalink_from_http (resp, hs, u); xfree (hs->message); retval = RETR_WITH_METALINK; CLOSE_FINISH (sock); goto cleanup; } #endif if (statcode == HTTP_STATUS_UNAUTHORIZED) { /* Authorization is required. */ uerr_t auth_err = RETROK; bool retry; /* Normally we are not interested in the response body. But if we are writing a WARC file we are: we like to keep everyting. */ if (warc_enabled) { int _err; type = resp_header_strdup (resp, "Content-Type"); _err = read_response_body (hs, sock, NULL, contlen, 0, chunked_transfer_encoding, u->url, warc_timestamp_str, warc_request_uuid, warc_ip, type, statcode, head); xfree (type); if (_err != RETRFINISHED || hs->res < 0) { CLOSE_INVALIDATE (sock); retval = _err; goto cleanup; } else CLOSE_FINISH (sock); } else { /* Since WARC is disabled, we are not interested in the response body. */ if (keep_alive && !head_only && skip_short_body (sock, contlen, chunked_transfer_encoding)) CLOSE_FINISH (sock); else CLOSE_INVALIDATE (sock); } pconn.authorized = false; { auth_err = check_auth (u, user, passwd, resp, req, &ntlm_seen, &retry, &basic_auth_finished, &auth_finished); if (auth_err == RETROK && retry) { xfree (hs->message); resp_free (&resp); xfree (message); xfree (head); goto retry_with_auth; } } if (auth_err == RETROK) retval = AUTHFAILED; else retval = auth_err; goto cleanup; } else /* statcode != HTTP_STATUS_UNAUTHORIZED */ { /* Kludge: if NTLM is used, mark the TCP connection as authorized. */ if (ntlm_seen) pconn.authorized = true; } if (statcode == HTTP_STATUS_GATEWAY_TIMEOUT) { hs->len = 0; hs->res = 0; hs->restval = 0; CLOSE_FINISH (sock); xfree (hs->message); retval = GATEWAYTIMEOUT; goto cleanup; } { uerr_t ret = check_file_output (u, hs, resp, hdrval, sizeof hdrval); if (ret != RETROK) { retval = ret; goto cleanup; } } hs->statcode = statcode; if (statcode == -1) hs->error = xstrdup (_("Malformed status line")); else if (!*message) hs->error = xstrdup (_("(no description)")); else hs->error = xstrdup (message); #ifdef HAVE_HSTS if (opt.hsts && hsts_store) { hsts_params = resp_header_strdup (resp, "Strict-Transport-Security"); if (parse_strict_transport_security (hsts_params, &max_age, &include_subdomains)) { /* process strict transport security */ if (hsts_store_entry (hsts_store, u->scheme, u->host, u->port, max_age, include_subdomains)) DEBUGP(("Added new HSTS host: %s:%u (max-age: %u, includeSubdomains: %s)\n", u->host, u->port, (unsigned int) max_age, (include_subdomains ? "true" : "false"))); else DEBUGP(("Updated HSTS host: %s:%u (max-age: %u, includeSubdomains: %s)\n", u->host, u->port, (unsigned int) max_age, (include_subdomains ? "true" : "false"))); } } #endif type = resp_header_strdup (resp, "Content-Type"); if (type) { char *tmp = strchr (type, ';'); if (tmp) { #ifdef ENABLE_IRI /* sXXXav: only needed if IRI support is enabled */ char *tmp2 = tmp + 1; #endif while (tmp > type && c_isspace (tmp[-1])) --tmp; *tmp = '\0'; #ifdef ENABLE_IRI /* Try to get remote encoding if needed */ if (opt.enable_iri && !opt.encoding_remote) { tmp = parse_charset (tmp2); if (tmp) set_content_encoding (iri, tmp); xfree(tmp); } #endif } } hs->newloc = resp_header_strdup (resp, "Location"); hs->remote_time = resp_header_strdup (resp, "Last-Modified"); if (resp_header_copy (resp, "Content-Range", hdrval, sizeof (hdrval))) { wgint first_byte_pos, last_byte_pos, entity_length; if (parse_content_range (hdrval, &first_byte_pos, &last_byte_pos, &entity_length)) { contrange = first_byte_pos; contlen = last_byte_pos - first_byte_pos + 1; } } /* 20x responses are counted among successful by default. */ if (H_20X (statcode)) *dt |= RETROKF; if (statcode == HTTP_STATUS_NO_CONTENT) { /* 204 response has no body (RFC 2616, 4.3) */ /* In case the caller cares to look... */ hs->len = 0; hs->res = 0; hs->restval = 0; CLOSE_FINISH (sock); retval = RETRFINISHED; goto cleanup; } /* Return if redirected. */ if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES) { /* RFC2068 says that in case of the 300 (multiple choices) response, the server can output a preferred URL through `Location' header; otherwise, the request should be treated like GET. So, if the location is set, it will be a redirection; otherwise, just proceed normally. */ if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc) *dt |= RETROKF; else { logprintf (LOG_VERBOSE, _("Location: %s%s\n"), hs->newloc ? escnonprint_uri (hs->newloc) : _("unspecified"), hs->newloc ? _(" [following]") : ""); /* In case the caller cares to look... */ hs->len = 0; hs->res = 0; hs->restval = 0; /* Normally we are not interested in the response body of a redirect. But if we are writing a WARC file we are: we like to keep everyting. */ if (warc_enabled) { int _err = read_response_body (hs, sock, NULL, contlen, 0, chunked_transfer_encoding, u->url, warc_timestamp_str, warc_request_uuid, warc_ip, type, statcode, head); if (_err != RETRFINISHED || hs->res < 0) { CLOSE_INVALIDATE (sock); retval = _err; goto cleanup; } else CLOSE_FINISH (sock); } else { /* Since WARC is disabled, we are not interested in the response body. */ if (keep_alive && !head_only && skip_short_body (sock, contlen, chunked_transfer_encoding)) CLOSE_FINISH (sock); else CLOSE_INVALIDATE (sock); } /* From RFC2616: The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client. A 307 should be redirected using the same method, in other words, a POST should be preserved and not converted to a GET in that case. With strict adherence to RFC2616, POST requests are not converted to a GET request on 301 Permanent Redirect or 302 Temporary Redirect. A switch may be provided later based on the HTTPbis draft that allows clients to convert POST requests to GET requests on 301 and 302 response codes. */ switch (statcode) { case HTTP_STATUS_TEMPORARY_REDIRECT: retval = NEWLOCATION_KEEP_POST; goto cleanup; case HTTP_STATUS_MOVED_PERMANENTLY: if (opt.method && c_strcasecmp (opt.method, "post") != 0) { retval = NEWLOCATION_KEEP_POST; goto cleanup; } break; case HTTP_STATUS_MOVED_TEMPORARILY: if (opt.method && c_strcasecmp (opt.method, "post") != 0) { retval = NEWLOCATION_KEEP_POST; goto cleanup; } break; } retval = NEWLOCATION; goto cleanup; } } set_content_type (dt, type); if (opt.adjust_extension) { if (*dt & TEXTHTML) /* -E / --adjust-extension / adjust_extension = on was specified, and this is a text/html file. If some case-insensitive variation on ".htm[l]" isn't already the file's suffix, tack on ".html". */ { ensure_extension (hs, ".html", dt); } else if (*dt & TEXTCSS) { ensure_extension (hs, ".css", dt); } } if (cond_get) { if (statcode == HTTP_STATUS_NOT_MODIFIED) { logprintf (LOG_VERBOSE, _("File %s not modified on server. Omitting download.\n\n"), quote (hs->local_file)); *dt |= RETROKF; CLOSE_FINISH (sock); retval = RETRUNNEEDED; goto cleanup; } /* Handle the case when server ignores If-Modified-Since header. */ else if (statcode == HTTP_STATUS_OK && hs->remote_time) { time_t tmr = http_atotm (hs->remote_time); /* Check if the local file is up-to-date based on Last-Modified header and content length. */ if (tmr != (time_t) - 1 && tmr <= hs->orig_file_tstamp && (contlen == -1 || contlen == hs->orig_file_size)) { logprintf (LOG_VERBOSE, _("Server ignored If-Modified-Since header for file %s.\n" "You might want to add --no-if-modified-since option." "\n\n"), quote (hs->local_file)); *dt |= RETROKF; CLOSE_INVALIDATE (sock); retval = RETRUNNEEDED; goto cleanup; } } } if (statcode == HTTP_STATUS_RANGE_NOT_SATISFIABLE || (!opt.timestamping && hs->restval > 0 && statcode == HTTP_STATUS_OK && contrange == 0 && contlen >= 0 && hs->restval >= contlen)) { /* If `-c' is in use and the file has been fully downloaded (or the remote file has shrunk), Wget effectively requests bytes after the end of file and the server response with 416 (or 200 with a <= Content-Length. */ logputs (LOG_VERBOSE, _("\ \n The file is already fully retrieved; nothing to do.\n\n")); /* In case the caller inspects. */ hs->len = contlen; hs->res = 0; /* Mark as successfully retrieved. */ *dt |= RETROKF; if (statcode == HTTP_STATUS_RANGE_NOT_SATISFIABLE) CLOSE_FINISH (sock); else CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there might be more bytes in the body. */ retval = RETRUNNEEDED; goto cleanup; } if ((contrange != 0 && contrange != hs->restval) || (H_PARTIAL (statcode) && !contrange)) { /* The Range request was somehow misunderstood by the server. Bail out. */ CLOSE_INVALIDATE (sock); retval = RANGEERR; goto cleanup; } if (contlen == -1) hs->contlen = -1; else hs->contlen = contlen + contrange; if (opt.verbose) { if (*dt & RETROKF) { /* No need to print this output if the body won't be downloaded at all, or if the original server response is printed. */ logputs (LOG_VERBOSE, _("Length: ")); if (contlen != -1) { logputs (LOG_VERBOSE, number_to_static_string (contlen + contrange)); if (contlen + contrange >= 1024) logprintf (LOG_VERBOSE, " (%s)", human_readable (contlen + contrange, 10, 1)); if (contrange) { if (contlen >= 1024) logprintf (LOG_VERBOSE, _(", %s (%s) remaining"), number_to_static_string (contlen), human_readable (contlen, 10, 1)); else logprintf (LOG_VERBOSE, _(", %s remaining"), number_to_static_string (contlen)); } } else logputs (LOG_VERBOSE, opt.ignore_length ? _("ignored") : _("unspecified")); if (type) logprintf (LOG_VERBOSE, " [%s]\n", quotearg_style (escape_quoting_style, type)); else logputs (LOG_VERBOSE, "\n"); } } /* Return if we have no intention of further downloading. */ if ((!(*dt & RETROKF) && !opt.content_on_error) || head_only || (opt.spider && !opt.recursive)) { /* In case the caller cares to look... */ hs->len = 0; hs->res = 0; hs->restval = 0; /* Normally we are not interested in the response body of a error responses. But if we are writing a WARC file we are: we like to keep everything. */ if (warc_enabled) { int _err = read_response_body (hs, sock, NULL, contlen, 0, chunked_transfer_encoding, u->url, warc_timestamp_str, warc_request_uuid, warc_ip, type, statcode, head); if (_err != RETRFINISHED || hs->res < 0) { CLOSE_INVALIDATE (sock); retval = _err; goto cleanup; } else CLOSE_FINISH (sock); } else { /* Since WARC is disabled, we are not interested in the response body. */ if (head_only) /* Pre-1.10 Wget used CLOSE_INVALIDATE here. Now we trust the servers not to send body in response to a HEAD request, and those that do will likely be caught by test_socket_open. If not, they can be worked around using `--no-http-keep-alive'. */ CLOSE_FINISH (sock); else if (opt.spider && !opt.recursive) /* we just want to see if the page exists - no downloading required */ CLOSE_INVALIDATE (sock); else if (keep_alive && skip_short_body (sock, contlen, chunked_transfer_encoding)) /* Successfully skipped the body; also keep using the socket. */ CLOSE_FINISH (sock); else CLOSE_INVALIDATE (sock); } retval = RETRFINISHED; goto cleanup; } err = open_output_stream (hs, count, &fp); if (err != RETROK) { CLOSE_INVALIDATE (sock); retval = err; goto cleanup; } err = read_response_body (hs, sock, fp, contlen, contrange, chunked_transfer_encoding, u->url, warc_timestamp_str, warc_request_uuid, warc_ip, type, statcode, head); if (hs->res >= 0) CLOSE_FINISH (sock); else CLOSE_INVALIDATE (sock); if (!output_stream) fclose (fp); retval = err; cleanup: xfree (head); xfree (type); xfree (message); resp_free (&resp); request_free (&req); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Keep fetched URLs in POSIX extended attributes * configure.ac: Check for xattr availability * src/Makefile.am: Add xattr.c * src/ftp.c: Include xattr.h. (getftp): Set attributes if enabled. * src/http.c: Include xattr.h. (gethttp): Add parameter 'original_url', set attributes if enabled. (http_loop): Add 'original_url' to call of gethttp(). * src/init.c: Add new option --xattr. * src/main.c: Add new option --xattr, add description to help text. * src/options.h: Add new config member 'enable_xattr'. * src/xatrr.c: New file. * src/xattr.h: New file. These attributes provide a lightweight method of later determining where a file was downloaded from. This patch changes: * autoconf detects whether extended attributes are available and enables the code if they are. * The new flags --xattr and --no-xattr control whether xattr is enabled. * The new command "xattr = (on|off)" can be used in ~/.wgetrc or /etc/wgetrc * The original and redirected URLs are recorded as shown below. * This works for both single fetches and recursive mode. The attributes that are set are: user.xdg.origin.url: The URL that the content was fetched from. user.xdg.referrer.url: The URL that was originally requested. Here is an example, where http://archive.org redirects to https://archive.org: $ wget --xattr http://archive.org ... $ getfattr -d index.html user.xdg.origin.url="https://archive.org/" user.xdg.referrer.url="http://archive.org/" These attributes were chosen based on those stored by Google Chrome https://bugs.chromium.org/p/chromium/issues/detail?id=45903 and curl https://github.com/curl/curl/blob/master/src/tool_xattr.c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: defaults (void) { char *tmp; /* Most of the default values are 0 (and 0.0, NULL, and false). Just reset everything, and fill in the non-zero values. Note that initializing pointers to NULL this way is technically illegal, but porting Wget to a machine where NULL is not all-zero bit pattern will be the least of the implementors' worries. */ xzero (opt); opt.cookies = true; opt.verbose = -1; opt.ntry = 20; opt.reclevel = 5; opt.add_hostdir = true; opt.netrc = true; opt.ftp_glob = true; opt.htmlify = true; opt.http_keep_alive = true; opt.use_proxy = true; opt.convert_file_only = false; tmp = getenv ("no_proxy"); if (tmp) opt.no_proxy = sepstring (tmp); opt.prefer_family = prefer_none; opt.allow_cache = true; opt.if_modified_since = true; opt.read_timeout = 900; opt.use_robots = true; opt.remove_listing = true; opt.dot_bytes = 1024; opt.dot_spacing = 10; opt.dots_in_line = 50; opt.dns_cache = true; opt.ftp_pasv = true; /* 2014-09-07 Darshit Shah <[email protected]> * opt.retr_symlinks is set to true by default. Creating symbolic links on the * local filesystem pose a security threat by malicious FTP Servers that * server a specially crafted .listing file akin to this: * * lrwxrwxrwx 1 root root 33 Dec 25 2012 JoCxl6d8rFU -> / * drwxrwxr-x 15 1024 106 4096 Aug 28 02:02 JoCxl6d8rFU * * A .listing file in this fashion makes Wget susceptiple to a symlink attack * wherein the attacker is able to create arbitrary files, directories and * symbolic links on the target system and even set permissions. * * Hence, by default Wget attempts to retrieve the pointed-to files and does * not create the symbolic links locally. */ opt.retr_symlinks = true; #ifdef HAVE_SSL opt.check_cert = CHECK_CERT_ON; opt.ftps_resume_ssl = true; opt.ftps_fallback_to_ftp = false; opt.ftps_implicit = false; opt.ftps_clear_data_connection = false; #endif /* The default for file name restriction defaults to the OS type. */ #if defined(WINDOWS) || defined(MSDOS) || defined(__CYGWIN__) opt.restrict_files_os = restrict_windows; #elif defined(__VMS) opt.restrict_files_os = restrict_vms; #else opt.restrict_files_os = restrict_unix; #endif opt.restrict_files_ctrl = true; opt.restrict_files_nonascii = false; opt.restrict_files_case = restrict_no_case_restriction; opt.regex_type = regex_type_posix; opt.max_redirect = 20; opt.waitretry = 10; #ifdef ENABLE_IRI opt.enable_iri = true; #else opt.enable_iri = false; #endif opt.locale = NULL; opt.encoding_remote = NULL; opt.useservertimestamps = true; opt.show_all_dns_entries = false; opt.warc_maxsize = 0; /* 1024 * 1024 * 1024; */ #ifdef HAVE_LIBZ opt.warc_compression_enabled = true; #else opt.warc_compression_enabled = false; #endif opt.warc_digests_enabled = true; opt.warc_cdx_enabled = false; opt.warc_cdx_dedup_filename = NULL; opt.warc_tempdir = NULL; opt.warc_keep_log = true; /* Use a negative value to mark the absence of --start-pos option */ opt.start_pos = -1; opt.show_progress = -1; opt.noscroll = false; #ifdef HAVE_HSTS /* HSTS is enabled by default */ opt.hsts = true; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Keep fetched URLs in POSIX extended attributes * configure.ac: Check for xattr availability * src/Makefile.am: Add xattr.c * src/ftp.c: Include xattr.h. (getftp): Set attributes if enabled. * src/http.c: Include xattr.h. (gethttp): Add parameter 'original_url', set attributes if enabled. (http_loop): Add 'original_url' to call of gethttp(). * src/init.c: Add new option --xattr. * src/main.c: Add new option --xattr, add description to help text. * src/options.h: Add new config member 'enable_xattr'. * src/xatrr.c: New file. * src/xattr.h: New file. These attributes provide a lightweight method of later determining where a file was downloaded from. This patch changes: * autoconf detects whether extended attributes are available and enables the code if they are. * The new flags --xattr and --no-xattr control whether xattr is enabled. * The new command "xattr = (on|off)" can be used in ~/.wgetrc or /etc/wgetrc * The original and redirected URLs are recorded as shown below. * This works for both single fetches and recursive mode. The attributes that are set are: user.xdg.origin.url: The URL that the content was fetched from. user.xdg.referrer.url: The URL that was originally requested. Here is an example, where http://archive.org redirects to https://archive.org: $ wget --xattr http://archive.org ... $ getfattr -d index.html user.xdg.origin.url="https://archive.org/" user.xdg.referrer.url="http://archive.org/" These attributes were chosen based on those stored by Google Chrome https://bugs.chromium.org/p/chromium/issues/detail?id=45903 and curl https://github.com/curl/curl/blob/master/src/tool_xattr.c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int h2c_decode_headers(struct h2c *h2c, struct buffer *rxbuf, uint32_t *flags) { const uint8_t *hdrs = (uint8_t *)b_head(&h2c->dbuf); struct buffer *tmp = get_trash_chunk(); struct http_hdr list[MAX_HTTP_HDR * 2]; struct buffer *copy = NULL; unsigned int msgf; struct htx *htx = NULL; int flen; // header frame len int hole = 0; int ret = 0; int outlen; int wrap; int try = 0; next_frame: if (b_data(&h2c->dbuf) - hole < h2c->dfl) goto leave; // incomplete input frame /* No END_HEADERS means there's one or more CONTINUATION frames. In * this case, we'll try to paste it immediately after the initial * HEADERS frame payload and kill any possible padding. The initial * frame's length will be increased to represent the concatenation * of the two frames. The next frame is read from position <tlen> * and written at position <flen> (minus padding if some is present). */ if (unlikely(!(h2c->dff & H2_F_HEADERS_END_HEADERS))) { struct h2_fh hdr; int clen; // CONTINUATION frame's payload length if (!h2_peek_frame_hdr(&h2c->dbuf, h2c->dfl + hole, &hdr)) { /* no more data, the buffer may be full, either due to * too large a frame or because of too large a hole that * we're going to compact at the end. */ goto leave; } if (hdr.ft != H2_FT_CONTINUATION) { /* RFC7540#6.10: frame of unexpected type */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); goto fail; } if (hdr.sid != h2c->dsi) { /* RFC7540#6.10: frame of different stream */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); goto fail; } if ((unsigned)hdr.len > (unsigned)global.tune.bufsize) { /* RFC7540#4.2: invalid frame length */ h2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR); goto fail; } /* detect when we must stop aggragating frames */ h2c->dff |= hdr.ff & H2_F_HEADERS_END_HEADERS; /* Take as much as we can of the CONTINUATION frame's payload */ clen = b_data(&h2c->dbuf) - (h2c->dfl + hole + 9); if (clen > hdr.len) clen = hdr.len; /* Move the frame's payload over the padding, hole and frame * header. At least one of hole or dpl is null (see diagrams * above). The hole moves after the new aggragated frame. */ b_move(&h2c->dbuf, b_peek_ofs(&h2c->dbuf, h2c->dfl + hole + 9), clen, -(h2c->dpl + hole + 9)); h2c->dfl += clen - h2c->dpl; hole += h2c->dpl + 9; h2c->dpl = 0; goto next_frame; } flen = h2c->dfl - h2c->dpl; /* if the input buffer wraps, take a temporary copy of it (rare) */ wrap = b_wrap(&h2c->dbuf) - b_head(&h2c->dbuf); if (wrap < h2c->dfl) { copy = alloc_trash_chunk(); if (!copy) { h2c_error(h2c, H2_ERR_INTERNAL_ERROR); goto fail; } memcpy(copy->area, b_head(&h2c->dbuf), wrap); memcpy(copy->area + wrap, b_orig(&h2c->dbuf), h2c->dfl - wrap); hdrs = (uint8_t *) copy->area; } /* Skip StreamDep and weight for now (we don't support PRIORITY) */ if (h2c->dff & H2_F_HEADERS_PRIORITY) { if (read_n32(hdrs) == h2c->dsi) { /* RFC7540#5.3.1 : stream dep may not depend on itself */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); goto fail; } hdrs += 5; // stream dep = 4, weight = 1 flen -= 5; } if (!h2_get_buf(h2c, rxbuf)) { h2c->flags |= H2_CF_DEM_SALLOC; goto leave; } /* we can't retry a failed decompression operation so we must be very * careful not to take any risks. In practice the output buffer is * always empty except maybe for trailers, in which case we simply have * to wait for the upper layer to finish consuming what is available. */ if (h2c->proxy->options2 & PR_O2_USE_HTX) { htx = htx_from_buf(rxbuf); if (!htx_is_empty(htx)) { h2c->flags |= H2_CF_DEM_SFULL; goto leave; } } else { if (b_data(rxbuf)) { h2c->flags |= H2_CF_DEM_SFULL; goto leave; } rxbuf->head = 0; try = b_size(rxbuf); } /* past this point we cannot roll back in case of error */ outlen = hpack_decode_frame(h2c->ddht, hdrs, flen, list, sizeof(list)/sizeof(list[0]), tmp); if (outlen < 0) { h2c_error(h2c, H2_ERR_COMPRESSION_ERROR); goto fail; } /* The PACK decompressor was updated, let's update the input buffer and * the parser's state to commit these changes and allow us to later * fail solely on the stream if needed. */ b_del(&h2c->dbuf, h2c->dfl + hole); h2c->dfl = hole = 0; h2c->st0 = H2_CS_FRAME_H; /* OK now we have our header list in <list> */ msgf = (h2c->dff & H2_F_HEADERS_END_STREAM) ? 0 : H2_MSGF_BODY; if (*flags & H2_SF_HEADERS_RCVD) goto trailers; /* This is the first HEADERS frame so it's a headers block */ if (htx) { /* HTX mode */ if (h2c->flags & H2_CF_IS_BACK) outlen = h2_make_htx_response(list, htx, &msgf); else outlen = h2_make_htx_request(list, htx, &msgf); } else { /* HTTP/1 mode */ outlen = h2_make_h1_request(list, b_tail(rxbuf), try, &msgf); if (outlen > 0) b_add(rxbuf, outlen); } if (outlen < 0) { /* too large headers? this is a stream error only */ goto fail; } if (msgf & H2_MSGF_BODY) { /* a payload is present */ if (msgf & H2_MSGF_BODY_CL) *flags |= H2_SF_DATA_CLEN; else if (!(msgf & H2_MSGF_BODY_TUNNEL) && !htx) *flags |= H2_SF_DATA_CHNK; } done: /* indicate that a HEADERS frame was received for this stream */ *flags |= H2_SF_HEADERS_RCVD; if (h2c->dff & H2_F_HEADERS_END_STREAM) { /* Mark the end of message, either using EOM in HTX or with the * trailing CRLF after the end of trailers. Note that DATA_CHNK * is not set during headers with END_STREAM. */ if (htx) { if (!htx_add_endof(htx, HTX_BLK_EOM)) goto fail; } else if (*flags & H2_SF_DATA_CHNK) { if (!b_putblk(rxbuf, "\r\n", 2)) goto fail; } } /* success */ ret = 1; leave: /* If there is a hole left and it's not at the end, we are forced to * move the remaining data over it. */ if (hole) { if (b_data(&h2c->dbuf) > h2c->dfl + hole) b_move(&h2c->dbuf, b_peek_ofs(&h2c->dbuf, h2c->dfl + hole), b_data(&h2c->dbuf) - (h2c->dfl + hole), -hole); b_sub(&h2c->dbuf, hole); } if (b_full(&h2c->dbuf) && h2c->dfl > b_data(&h2c->dbuf)) { /* too large frames */ h2c_error(h2c, H2_ERR_INTERNAL_ERROR); ret = -1; } if (htx) htx_to_buf(htx, rxbuf); free_trash_chunk(copy); return ret; fail: ret = -1; goto leave; trailers: /* This is the last HEADERS frame hence a trailer */ if (!(h2c->dff & H2_F_HEADERS_END_STREAM)) { /* It's a trailer but it's missing ES flag */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); goto fail; } /* Trailers terminate a DATA sequence. In HTX we have to emit an EOD * block, and when using chunks we must send the 0 CRLF marker. For * other modes, the trailers are silently dropped. */ if (htx) { if (!htx_add_endof(htx, HTX_BLK_EOD)) goto fail; if (h2_make_htx_trailers(list, htx) <= 0) goto fail; } else if (*flags & H2_SF_DATA_CHNK) { /* Legacy mode with chunked encoding : we must finalize the * data block message emit the trailing CRLF */ if (!b_putblk(rxbuf, "0\r\n", 3)) goto fail; outlen = h2_make_h1_trailers(list, b_tail(rxbuf), try); if (outlen > 0) b_add(rxbuf, outlen); else goto fail; } goto done; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'BUG/CRITICAL: mux-h2: re-check the frame length when PRIORITY is used Tim D�sterhus reported a possible crash in the H2 HEADERS frame decoder when the PRIORITY flag is present. A check is missing to ensure the 5 extra bytes needed with this flag are actually part of the frame. As per RFC7540#4.2, let's return a connection error with code FRAME_SIZE_ERROR. Many thanks to Tim for responsibly reporting this issue with a working config and reproducer. This issue was assigned CVE-2018-20615. This fix must be backported to 1.9 and 1.8.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int l2cap_parse_conf_req(struct l2cap_chan *chan, void *data, size_t data_size) { struct l2cap_conf_rsp *rsp = data; void *ptr = rsp->data; void *endptr = data + data_size; void *req = chan->conf_req; int len = chan->conf_len; int type, hint, olen; unsigned long val; struct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC }; struct l2cap_conf_efs efs; u8 remote_efs = 0; u16 mtu = L2CAP_DEFAULT_MTU; u16 result = L2CAP_CONF_SUCCESS; u16 size; BT_DBG("chan %p", chan); while (len >= L2CAP_CONF_OPT_SIZE) { len -= l2cap_get_conf_opt(&req, &type, &olen, &val); hint = type & L2CAP_CONF_HINT; type &= L2CAP_CONF_MASK; switch (type) { case L2CAP_CONF_MTU: if (olen != 2) break; mtu = val; break; case L2CAP_CONF_FLUSH_TO: if (olen != 2) break; chan->flush_to = val; break; case L2CAP_CONF_QOS: break; case L2CAP_CONF_RFC: if (olen != sizeof(rfc)) break; memcpy(&rfc, (void *) val, olen); break; case L2CAP_CONF_FCS: if (olen != 1) break; if (val == L2CAP_FCS_NONE) set_bit(CONF_RECV_NO_FCS, &chan->conf_state); break; case L2CAP_CONF_EFS: if (olen != sizeof(efs)) break; remote_efs = 1; memcpy(&efs, (void *) val, olen); break; case L2CAP_CONF_EWS: if (olen != 2) break; if (!(chan->conn->local_fixed_chan & L2CAP_FC_A2MP)) return -ECONNREFUSED; set_bit(FLAG_EXT_CTRL, &chan->flags); set_bit(CONF_EWS_RECV, &chan->conf_state); chan->tx_win_max = L2CAP_DEFAULT_EXT_WINDOW; chan->remote_tx_win = val; break; default: if (hint) break; result = L2CAP_CONF_UNKNOWN; *((u8 *) ptr++) = type; break; } } if (chan->num_conf_rsp || chan->num_conf_req > 1) goto done; switch (chan->mode) { case L2CAP_MODE_STREAMING: case L2CAP_MODE_ERTM: if (!test_bit(CONF_STATE2_DEVICE, &chan->conf_state)) { chan->mode = l2cap_select_mode(rfc.mode, chan->conn->feat_mask); break; } if (remote_efs) { if (__l2cap_efs_supported(chan->conn)) set_bit(FLAG_EFS_ENABLE, &chan->flags); else return -ECONNREFUSED; } if (chan->mode != rfc.mode) return -ECONNREFUSED; break; } done: if (chan->mode != rfc.mode) { result = L2CAP_CONF_UNACCEPT; rfc.mode = chan->mode; if (chan->num_conf_rsp == 1) return -ECONNREFUSED; l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc), (unsigned long) &rfc, endptr - ptr); } if (result == L2CAP_CONF_SUCCESS) { /* Configure output options and let the other side know * which ones we don't like. */ if (mtu < L2CAP_DEFAULT_MIN_MTU) result = L2CAP_CONF_UNACCEPT; else { chan->omtu = mtu; set_bit(CONF_MTU_DONE, &chan->conf_state); } l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, chan->omtu, endptr - ptr); if (remote_efs) { if (chan->local_stype != L2CAP_SERV_NOTRAFIC && efs.stype != L2CAP_SERV_NOTRAFIC && efs.stype != chan->local_stype) { result = L2CAP_CONF_UNACCEPT; if (chan->num_conf_req >= 1) return -ECONNREFUSED; l2cap_add_conf_opt(&ptr, L2CAP_CONF_EFS, sizeof(efs), (unsigned long) &efs, endptr - ptr); } else { /* Send PENDING Conf Rsp */ result = L2CAP_CONF_PENDING; set_bit(CONF_LOC_CONF_PEND, &chan->conf_state); } } switch (rfc.mode) { case L2CAP_MODE_BASIC: chan->fcs = L2CAP_FCS_NONE; set_bit(CONF_MODE_DONE, &chan->conf_state); break; case L2CAP_MODE_ERTM: if (!test_bit(CONF_EWS_RECV, &chan->conf_state)) chan->remote_tx_win = rfc.txwin_size; else rfc.txwin_size = L2CAP_DEFAULT_TX_WINDOW; chan->remote_max_tx = rfc.max_transmit; size = min_t(u16, le16_to_cpu(rfc.max_pdu_size), chan->conn->mtu - L2CAP_EXT_HDR_SIZE - L2CAP_SDULEN_SIZE - L2CAP_FCS_SIZE); rfc.max_pdu_size = cpu_to_le16(size); chan->remote_mps = size; __l2cap_set_ertm_timeouts(chan, &rfc); set_bit(CONF_MODE_DONE, &chan->conf_state); l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc), (unsigned long) &rfc, endptr - ptr); if (test_bit(FLAG_EFS_ENABLE, &chan->flags)) { chan->remote_id = efs.id; chan->remote_stype = efs.stype; chan->remote_msdu = le16_to_cpu(efs.msdu); chan->remote_flush_to = le32_to_cpu(efs.flush_to); chan->remote_acc_lat = le32_to_cpu(efs.acc_lat); chan->remote_sdu_itime = le32_to_cpu(efs.sdu_itime); l2cap_add_conf_opt(&ptr, L2CAP_CONF_EFS, sizeof(efs), (unsigned long) &efs, endptr - ptr); } break; case L2CAP_MODE_STREAMING: size = min_t(u16, le16_to_cpu(rfc.max_pdu_size), chan->conn->mtu - L2CAP_EXT_HDR_SIZE - L2CAP_SDULEN_SIZE - L2CAP_FCS_SIZE); rfc.max_pdu_size = cpu_to_le16(size); chan->remote_mps = size; set_bit(CONF_MODE_DONE, &chan->conf_state); l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc), (unsigned long) &rfc, endptr - ptr); break; default: result = L2CAP_CONF_UNACCEPT; memset(&rfc, 0, sizeof(rfc)); rfc.mode = chan->mode; } if (result == L2CAP_CONF_SUCCESS) set_bit(CONF_OUTPUT_DONE, &chan->conf_state); } rsp->scid = cpu_to_le16(chan->dcid); rsp->result = cpu_to_le16(result); rsp->flags = cpu_to_le16(0); return ptr - data; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Bluetooth: Verify that l2cap_get_conf_opt provides large enough buffer The function l2cap_get_conf_opt will return L2CAP_CONF_OPT_SIZE + opt->len as length value. The opt->len however is in control over the remote user and can be used by an attacker to gain access beyond the bounds of the actual packet. To prevent any potential leak of heap memory, it is enough to check that the resulting len calculation after calling l2cap_get_conf_opt is not below zero. A well formed packet will always return >= 0 here and will end with the length value being zero after the last option has been parsed. In case of malformed packets messing with the opt->len field the length value will become negative. If that is the case, then just abort and ignore the option. In case an attacker uses a too short opt->len value, then garbage will be parsed, but that is protected by the unknown option handling and also the option parameter size checks. Signed-off-by: Marcel Holtmann <[email protected]> Reviewed-by: Greg Kroah-Hartman <[email protected]> Signed-off-by: Johan Hedberg <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int l2cap_parse_conf_rsp(struct l2cap_chan *chan, void *rsp, int len, void *data, size_t size, u16 *result) { struct l2cap_conf_req *req = data; void *ptr = req->data; void *endptr = data + size; int type, olen; unsigned long val; struct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC }; struct l2cap_conf_efs efs; BT_DBG("chan %p, rsp %p, len %d, req %p", chan, rsp, len, data); while (len >= L2CAP_CONF_OPT_SIZE) { len -= l2cap_get_conf_opt(&rsp, &type, &olen, &val); switch (type) { case L2CAP_CONF_MTU: if (olen != 2) break; if (val < L2CAP_DEFAULT_MIN_MTU) { *result = L2CAP_CONF_UNACCEPT; chan->imtu = L2CAP_DEFAULT_MIN_MTU; } else chan->imtu = val; l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, chan->imtu, endptr - ptr); break; case L2CAP_CONF_FLUSH_TO: if (olen != 2) break; chan->flush_to = val; l2cap_add_conf_opt(&ptr, L2CAP_CONF_FLUSH_TO, 2, chan->flush_to, endptr - ptr); break; case L2CAP_CONF_RFC: if (olen != sizeof(rfc)) break; memcpy(&rfc, (void *)val, olen); if (test_bit(CONF_STATE2_DEVICE, &chan->conf_state) && rfc.mode != chan->mode) return -ECONNREFUSED; chan->fcs = 0; l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc), (unsigned long) &rfc, endptr - ptr); break; case L2CAP_CONF_EWS: if (olen != 2) break; chan->ack_win = min_t(u16, val, chan->ack_win); l2cap_add_conf_opt(&ptr, L2CAP_CONF_EWS, 2, chan->tx_win, endptr - ptr); break; case L2CAP_CONF_EFS: if (olen != sizeof(efs)) break; memcpy(&efs, (void *)val, olen); if (chan->local_stype != L2CAP_SERV_NOTRAFIC && efs.stype != L2CAP_SERV_NOTRAFIC && efs.stype != chan->local_stype) return -ECONNREFUSED; l2cap_add_conf_opt(&ptr, L2CAP_CONF_EFS, sizeof(efs), (unsigned long) &efs, endptr - ptr); break; case L2CAP_CONF_FCS: if (olen != 1) break; if (*result == L2CAP_CONF_PENDING) if (val == L2CAP_FCS_NONE) set_bit(CONF_RECV_NO_FCS, &chan->conf_state); break; } } if (chan->mode == L2CAP_MODE_BASIC && chan->mode != rfc.mode) return -ECONNREFUSED; chan->mode = rfc.mode; if (*result == L2CAP_CONF_SUCCESS || *result == L2CAP_CONF_PENDING) { switch (rfc.mode) { case L2CAP_MODE_ERTM: chan->retrans_timeout = le16_to_cpu(rfc.retrans_timeout); chan->monitor_timeout = le16_to_cpu(rfc.monitor_timeout); chan->mps = le16_to_cpu(rfc.max_pdu_size); if (!test_bit(FLAG_EXT_CTRL, &chan->flags)) chan->ack_win = min_t(u16, chan->ack_win, rfc.txwin_size); if (test_bit(FLAG_EFS_ENABLE, &chan->flags)) { chan->local_msdu = le16_to_cpu(efs.msdu); chan->local_sdu_itime = le32_to_cpu(efs.sdu_itime); chan->local_acc_lat = le32_to_cpu(efs.acc_lat); chan->local_flush_to = le32_to_cpu(efs.flush_to); } break; case L2CAP_MODE_STREAMING: chan->mps = le16_to_cpu(rfc.max_pdu_size); } } req->dcid = cpu_to_le16(chan->dcid); req->flags = cpu_to_le16(0); return ptr - data; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Bluetooth: Verify that l2cap_get_conf_opt provides large enough buffer The function l2cap_get_conf_opt will return L2CAP_CONF_OPT_SIZE + opt->len as length value. The opt->len however is in control over the remote user and can be used by an attacker to gain access beyond the bounds of the actual packet. To prevent any potential leak of heap memory, it is enough to check that the resulting len calculation after calling l2cap_get_conf_opt is not below zero. A well formed packet will always return >= 0 here and will end with the length value being zero after the last option has been parsed. In case of malformed packets messing with the opt->len field the length value will become negative. If that is the case, then just abort and ignore the option. In case an attacker uses a too short opt->len value, then garbage will be parsed, but that is protected by the unknown option handling and also the option parameter size checks. Signed-off-by: Marcel Holtmann <[email protected]> Reviewed-by: Greg Kroah-Hartman <[email protected]> Signed-off-by: Johan Hedberg <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: exif_data_load_data_content (ExifData *data, ExifIfd ifd, const unsigned char *d, unsigned int ds, unsigned int offset, unsigned int recursion_depth) { ExifLong o, thumbnail_offset = 0, thumbnail_length = 0; ExifShort n; ExifEntry *entry; unsigned int i; ExifTag tag; if (!data || !data->priv) return; /* check for valid ExifIfd enum range */ if ((((int)ifd) < 0) || ( ((int)ifd) >= EXIF_IFD_COUNT)) return; if (recursion_depth > 12) { exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", "Deep recursion detected!"); return; } /* Read the number of entries */ if ((offset + 2 < offset) || (offset + 2 < 2) || (offset + 2 > ds)) { exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", "Tag data past end of buffer (%u > %u)", offset+2, ds); return; } n = exif_get_short (d + offset, data->priv->order); exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Loading %hu entries...", n); offset += 2; /* Check if we have enough data. */ if (offset + 12 * n > ds) { n = (ds - offset) / 12; exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Short data; only loading %hu entries...", n); } for (i = 0; i < n; i++) { tag = exif_get_short (d + offset + 12 * i, data->priv->order); switch (tag) { case EXIF_TAG_EXIF_IFD_POINTER: case EXIF_TAG_GPS_INFO_IFD_POINTER: case EXIF_TAG_INTEROPERABILITY_IFD_POINTER: case EXIF_TAG_JPEG_INTERCHANGE_FORMAT_LENGTH: case EXIF_TAG_JPEG_INTERCHANGE_FORMAT: o = exif_get_long (d + offset + 12 * i + 8, data->priv->order); /* FIXME: IFD_POINTER tags aren't marked as being in a * specific IFD, so exif_tag_get_name_in_ifd won't work */ exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Sub-IFD entry 0x%x ('%s') at %u.", tag, exif_tag_get_name(tag), o); switch (tag) { case EXIF_TAG_EXIF_IFD_POINTER: CHECK_REC (EXIF_IFD_EXIF); exif_data_load_data_content (data, EXIF_IFD_EXIF, d, ds, o, recursion_depth + 1); break; case EXIF_TAG_GPS_INFO_IFD_POINTER: CHECK_REC (EXIF_IFD_GPS); exif_data_load_data_content (data, EXIF_IFD_GPS, d, ds, o, recursion_depth + 1); break; case EXIF_TAG_INTEROPERABILITY_IFD_POINTER: CHECK_REC (EXIF_IFD_INTEROPERABILITY); exif_data_load_data_content (data, EXIF_IFD_INTEROPERABILITY, d, ds, o, recursion_depth + 1); break; case EXIF_TAG_JPEG_INTERCHANGE_FORMAT: thumbnail_offset = o; if (thumbnail_offset && thumbnail_length) exif_data_load_data_thumbnail (data, d, ds, thumbnail_offset, thumbnail_length); break; case EXIF_TAG_JPEG_INTERCHANGE_FORMAT_LENGTH: thumbnail_length = o; if (thumbnail_offset && thumbnail_length) exif_data_load_data_thumbnail (data, d, ds, thumbnail_offset, thumbnail_length); break; default: return; } break; default: /* * If we don't know the tag, don't fail. It could be that new * versions of the standard have defined additional tags. Note that * 0 is a valid tag in the GPS IFD. */ if (!exif_tag_get_name_in_ifd (tag, ifd)) { /* * Special case: Tag and format 0. That's against specification * (at least up to 2.2). But Photoshop writes it anyways. */ if (!memcmp (d + offset + 12 * i, "\0\0\0\0", 4)) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Skipping empty entry at position %u in '%s'.", i, exif_ifd_get_name (ifd)); break; } exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Unknown tag 0x%04x (entry %u in '%s'). Please report this tag " "to <[email protected]>.", tag, i, exif_ifd_get_name (ifd)); if (data->priv->options & EXIF_DATA_OPTION_IGNORE_UNKNOWN_TAGS) break; } entry = exif_entry_new_mem (data->priv->mem); if (!entry) { exif_log (data->priv->log, EXIF_LOG_CODE_NO_MEMORY, "ExifData", "Could not allocate memory"); return; } if (exif_data_load_data_entry (data, entry, d, ds, offset + 12 * i)) exif_content_add_entry (data->ifd[ifd], entry); exif_entry_unref (entry); break; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Improve deep recursion detection in exif_data_load_data_content. The existing detection was still vulnerable to pathological cases causing DoS by wasting CPU. The new algorithm takes the number of tags into account to make it harder to abuse by cases using shallow recursion but with a very large number of tags. This improves on commit 5d28011c which wasn't sufficient to counter this kind of case. The limitation in the previous fix was discovered by Laurent Delosieres, Secunia Research at Flexera (Secunia Advisory SA84652) and is assigned the identifier CVE-2018-20030.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rar_read_ahead(struct archive_read *a, size_t min, ssize_t *avail) { struct rar *rar = (struct rar *)(a->format->data); const void *h = __archive_read_ahead(a, min, avail); int ret; if (avail) { if (a->archive.read_data_is_posix_read && *avail > (ssize_t)a->archive.read_data_requested) *avail = a->archive.read_data_requested; if (*avail > rar->bytes_remaining) *avail = (ssize_t)rar->bytes_remaining; if (*avail < 0) return NULL; else if (*avail == 0 && rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER) { ret = archive_read_format_rar_read_header(a, a->entry); if (ret == (ARCHIVE_EOF)) { rar->has_endarc_header = 1; ret = archive_read_format_rar_read_header(a, a->entry); } if (ret != (ARCHIVE_OK)) return NULL; return rar_read_ahead(a, min, avail); } } return h; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'rar: file split across multi-part archives must match Fuzzing uncovered some UAF and memory overrun bugs where a file in a single file archive reported that it was split across multiple volumes. This was caused by ppmd7 operations calling rar_br_fillup. This would invoke rar_read_ahead, which would in some situations invoke archive_read_format_rar_read_header. That would check the new file name against the old file name, and if they didn't match up it would free the ppmd7 buffer and allocate a new one. However, because the ppmd7 decoder wasn't actually done with the buffer, it would continue to used the freed buffer. Both reads and writes to the freed region can be observed. This is quite tricky to solve: once the buffer has been freed it is too late, as the ppmd7 decoder functions almost universally assume success - there's no way for ppmd_read to signal error, nor are there good ways for functions like Range_Normalise to propagate them. So we can't detect after the fact that we're in an invalid state - e.g. by checking rar->cursor, we have to prevent ourselves from ever ending up there. So, when we are in the dangerous part or rar_read_ahead that assumes a valid split, we set a flag force read_header to either go down the path for split files or bail. This means that the ppmd7 decoder keeps a valid buffer and just runs out of data. Found with a combination of AFL, afl-rb and qsym.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ks_http_fetch (ctrl_t ctrl, const char *url, unsigned int flags, estream_t *r_fp) { gpg_error_t err; http_session_t session = NULL; unsigned int session_flags; http_t http = NULL; int redirects_left = MAX_REDIRECTS; estream_t fp = NULL; char *request_buffer = NULL; parsed_uri_t uri = NULL; int is_onion, is_https; err = http_parse_uri (&uri, url, 0); if (err) goto leave; is_onion = uri->onion; is_https = uri->use_tls; /* By default we only use the system provided certificates with this * fetch command. */ session_flags = HTTP_FLAG_TRUST_SYS; if ((flags & KS_HTTP_FETCH_NO_CRL) || ctrl->http_no_crl) session_flags |= HTTP_FLAG_NO_CRL; if ((flags & KS_HTTP_FETCH_TRUST_CFG)) session_flags |= HTTP_FLAG_TRUST_CFG; once_more: err = http_session_new (&session, NULL, session_flags, gnupg_http_tls_verify_cb, ctrl); if (err) goto leave; http_session_set_log_cb (session, cert_log_cb); http_session_set_timeout (session, ctrl->timeout); *r_fp = NULL; err = http_open (&http, HTTP_REQ_GET, url, /* httphost */ NULL, /* fixme: AUTH */ NULL, ((opt.honor_http_proxy? HTTP_FLAG_TRY_PROXY:0) | (DBG_LOOKUP? HTTP_FLAG_LOG_RESP:0) | (dirmngr_use_tor ()? HTTP_FLAG_FORCE_TOR:0) | (opt.disable_ipv4? HTTP_FLAG_IGNORE_IPv4 : 0) | (opt.disable_ipv6? HTTP_FLAG_IGNORE_IPv6 : 0)), ctrl->http_proxy, session, NULL, /*FIXME curl->srvtag*/NULL); if (!err) { fp = http_get_write_ptr (http); /* Avoid caches to get the most recent copy of the key. We set * both the Pragma and Cache-Control versions of the header, so * we're good with both HTTP 1.0 and 1.1. */ if ((flags & KS_HTTP_FETCH_NOCACHE)) es_fputs ("Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n", fp); http_start_data (http); if (es_ferror (fp)) err = gpg_error_from_syserror (); } if (err) { /* Fixme: After a redirection we show the old host name. */ log_error (_("error connecting to '%s': %s\n"), url, gpg_strerror (err)); goto leave; } /* Wait for the response. */ dirmngr_tick (ctrl); err = http_wait_response (http); if (err) { log_error (_("error reading HTTP response for '%s': %s\n"), url, gpg_strerror (err)); goto leave; } switch (http_get_status_code (http)) { case 200: err = 0; break; /* Success. */ case 301: case 302: case 307: { const char *s = http_get_header (http, "Location"); log_info (_("URL '%s' redirected to '%s' (%u)\n"), url, s?s:"[none]", http_get_status_code (http)); if (s && *s && redirects_left-- ) { if (is_onion || is_https) { /* Make sure that an onion address only redirects to * another onion address, or that a https address * only redirects to a https address. */ http_release_parsed_uri (uri); uri = NULL; err = http_parse_uri (&uri, s, 0); if (err) goto leave; if (is_onion && !uri->onion) { err = gpg_error (GPG_ERR_FORBIDDEN); goto leave; } if (!(flags & KS_HTTP_FETCH_ALLOW_DOWNGRADE) && is_https && !uri->use_tls) { err = gpg_error (GPG_ERR_FORBIDDEN); goto leave; } } xfree (request_buffer); request_buffer = xtrystrdup (s); if (request_buffer) { url = request_buffer; http_close (http, 0); http = NULL; http_session_release (session); goto once_more; } err = gpg_error_from_syserror (); } else err = gpg_error (GPG_ERR_NO_DATA); log_error (_("too many redirections\n")); } goto leave; default: log_error (_("error accessing '%s': http status %u\n"), url, http_get_status_code (http)); err = gpg_error (GPG_ERR_NO_DATA); goto leave; } fp = http_get_read_ptr (http); if (!fp) { err = gpg_error (GPG_ERR_BUG); goto leave; } /* Return the read stream and close the HTTP context. */ *r_fp = fp; http_close (http, 1); http = NULL; leave: http_close (http, 0); http_session_release (session); xfree (request_buffer); http_release_parsed_uri (uri); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-352'], 'message': 'dirmngr: Avoid possible CSRF attacks via http redirects. * dirmngr/http.h (parsed_uri_s): Add fields off_host and off_path. (http_redir_info_t): New. * dirmngr/http.c (do_parse_uri): Set new fields. (same_host_p): New. (http_prepare_redirect): New. * dirmngr/t-http-basic.c: New test. * dirmngr/ks-engine-hkp.c (send_request): Use http_prepare_redirect instead of the open code. * dirmngr/ks-engine-http.c (ks_http_fetch): Ditto. -- With this change a http query will not follow a redirect unless the Location header gives the same host. If the host is different only the host and port is taken from the Location header and the original path and query parts are kept. Signed-off-by: Werner Koch <[email protected]> (cherry picked from commit fa1b1eaa4241ff3f0634c8bdf8591cbc7c464144)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: do_parse_uri (parsed_uri_t uri, int only_local_part, int no_scheme_check, int force_tls) { uri_tuple_t *tail; char *p, *p2, *p3, *pp; int n; p = uri->buffer; n = strlen (uri->buffer); /* Initialize all fields to an empty string or an empty list. */ uri->scheme = uri->host = uri->path = p + n; uri->port = 0; uri->params = uri->query = NULL; uri->use_tls = 0; uri->is_http = 0; uri->opaque = 0; uri->v6lit = 0; uri->onion = 0; uri->explicit_port = 0; /* A quick validity check. */ if (strspn (p, VALID_URI_CHARS) != n) return GPG_ERR_BAD_URI; /* Invalid characters found. */ if (!only_local_part) { /* Find the scheme. */ if (!(p2 = strchr (p, ':')) || p2 == p) return GPG_ERR_BAD_URI; /* No scheme. */ *p2++ = 0; for (pp=p; *pp; pp++) *pp = tolower (*(unsigned char*)pp); uri->scheme = p; if (!strcmp (uri->scheme, "http") && !force_tls) { uri->port = 80; uri->is_http = 1; } else if (!strcmp (uri->scheme, "hkp") && !force_tls) { uri->port = 11371; uri->is_http = 1; } #ifdef USE_TLS else if (!strcmp (uri->scheme, "https") || !strcmp (uri->scheme,"hkps") || (force_tls && (!strcmp (uri->scheme, "http") || !strcmp (uri->scheme,"hkp")))) { uri->port = 443; uri->is_http = 1; uri->use_tls = 1; } #endif /*USE_TLS*/ else if (!no_scheme_check) return GPG_ERR_INV_URI; /* Unsupported scheme */ p = p2; if (*p == '/' && p[1] == '/' ) /* There seems to be a hostname. */ { p += 2; if ((p2 = strchr (p, '/'))) *p2++ = 0; /* Check for username/password encoding */ if ((p3 = strchr (p, '@'))) { uri->auth = p; *p3++ = '\0'; p = p3; } for (pp=p; *pp; pp++) *pp = tolower (*(unsigned char*)pp); /* Handle an IPv6 literal */ if( *p == '[' && (p3=strchr( p, ']' )) ) { *p3++ = '\0'; /* worst case, uri->host should have length 0, points to \0 */ uri->host = p + 1; uri->v6lit = 1; p = p3; } else uri->host = p; if ((p3 = strchr (p, ':'))) { *p3++ = '\0'; uri->port = atoi (p3); uri->explicit_port = 1; } if ((n = remove_escapes (uri->host)) < 0) return GPG_ERR_BAD_URI; if (n != strlen (uri->host)) return GPG_ERR_BAD_URI; /* Hostname includes a Nul. */ p = p2 ? p2 : NULL; } else if (uri->is_http) return GPG_ERR_INV_URI; /* No Leading double slash for HTTP. */ else { uri->opaque = 1; uri->path = p; if (is_onion_address (uri->path)) uri->onion = 1; return 0; } } /* End global URI part. */ /* Parse the pathname part if any. */ if (p && *p) { /* TODO: Here we have to check params. */ /* Do we have a query part? */ if ((p2 = strchr (p, '?'))) *p2++ = 0; uri->path = p; if ((n = remove_escapes (p)) < 0) return GPG_ERR_BAD_URI; if (n != strlen (p)) return GPG_ERR_BAD_URI; /* Path includes a Nul. */ p = p2 ? p2 : NULL; /* Parse a query string if any. */ if (p && *p) { tail = &uri->query; for (;;) { uri_tuple_t elem; if ((p2 = strchr (p, '&'))) *p2++ = 0; if (!(elem = parse_tuple (p))) return GPG_ERR_BAD_URI; *tail = elem; tail = &elem->next; if (!p2) break; /* Ready. */ p = p2; } } } if (is_onion_address (uri->host)) uri->onion = 1; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-352'], 'message': 'dirmngr: Avoid possible CSRF attacks via http redirects. * dirmngr/http.h (parsed_uri_s): Add fields off_host and off_path. (http_redir_info_t): New. * dirmngr/http.c (do_parse_uri): Set new fields. (same_host_p): New. (http_prepare_redirect): New. * dirmngr/t-http-basic.c: New test. * dirmngr/ks-engine-hkp.c (send_request): Use http_prepare_redirect instead of the open code. * dirmngr/ks-engine-http.c (ks_http_fetch): Ditto. -- With this change a http query will not follow a redirect unless the Location header gives the same host. If the host is different only the host and port is taken from the Location header and the original path and query parts are kept. Signed-off-by: Werner Koch <[email protected]> (cherry picked from commit fa1b1eaa4241ff3f0634c8bdf8591cbc7c464144)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: std::string HttpConnection::eraseConfidentialInfo(const std::string& request) { std::istringstream istr(request); std::string result; std::string line; while (getline(istr, line)) { if (util::startsWith(line, "Authorization: Basic")) { result += "Authorization: Basic ********\n"; } else if (util::startsWith(line, "Proxy-Authorization: Basic")) { result += "Proxy-Authorization: Basic ********\n"; } else { result += line; result += "\n"; } } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-532'], 'message': 'Mask headers'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool parseOperands(char* str, ArmOp *op) { char *t = strdup (str); int operand = 0; char *token = t; char *x; int imm_count = 0; int mem_opt = 0; if (!token) { return false; } while (token) { char *next = strchr (token, ','); if (next) { *next++ = 0; } while (token[0] == ' ') { token++; } op->operands[operand].type = ARM_NOTYPE; op->operands[operand].reg_type = ARM_UNDEFINED; op->operands[operand].shift = ARM_NO_SHIFT; while (token[0] == ' ' || token[0] == '[' || token[0] == ']') { token ++; } if (!strncmp (token, "lsl", 3)) { op->operands[operand].shift = ARM_LSL; } else if (!strncmp (token, "lsr", 3)) { op->operands[operand].shift = ARM_LSR; } else if (!strncmp (token, "asr", 3)) { op->operands[operand].shift = ARM_ASR; } if (op->operands[operand].shift != ARM_NO_SHIFT) { op->operands_count ++; op->operands[operand].shift_amount = r_num_math (NULL, token + 4); if (op->operands[operand].shift_amount > 63) { return false; } operand ++; token = next; continue; } switch (token[0]) { case 'x': x = strchr (token, ','); if (x) { x[0] = '\0'; } op->operands_count ++; op->operands[operand].type = ARM_GPR; op->operands[operand].reg_type = ARM_REG64; op->operands[operand].reg = r_num_math (NULL, token + 1); if (op->operands[operand].reg > 31) { return false; } break; case 'w': op->operands_count ++; op->operands[operand].type = ARM_GPR; op->operands[operand].reg_type = ARM_REG32; op->operands[operand].reg = r_num_math (NULL, token + 1); if (op->operands[operand].reg > 31) { return false; } break; case 'v': op->operands_count ++; op->operands[operand].type = ARM_FP; op->operands[operand].reg = r_num_math (NULL, token + 1); break; case 's': case 'S': if (token[1] == 'P' || token [1] == 'p') { int i; for (i = 0; msr_const[i].name; i++) { if (!r_str_ncasecmp (token, msr_const[i].name, strlen (msr_const[i].name))) { op->operands[operand].sp_val = msr_const[i].val; break; } } op->operands_count ++; op->operands[operand].type = ARM_GPR; op->operands[operand].reg_type = ARM_SP | ARM_REG64; op->operands[operand].reg = 31; break; } mem_opt = get_mem_option (token); if (mem_opt != -1) { op->operands_count ++; op->operands[operand].type = ARM_MEM_OPT; op->operands[operand].mem_option = mem_opt; } break; case 'L': case 'l': case 'I': case 'i': case 'N': case 'n': case 'O': case 'o': case 'p': case 'P': mem_opt = get_mem_option (token); if (mem_opt != -1) { op->operands_count ++; op->operands[operand].type = ARM_MEM_OPT; op->operands[operand].mem_option = mem_opt; } break; case '-': op->operands[operand].sign = -1; // falthru default: op->operands_count ++; op->operands[operand].type = ARM_CONSTANT; op->operands[operand].immediate = r_num_math (NULL, token); imm_count++; break; } token = next; operand ++; if (operand > MAX_OPERANDS) { free (t); return false; } } free (t); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix #12376 - crash in: rasm2 -a arm -b 64 '0 ,0,0,0,0,0,0,''</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static __latent_entropy struct task_struct *copy_process( unsigned long clone_flags, unsigned long stack_start, unsigned long stack_size, int __user *child_tidptr, struct pid *pid, int trace, unsigned long tls, int node) { int retval; struct task_struct *p; struct multiprocess_signals delayed; /* * Don't allow sharing the root directory with processes in a different * namespace */ if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS)) return ERR_PTR(-EINVAL); if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS)) return ERR_PTR(-EINVAL); /* * Thread groups must share signals as well, and detached threads * can only be started up within the thread group. */ if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND)) return ERR_PTR(-EINVAL); /* * Shared signal handlers imply shared VM. By way of the above, * thread groups also imply shared VM. Blocking this case allows * for various simplifications in other code. */ if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM)) return ERR_PTR(-EINVAL); /* * Siblings of global init remain as zombies on exit since they are * not reaped by their parent (swapper). To solve this and to avoid * multi-rooted process trees, prevent global and container-inits * from creating siblings. */ if ((clone_flags & CLONE_PARENT) && current->signal->flags & SIGNAL_UNKILLABLE) return ERR_PTR(-EINVAL); /* * If the new process will be in a different pid or user namespace * do not allow it to share a thread group with the forking task. */ if (clone_flags & CLONE_THREAD) { if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) || (task_active_pid_ns(current) != current->nsproxy->pid_ns_for_children)) return ERR_PTR(-EINVAL); } /* * Force any signals received before this point to be delivered * before the fork happens. Collect up signals sent to multiple * processes that happen during the fork and delay them so that * they appear to happen after the fork. */ sigemptyset(&delayed.signal); INIT_HLIST_NODE(&delayed.node); spin_lock_irq(&current->sighand->siglock); if (!(clone_flags & CLONE_THREAD)) hlist_add_head(&delayed.node, &current->signal->multiprocess); recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); retval = -ERESTARTNOINTR; if (signal_pending(current)) goto fork_out; retval = -ENOMEM; p = dup_task_struct(current, node); if (!p) goto fork_out; /* * This _must_ happen before we call free_task(), i.e. before we jump * to any of the bad_fork_* labels. This is to avoid freeing * p->set_child_tid which is (ab)used as a kthread's data pointer for * kernel threads (PF_KTHREAD). */ p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL; /* * Clear TID on mm_release()? */ p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr : NULL; ftrace_graph_init_task(p); rt_mutex_init_task(p); #ifdef CONFIG_PROVE_LOCKING DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled); DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled); #endif retval = -EAGAIN; if (atomic_read(&p->real_cred->user->processes) >= task_rlimit(p, RLIMIT_NPROC)) { if (p->real_cred->user != INIT_USER && !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) goto bad_fork_free; } current->flags &= ~PF_NPROC_EXCEEDED; retval = copy_creds(p, clone_flags); if (retval < 0) goto bad_fork_free; /* * If multiple threads are within copy_process(), then this check * triggers too late. This doesn't hurt, the check is only there * to stop root fork bombs. */ retval = -EAGAIN; if (nr_threads >= max_threads) goto bad_fork_cleanup_count; delayacct_tsk_init(p); /* Must remain after dup_task_struct() */ p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE); p->flags |= PF_FORKNOEXEC; INIT_LIST_HEAD(&p->children); INIT_LIST_HEAD(&p->sibling); rcu_copy_process(p); p->vfork_done = NULL; spin_lock_init(&p->alloc_lock); init_sigpending(&p->pending); p->utime = p->stime = p->gtime = 0; #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME p->utimescaled = p->stimescaled = 0; #endif prev_cputime_init(&p->prev_cputime); #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN seqcount_init(&p->vtime.seqcount); p->vtime.starttime = 0; p->vtime.state = VTIME_INACTIVE; #endif #if defined(SPLIT_RSS_COUNTING) memset(&p->rss_stat, 0, sizeof(p->rss_stat)); #endif p->default_timer_slack_ns = current->timer_slack_ns; #ifdef CONFIG_PSI p->psi_flags = 0; #endif task_io_accounting_init(&p->ioac); acct_clear_integrals(p); posix_cpu_timers_init(p); p->start_time = ktime_get_ns(); p->real_start_time = ktime_get_boot_ns(); p->io_context = NULL; audit_set_context(p, NULL); cgroup_fork(p); #ifdef CONFIG_NUMA p->mempolicy = mpol_dup(p->mempolicy); if (IS_ERR(p->mempolicy)) { retval = PTR_ERR(p->mempolicy); p->mempolicy = NULL; goto bad_fork_cleanup_threadgroup_lock; } #endif #ifdef CONFIG_CPUSETS p->cpuset_mem_spread_rotor = NUMA_NO_NODE; p->cpuset_slab_spread_rotor = NUMA_NO_NODE; seqcount_init(&p->mems_allowed_seq); #endif #ifdef CONFIG_TRACE_IRQFLAGS p->irq_events = 0; p->hardirqs_enabled = 0; p->hardirq_enable_ip = 0; p->hardirq_enable_event = 0; p->hardirq_disable_ip = _THIS_IP_; p->hardirq_disable_event = 0; p->softirqs_enabled = 1; p->softirq_enable_ip = _THIS_IP_; p->softirq_enable_event = 0; p->softirq_disable_ip = 0; p->softirq_disable_event = 0; p->hardirq_context = 0; p->softirq_context = 0; #endif p->pagefault_disabled = 0; #ifdef CONFIG_LOCKDEP p->lockdep_depth = 0; /* no locks held yet */ p->curr_chain_key = 0; p->lockdep_recursion = 0; lockdep_init_task(p); #endif #ifdef CONFIG_DEBUG_MUTEXES p->blocked_on = NULL; /* not blocked yet */ #endif #ifdef CONFIG_BCACHE p->sequential_io = 0; p->sequential_io_avg = 0; #endif /* Perform scheduler related setup. Assign this task to a CPU. */ retval = sched_fork(clone_flags, p); if (retval) goto bad_fork_cleanup_policy; retval = perf_event_init_task(p); if (retval) goto bad_fork_cleanup_policy; retval = audit_alloc(p); if (retval) goto bad_fork_cleanup_perf; /* copy all the process information */ shm_init_task(p); retval = security_task_alloc(p, clone_flags); if (retval) goto bad_fork_cleanup_audit; retval = copy_semundo(clone_flags, p); if (retval) goto bad_fork_cleanup_security; retval = copy_files(clone_flags, p); if (retval) goto bad_fork_cleanup_semundo; retval = copy_fs(clone_flags, p); if (retval) goto bad_fork_cleanup_files; retval = copy_sighand(clone_flags, p); if (retval) goto bad_fork_cleanup_fs; retval = copy_signal(clone_flags, p); if (retval) goto bad_fork_cleanup_sighand; retval = copy_mm(clone_flags, p); if (retval) goto bad_fork_cleanup_signal; retval = copy_namespaces(clone_flags, p); if (retval) goto bad_fork_cleanup_mm; retval = copy_io(clone_flags, p); if (retval) goto bad_fork_cleanup_namespaces; retval = copy_thread_tls(clone_flags, stack_start, stack_size, p, tls); if (retval) goto bad_fork_cleanup_io; stackleak_task_init(p); if (pid != &init_struct_pid) { pid = alloc_pid(p->nsproxy->pid_ns_for_children); if (IS_ERR(pid)) { retval = PTR_ERR(pid); goto bad_fork_cleanup_thread; } } #ifdef CONFIG_BLOCK p->plug = NULL; #endif #ifdef CONFIG_FUTEX p->robust_list = NULL; #ifdef CONFIG_COMPAT p->compat_robust_list = NULL; #endif INIT_LIST_HEAD(&p->pi_state_list); p->pi_state_cache = NULL; #endif /* * sigaltstack should be cleared when sharing the same VM */ if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM) sas_ss_reset(p); /* * Syscall tracing and stepping should be turned off in the * child regardless of CLONE_PTRACE. */ user_disable_single_step(p); clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE); #ifdef TIF_SYSCALL_EMU clear_tsk_thread_flag(p, TIF_SYSCALL_EMU); #endif clear_all_latency_tracing(p); /* ok, now we should be set up.. */ p->pid = pid_nr(pid); if (clone_flags & CLONE_THREAD) { p->exit_signal = -1; p->group_leader = current->group_leader; p->tgid = current->tgid; } else { if (clone_flags & CLONE_PARENT) p->exit_signal = current->group_leader->exit_signal; else p->exit_signal = (clone_flags & CSIGNAL); p->group_leader = p; p->tgid = p->pid; } p->nr_dirtied = 0; p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10); p->dirty_paused_when = 0; p->pdeath_signal = 0; INIT_LIST_HEAD(&p->thread_group); p->task_works = NULL; cgroup_threadgroup_change_begin(current); /* * Ensure that the cgroup subsystem policies allow the new process to be * forked. It should be noted the the new process's css_set can be changed * between here and cgroup_post_fork() if an organisation operation is in * progress. */ retval = cgroup_can_fork(p); if (retval) goto bad_fork_free_pid; /* * Make it visible to the rest of the system, but dont wake it up yet. * Need tasklist lock for parent etc handling! */ write_lock_irq(&tasklist_lock); /* CLONE_PARENT re-uses the old parent */ if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) { p->real_parent = current->real_parent; p->parent_exec_id = current->parent_exec_id; } else { p->real_parent = current; p->parent_exec_id = current->self_exec_id; } klp_copy_process(p); spin_lock(&current->sighand->siglock); /* * Copy seccomp details explicitly here, in case they were changed * before holding sighand lock. */ copy_seccomp(p); rseq_fork(p, clone_flags); /* Don't start children in a dying pid namespace */ if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) { retval = -ENOMEM; goto bad_fork_cancel_cgroup; } /* Let kill terminate clone/fork in the middle */ if (fatal_signal_pending(current)) { retval = -EINTR; goto bad_fork_cancel_cgroup; } init_task_pid_links(p); if (likely(p->pid)) { ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace); init_task_pid(p, PIDTYPE_PID, pid); if (thread_group_leader(p)) { init_task_pid(p, PIDTYPE_TGID, pid); init_task_pid(p, PIDTYPE_PGID, task_pgrp(current)); init_task_pid(p, PIDTYPE_SID, task_session(current)); if (is_child_reaper(pid)) { ns_of_pid(pid)->child_reaper = p; p->signal->flags |= SIGNAL_UNKILLABLE; } p->signal->shared_pending.signal = delayed.signal; p->signal->tty = tty_kref_get(current->signal->tty); /* * Inherit has_child_subreaper flag under the same * tasklist_lock with adding child to the process tree * for propagate_has_child_subreaper optimization. */ p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper || p->real_parent->signal->is_child_subreaper; list_add_tail(&p->sibling, &p->real_parent->children); list_add_tail_rcu(&p->tasks, &init_task.tasks); attach_pid(p, PIDTYPE_TGID); attach_pid(p, PIDTYPE_PGID); attach_pid(p, PIDTYPE_SID); __this_cpu_inc(process_counts); } else { current->signal->nr_threads++; atomic_inc(&current->signal->live); atomic_inc(&current->signal->sigcnt); task_join_group_stop(p); list_add_tail_rcu(&p->thread_group, &p->group_leader->thread_group); list_add_tail_rcu(&p->thread_node, &p->signal->thread_head); } attach_pid(p, PIDTYPE_PID); nr_threads++; } total_forks++; hlist_del_init(&delayed.node); spin_unlock(&current->sighand->siglock); syscall_tracepoint_update(p); write_unlock_irq(&tasklist_lock); proc_fork_connector(p); cgroup_post_fork(p); cgroup_threadgroup_change_end(current); perf_event_fork(p); trace_task_newtask(p, clone_flags); uprobe_copy_process(p, clone_flags); return p; bad_fork_cancel_cgroup: spin_unlock(&current->sighand->siglock); write_unlock_irq(&tasklist_lock); cgroup_cancel_fork(p); bad_fork_free_pid: cgroup_threadgroup_change_end(current); if (pid != &init_struct_pid) free_pid(pid); bad_fork_cleanup_thread: exit_thread(p); bad_fork_cleanup_io: if (p->io_context) exit_io_context(p); bad_fork_cleanup_namespaces: exit_task_namespaces(p); bad_fork_cleanup_mm: if (p->mm) mmput(p->mm); bad_fork_cleanup_signal: if (!(clone_flags & CLONE_THREAD)) free_signal_struct(p->signal); bad_fork_cleanup_sighand: __cleanup_sighand(p->sighand); bad_fork_cleanup_fs: exit_fs(p); /* blocking */ bad_fork_cleanup_files: exit_files(p); /* blocking */ bad_fork_cleanup_semundo: exit_sem(p); bad_fork_cleanup_security: security_task_free(p); bad_fork_cleanup_audit: audit_free(p); bad_fork_cleanup_perf: perf_event_free_task(p); bad_fork_cleanup_policy: lockdep_free_task(p); #ifdef CONFIG_NUMA mpol_put(p->mempolicy); bad_fork_cleanup_threadgroup_lock: #endif delayacct_tsk_free(p); bad_fork_cleanup_count: atomic_dec(&p->cred->user->processes); exit_creds(p); bad_fork_free: p->state = TASK_DEAD; put_task_stack(p); free_task(p); fork_out: spin_lock_irq(&current->sighand->siglock); hlist_del_init(&delayed.node); spin_unlock_irq(&current->sighand->siglock); return ERR_PTR(retval); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'fork: record start_time late This changes the fork(2) syscall to record the process start_time after initializing the basic task structure but still before making the new process visible to user-space. Technically, we could record the start_time anytime during fork(2). But this might lead to scenarios where a start_time is recorded long before a process becomes visible to user-space. For instance, with userfaultfd(2) and TLS, user-space can delay the execution of fork(2) for an indefinite amount of time (and will, if this causes network access, or similar). By recording the start_time late, it much closer reflects the point in time where the process becomes live and can be observed by other processes. Lastly, this makes it much harder for user-space to predict and control the start_time they get assigned. Previously, user-space could fork a process and stall it in copy_thread_tls() before its pid is allocated, but after its start_time is recorded. This can be misused to later-on cycle through PIDs and resume the stalled fork(2) yielding a process that has the same pid and start_time as a process that existed before. This can be used to circumvent security systems that identify processes by their pid+start_time combination. Even though user-space was always aware that start_time recording is flaky (but several projects are known to still rely on start_time-based identification), changing the start_time to be recorded late will help mitigate existing attacks and make it much harder for user-space to control the start_time a process gets assigned. Reported-by: Jann Horn <[email protected]> Signed-off-by: Tom Gundersen <[email protected]> Signed-off-by: David Herrmann <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PyMemoTable_Copy(PyMemoTable *self) { Py_ssize_t i; PyMemoTable *new = PyMemoTable_New(); if (new == NULL) return NULL; new->mt_used = self->mt_used; new->mt_allocated = self->mt_allocated; new->mt_mask = self->mt_mask; /* The table we get from _New() is probably smaller than we wanted. Free it and allocate one that's the right size. */ PyMem_FREE(new->mt_table); new->mt_table = PyMem_NEW(PyMemoEntry, self->mt_allocated); if (new->mt_table == NULL) { PyMem_FREE(new); PyErr_NoMemory(); return NULL; } for (i = 0; i < self->mt_allocated; i++) { Py_XINCREF(self->mt_table[i].me_key); } memcpy(new->mt_table, self->mt_table, sizeof(PyMemoEntry) * self->mt_allocated); return new; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-369'], 'message': 'closes bpo-34656: Avoid relying on signed overflow in _pickle memos. (GH-9261)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _Unpickler_ResizeMemoList(UnpicklerObject *self, Py_ssize_t new_size) { Py_ssize_t i; assert(new_size > self->memo_size); PyObject **memo_new = self->memo; PyMem_RESIZE(memo_new, PyObject *, new_size); if (memo_new == NULL) { PyErr_NoMemory(); return -1; } self->memo = memo_new; for (i = self->memo_size; i < new_size; i++) self->memo[i] = NULL; self->memo_size = new_size; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-369'], 'message': 'closes bpo-34656: Avoid relying on signed overflow in _pickle memos. (GH-9261)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _PyMemoTable_ResizeTable(PyMemoTable *self, Py_ssize_t min_size) { PyMemoEntry *oldtable = NULL; PyMemoEntry *oldentry, *newentry; Py_ssize_t new_size = MT_MINSIZE; Py_ssize_t to_process; assert(min_size > 0); /* Find the smallest valid table size >= min_size. */ while (new_size < min_size && new_size > 0) new_size <<= 1; if (new_size <= 0) { PyErr_NoMemory(); return -1; } /* new_size needs to be a power of two. */ assert((new_size & (new_size - 1)) == 0); /* Allocate new table. */ oldtable = self->mt_table; self->mt_table = PyMem_NEW(PyMemoEntry, new_size); if (self->mt_table == NULL) { self->mt_table = oldtable; PyErr_NoMemory(); return -1; } self->mt_allocated = new_size; self->mt_mask = new_size - 1; memset(self->mt_table, 0, sizeof(PyMemoEntry) * new_size); /* Copy entries from the old table. */ to_process = self->mt_used; for (oldentry = oldtable; to_process > 0; oldentry++) { if (oldentry->me_key != NULL) { to_process--; /* newentry is a pointer to a chunk of the new mt_table, so we're setting the key:value pair in-place. */ newentry = _PyMemoTable_Lookup(self, oldentry->me_key); newentry->me_key = oldentry->me_key; newentry->me_value = oldentry->me_value; } } /* Deallocate the old table. */ PyMem_FREE(oldtable); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-369'], 'message': 'closes bpo-34656: Avoid relying on signed overflow in _pickle memos. (GH-9261)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PyMemoTable_Set(PyMemoTable *self, PyObject *key, Py_ssize_t value) { PyMemoEntry *entry; assert(key != NULL); entry = _PyMemoTable_Lookup(self, key); if (entry->me_key != NULL) { entry->me_value = value; return 0; } Py_INCREF(key); entry->me_key = key; entry->me_value = value; self->mt_used++; /* If we added a key, we can safely resize. Otherwise just return! * If used >= 2/3 size, adjust size. Normally, this quaduples the size. * * Quadrupling the size improves average table sparseness * (reducing collisions) at the cost of some memory. It also halves * the number of expensive resize operations in a growing memo table. * * Very large memo tables (over 50K items) use doubling instead. * This may help applications with severe memory constraints. */ if (!(self->mt_used * 3 >= (self->mt_mask + 1) * 2)) return 0; return _PyMemoTable_ResizeTable(self, (self->mt_used > 50000 ? 2 : 4) * self->mt_used); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-369'], 'message': 'closes bpo-34656: Avoid relying on signed overflow in _pickle memos. (GH-9261)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _Unpickler_MemoGet(UnpicklerObject *self, Py_ssize_t idx) { if (idx < 0 || idx >= self->memo_size) return NULL; return self->memo[idx]; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-369'], 'message': 'closes bpo-34656: Avoid relying on signed overflow in _pickle memos. (GH-9261)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; IndexPacket index; MagickBooleanType status; MagickOffsetType offset, start_position; MemoryInfo *pixel_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; register unsigned char *p; size_t bit, bytes_per_line, length; ssize_t count, y; unsigned char magick[12], *pixels; unsigned int blue, green, offset_bits, red; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a BMP file. */ (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; offset_bits=0; count=ReadBlob(image,2,magick); if (count != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { LongPixelPacket shift; PixelPacket quantum_bits; /* Verify BMP identifier. */ start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,"BA",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c", magick[0],magick[1]); if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) && (LocaleNCompare((char *) magick,"CI",2) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " File_size in header: %u bytes",bmp_info.file_size); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u", bmp_info.size); if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,"BMP2",MaxTextExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: OS/2 Bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError"); bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); if (bmp_info.number_colors > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); bmp_info.colors_important=ReadBlobLSBLong(image); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: MS Windows bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel); switch (bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RGB"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE4"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_BITFIELDS"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_PNG"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_JPEG"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: UNKNOWN (%u)",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %u",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double gamma; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=ReadBlobLSBSignedLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.red_primary.x*=gamma; bmp_info.red_primary.y*=gamma; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.green_primary.x*=gamma; bmp_info.green_primary.y*=gamma; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.blue_primary.x*=gamma; bmp_info.blue_primary.y*=gamma; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,"BMP3",MaxTextExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } (void) ReadBlobLSBLong(image); /* Profile data */ (void) ReadBlobLSBLong(image); /* Profile size */ (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "LengthAndFilesizeDoNotMatch","`%s'",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) ThrowReaderException(CorruptImageError,"UnrecognizedNumberOfColors"); if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); switch (bmp_info.compression) { case BI_RGB: image->compression=NoCompression; break; case BI_RLE8: case BI_RLE4: image->compression=RLECompression; break; case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,"JPEGCompressNotSupported"); case BI_PNG: ThrowReaderException(CoderError,"PNGCompressNotSupported"); default: ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->matte=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) ? MagickTrue : MagickFalse; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } image->x_resolution=(double) bmp_info.x_pixels/100.0; image->y_resolution=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading colormap of %.20g colors",(double) image->colors); if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].red=ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } /* Read image data. */ if (bmp_info.offset_bits == offset_bits) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset_bits=bmp_info.offset_bits; offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { if ((MagickSizeType) length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line, image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading pixels (%.20g bytes)",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } } else { /* Convert run-length encoded raster pixels. */ pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line, image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); status=DecodeImage(image,bmp_info.compression,pixels, image->columns*image->rows); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnableToRunlengthDecodeImage"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { /* We should ignore the alpha value in BMP3 files but there have been reports about 32 bit files with alpha. We do a quick check to see if the alpha channel contains a value that is not zero (default value). If we find a non zero value we asume the program that wrote the file wants to use the alpha channel. */ if ((image->matte == MagickFalse) && (bmp_info.size == 40) && (bmp_info.bits_per_pixel == 32)) { bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { if (*(p+3) != 0) { image->matte=MagickTrue; y=-1; break; } p+=4; } } } bmp_info.alpha_mask=image->matte != MagickFalse ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } (void) memset(&shift,0,sizeof(shift)); (void) memset(&quantum_bits,0,sizeof(quantum_bits)); if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register size_t sample; /* Get shift and quantum bits info from bitfield masks. */ if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) { shift.red++; if (shift.red > 32U) break; } if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) { shift.green++; if (shift.green > 32U) break; } if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) { shift.blue++; if (shift.blue > 32U) break; } if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.opacity) & 0x80000000UL) == 0) { shift.opacity++; if (shift.opacity > 32U) break; } sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.red=ClampToQuantum((MagickRealType) sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.green=ClampToQuantum((MagickRealType) sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.blue=ClampToQuantum((MagickRealType) sample-shift.blue); sample=shift.opacity; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.opacity=ClampToQuantum((MagickRealType) sample- shift.opacity); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); q++; } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0x0f), &index,exception); SetPixelIndex(indexes+x,index); (void) IsValidColormapIndex(image,(ssize_t) (*p & 0x0f),&index, exception); SetPixelIndex(indexes+x+1,index); p++; } if ((image->columns % 2) != 0) { (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0xf), &index,exception); SetPixelIndex(indexes+(x++),index); p++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=(ssize_t) image->columns; x != 0; --x) { (void) IsValidColormapIndex(image,(ssize_t) *p,&index,exception); SetPixelIndex(indexes,index); indexes++; p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 16: { unsigned int alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if (bmp_info.compression != BI_RGB && bmp_info.compression != BI_BITFIELDS) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); SetPixelRed(q,ScaleShortToQuantum((unsigned short) red)); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green)); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16; if (quantum_bits.opacity <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha)); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { unsigned int alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=((unsigned int) *p++ << 8); pixel|=((unsigned int) *p++ << 16); pixel|=((unsigned int) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); SetPixelRed(q,ScaleShortToQuantum((unsigned short) red)); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green)); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue)); SetPixelAlpha(q,OpaqueOpacity); if (image->matte != MagickFalse) { alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16; if (quantum_bits.opacity == 8) alpha|=(alpha >> 8); SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha)); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (y > 0) break; if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); ReplaceImageInList(&image, flipped_image); image=flipped_image; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; *magick='\0'; if (bmp_info.ba_offset != 0) { offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'Prevent infinite loop'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int jp2_encode(jas_image_t *image, jas_stream_t *out, const char *optstr) { jp2_box_t *box; jp2_ftyp_t *ftyp; jp2_ihdr_t *ihdr; jas_stream_t *tmpstream; int allcmptssame; jp2_bpcc_t *bpcc; long len; uint_fast16_t cmptno; jp2_colr_t *colr; char buf[4096]; uint_fast32_t overhead; jp2_cdefchan_t *cdefchanent; jp2_cdef_t *cdef; int i; uint_fast32_t typeasoc; jas_iccprof_t *iccprof; jas_stream_t *iccstream; int pos; int needcdef; int prec; int sgnd; box = 0; tmpstream = 0; iccstream = 0; iccprof = 0; if (jas_image_numcmpts(image) < 1) { jas_eprintf("image must have at least one component\n"); goto error; } allcmptssame = 1; sgnd = jas_image_cmptsgnd(image, 0); prec = jas_image_cmptprec(image, 0); for (i = 1; i < jas_image_numcmpts(image); ++i) { if (jas_image_cmptsgnd(image, i) != sgnd || jas_image_cmptprec(image, i) != prec) { allcmptssame = 0; break; } } /* Output the signature box. */ if (!(box = jp2_box_create(JP2_BOX_JP))) { jas_eprintf("cannot create JP box\n"); goto error; } box->data.jp.magic = JP2_JP_MAGIC; if (jp2_box_put(box, out)) { jas_eprintf("cannot write JP box\n"); goto error; } jp2_box_destroy(box); box = 0; /* Output the file type box. */ if (!(box = jp2_box_create(JP2_BOX_FTYP))) { jas_eprintf("cannot create FTYP box\n"); goto error; } ftyp = &box->data.ftyp; ftyp->majver = JP2_FTYP_MAJVER; ftyp->minver = JP2_FTYP_MINVER; ftyp->numcompatcodes = 1; ftyp->compatcodes[0] = JP2_FTYP_COMPATCODE; if (jp2_box_put(box, out)) { jas_eprintf("cannot write FTYP box\n"); goto error; } jp2_box_destroy(box); box = 0; /* * Generate the data portion of the JP2 header box. * We cannot simply output the header for this box * since we do not yet know the correct value for the length * field. */ if (!(tmpstream = jas_stream_memopen(0, 0))) { jas_eprintf("cannot create temporary stream\n"); goto error; } /* Generate image header box. */ if (!(box = jp2_box_create(JP2_BOX_IHDR))) { jas_eprintf("cannot create IHDR box\n"); goto error; } ihdr = &box->data.ihdr; ihdr->width = jas_image_width(image); ihdr->height = jas_image_height(image); ihdr->numcmpts = jas_image_numcmpts(image); ihdr->bpc = allcmptssame ? JP2_SPTOBPC(jas_image_cmptsgnd(image, 0), jas_image_cmptprec(image, 0)) : JP2_IHDR_BPCNULL; ihdr->comptype = JP2_IHDR_COMPTYPE; ihdr->csunk = 0; ihdr->ipr = 0; if (jp2_box_put(box, tmpstream)) { jas_eprintf("cannot write IHDR box\n"); goto error; } jp2_box_destroy(box); box = 0; /* Generate bits per component box. */ if (!allcmptssame) { if (!(box = jp2_box_create(JP2_BOX_BPCC))) { jas_eprintf("cannot create BPCC box\n"); goto error; } bpcc = &box->data.bpcc; bpcc->numcmpts = jas_image_numcmpts(image); if (!(bpcc->bpcs = jas_alloc2(bpcc->numcmpts, sizeof(uint_fast8_t)))) { jas_eprintf("memory allocation failed\n"); goto error; } for (cmptno = 0; cmptno < bpcc->numcmpts; ++cmptno) { bpcc->bpcs[cmptno] = JP2_SPTOBPC(jas_image_cmptsgnd(image, cmptno), jas_image_cmptprec(image, cmptno)); } if (jp2_box_put(box, tmpstream)) { jas_eprintf("cannot write BPCC box\n"); goto error; } jp2_box_destroy(box); box = 0; } /* Generate color specification box. */ if (!(box = jp2_box_create(JP2_BOX_COLR))) { jas_eprintf("cannot create COLR box\n"); goto error; } colr = &box->data.colr; switch (jas_image_clrspc(image)) { case JAS_CLRSPC_SRGB: case JAS_CLRSPC_SYCBCR: case JAS_CLRSPC_SGRAY: colr->method = JP2_COLR_ENUM; colr->csid = clrspctojp2(jas_image_clrspc(image)); colr->pri = JP2_COLR_PRI; colr->approx = 0; break; default: colr->method = JP2_COLR_ICC; colr->pri = JP2_COLR_PRI; colr->approx = 0; /* Ensure that cmprof_ is not null. */ if (!jas_image_cmprof(image)) { jas_eprintf("CM profile is null\n"); goto error; } if (!(iccprof = jas_iccprof_createfromcmprof( jas_image_cmprof(image)))) { jas_eprintf("cannot create ICC profile\n"); goto error; } if (!(iccstream = jas_stream_memopen(0, 0))) { jas_eprintf("cannot create temporary stream\n"); goto error; } if (jas_iccprof_save(iccprof, iccstream)) { jas_eprintf("cannot write ICC profile\n"); goto error; } if ((pos = jas_stream_tell(iccstream)) < 0) { jas_eprintf("cannot get stream position\n"); goto error; } colr->iccplen = pos; if (!(colr->iccp = jas_malloc(pos))) { jas_eprintf("memory allocation failed\n"); goto error; } jas_stream_rewind(iccstream); if (jas_stream_read(iccstream, colr->iccp, colr->iccplen) != colr->iccplen) { jas_eprintf("cannot read temporary stream\n"); goto error; } jas_stream_close(iccstream); iccstream = 0; jas_iccprof_destroy(iccprof); iccprof = 0; break; } if (jp2_box_put(box, tmpstream)) { jas_eprintf("cannot write box\n"); goto error; } jp2_box_destroy(box); box = 0; needcdef = 1; switch (jas_clrspc_fam(jas_image_clrspc(image))) { case JAS_CLRSPC_FAM_RGB: if (jas_image_cmpttype(image, 0) == JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R) && jas_image_cmpttype(image, 1) == JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G) && jas_image_cmpttype(image, 2) == JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)) needcdef = 0; break; case JAS_CLRSPC_FAM_YCBCR: if (jas_image_cmpttype(image, 0) == JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y) && jas_image_cmpttype(image, 1) == JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB) && jas_image_cmpttype(image, 2) == JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR)) needcdef = 0; break; case JAS_CLRSPC_FAM_GRAY: if (jas_image_cmpttype(image, 0) == JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y)) needcdef = 0; break; default: abort(); break; } if (needcdef) { if (!(box = jp2_box_create(JP2_BOX_CDEF))) { jas_eprintf("cannot create CDEF box\n"); goto error; } cdef = &box->data.cdef; cdef->numchans = jas_image_numcmpts(image); cdef->ents = jas_alloc2(cdef->numchans, sizeof(jp2_cdefchan_t)); for (i = 0; i < jas_image_numcmpts(image); ++i) { cdefchanent = &cdef->ents[i]; cdefchanent->channo = i; typeasoc = jp2_gettypeasoc(jas_image_clrspc(image), jas_image_cmpttype(image, i)); cdefchanent->type = typeasoc >> 16; cdefchanent->assoc = typeasoc & 0x7fff; } if (jp2_box_put(box, tmpstream)) { jas_eprintf("cannot write CDEF box\n"); goto error; } jp2_box_destroy(box); box = 0; } /* Determine the total length of the JP2 header box. */ len = jas_stream_tell(tmpstream); jas_stream_rewind(tmpstream); /* * Output the JP2 header box and all of the boxes which it contains. */ if (!(box = jp2_box_create(JP2_BOX_JP2H))) { jas_eprintf("cannot create JP2H box\n"); goto error; } box->len = len + JP2_BOX_HDRLEN(false); if (jp2_box_put(box, out)) { jas_eprintf("cannot write JP2H box\n"); goto error; } jp2_box_destroy(box); box = 0; if (jas_stream_copy(out, tmpstream, len)) { jas_eprintf("cannot copy stream\n"); goto error; } jas_stream_close(tmpstream); tmpstream = 0; /* * Output the contiguous code stream box. */ if (!(box = jp2_box_create(JP2_BOX_JP2C))) { jas_eprintf("cannot create JP2C box\n"); goto error; } box->len = 0; if (jp2_box_put(box, out)) { jas_eprintf("cannot write JP2C box\n"); goto error; } jp2_box_destroy(box); box = 0; /* Output the JPEG-2000 code stream. */ overhead = jas_stream_getrwcount(out); sprintf(buf, "%s\n_jp2overhead=%lu\n", (optstr ? optstr : ""), (unsigned long) overhead); if (jpc_encode(image, out, buf)) { jas_eprintf("jpc_encode failed\n"); goto error; } return 0; error: if (iccprof) { jas_iccprof_destroy(iccprof); } if (iccstream) { jas_stream_close(iccstream); } if (box) { jp2_box_destroy(box); } if (tmpstream) { jas_stream_close(tmpstream); } return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'jp2_enc: check number of components before dereferencing them Fixes CVE-2018-20570 Closes https://github.com/jasper-maint/jasper/issues/11 Closes https://github.com/mdadams/jasper/issues/191'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int qh_core(int sd, char *buf, unsigned int len) { char *space; if (*buf == 0 || !strcmp(buf, "help")) { nsock_printf_nul(sd, "Query handler for manipulating nagios core.\n" "Available commands:\n" " loadctl Print information about current load control settings\n" " loadctl <options> Configure nagios load control.\n" " The options are the same parameters and format as\n" " returned above.\n" " squeuestats scheduling queue statistics\n" ); return 0; } space = memchr(buf, ' ', len); if (space != NULL) { *(space++) = 0; } if (space == NULL) { if (!strcmp(buf, "loadctl")) { nsock_printf_nul(sd, "jobs_max=%u;jobs_min=%u;" "jobs_running=%u;jobs_limit=%u;" "load=%.2f;" "backoff_limit=%.2f;backoff_change=%u;" "rampup_limit=%.2f;rampup_change=%u;" "nproc_limit=%u;nofile_limit=%u;" "options=%u;changes=%u;", loadctl.jobs_max, loadctl.jobs_min, loadctl.jobs_running, loadctl.jobs_limit, loadctl.load[0], loadctl.backoff_limit, loadctl.backoff_change, loadctl.rampup_limit, loadctl.rampup_change, loadctl.nproc_limit, loadctl.nofile_limit, loadctl.options, loadctl.changes ); return 0; } else if (!strcmp(buf, "squeuestats")) { return dump_event_stats(sd); } } /* space != NULL: */ else { len -= (unsigned long)(space - buf); if (!strcmp(buf, "loadctl")) { return set_loadctl_options(space, len) == OK ? 200 : 400; } } /* No matching command found */ return 404; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'merge accidental master PR (#553) into maint and fix changelog merge conflict'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int qh_help(int sd, char *buf, unsigned int len) { struct query_handler *qh = NULL; if (!*buf || !strcmp(buf, "help")) { nsock_printf_nul(sd, " help <name> show help for handler <name>\n" " help list list registered handlers\n"); return 0; } if (!strcmp(buf, "list")) { for (qh = qhandlers; qh != NULL; qh = qh->next_qh) { nsock_printf(sd, "%-10s %s\n", qh->name, qh->description ? qh->description : "(No description available)"); } nsock_printf(sd, "%c", 0); return 0; } qh = qh_find_handler(buf); if (qh == NULL) { nsock_printf_nul(sd, "No handler named '%s' is registered\n", buf); } else if (qh->handler(sd, "help", 4) > 200) { nsock_printf_nul(sd, "The handler %s doesn't have any help yet.", buf); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'merge accidental master PR (#553) into maint and fix changelog merge conflict'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: FileSpec::FileSpec(const Object *fileSpecA) { ok = true; fileName = nullptr; platformFileName = nullptr; embFile = nullptr; desc = nullptr; fileSpec = fileSpecA->copy(); Object obj1 = getFileSpecName(fileSpecA); if (!obj1.isString()) { ok = false; error(errSyntaxError, -1, "Invalid FileSpec"); return; } fileName = obj1.getString()->copy(); if (fileSpec.isDict()) { obj1 = fileSpec.dictLookup("EF"); if (obj1.isDict()) { fileStream = obj1.dictLookupNF("F"); if (!fileStream.isRef()) { ok = false; fileStream.setToNull(); error(errSyntaxError, -1, "Invalid FileSpec: Embedded file stream is not an indirect reference"); return; } } } obj1 = fileSpec.dictLookup("Desc"); if (obj1.isString()) desc = obj1.getString()->copy(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'FileSpec: Move the fileSpec.dictLookup call inside fileSpec.isDict if Fixes #704'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool PDFDoc::setup(const GooString *ownerPassword, const GooString *userPassword) { pdfdocLocker(); if (str->getLength() <= 0) { error(errSyntaxError, -1, "Document stream is empty"); return false; } str->setPos(0, -1); if (str->getPos() < 0) { error(errSyntaxError, -1, "Document base stream is not seekable"); return false; } str->reset(); // check footer // Adobe does not seem to enforce %%EOF, so we do the same // if (!checkFooter()) return false; // check header checkHeader(); bool wasReconstructed = false; // read xref table xref = new XRef(str, getStartXRef(), getMainXRefEntriesOffset(), &wasReconstructed); if (!xref->isOk()) { if (wasReconstructed) { delete xref; startXRefPos = -1; xref = new XRef(str, getStartXRef(true), getMainXRefEntriesOffset(true), &wasReconstructed); } if (!xref->isOk()) { error(errSyntaxError, -1, "Couldn't read xref table"); errCode = xref->getErrorCode(); return false; } } // check for encryption if (!checkEncryption(ownerPassword, userPassword)) { errCode = errEncrypted; return false; } // read catalog catalog = new Catalog(this); if (catalog && !catalog->isOk()) { if (!wasReconstructed) { // try one more time to construct the Catalog, maybe the problem is damaged XRef delete catalog; delete xref; xref = new XRef(str, 0, 0, nullptr, true); catalog = new Catalog(this); } if (catalog && !catalog->isOk()) { error(errSyntaxError, -1, "Couldn't read page catalog"); errCode = errBadCatalog; return false; } } // Extract PDF Subtype information extractPDFSubtype(); // done return xref->isOk(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Revert 9fd5ec0e6e5f763b190f2a55ceb5427cfe851d5f It was causing regressions for some half-broken files Rationale: Even if xref::constructXRef is returning false, that only means "i din't find a new xref root", but constructXRef is also quite stubborn in which it basically parses the whole file and stores the positions of all the objects it finds, so for some half broken pdf files this is good enough and we will be able to render those files just fine'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void libxsmm_sparse_csc_reader( libxsmm_generated_code* io_generated_code, const char* i_csc_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csc_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_column_idx_id = NULL; unsigned int l_i = 0; l_csc_file_handle = fopen( i_csc_file_in, "r" ); if ( l_csc_file_handle == NULL ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_INPUT ); return; } while (fgets(l_line, l_line_length, l_csc_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose( l_csc_file_handle ); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_LEN ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC data structure matching mtx file */ *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * ((size_t)(*o_column_count) + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_column_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_column_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_column_idx_id == NULL ) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csc_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_ALLOC_DATA ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int) * (*o_element_count)); memset(*o_column_idx, 0, sizeof(unsigned int) * ((size_t)(*o_column_count) + 1)); memset(*o_values, 0, sizeof(double) * (*o_element_count)); memset(l_column_idx_id, 0, sizeof(unsigned int) * (*o_column_count)); /* init column idx */ for (l_i = 0; l_i <= *o_column_count; ++l_i) { (*o_column_idx)[l_i] = *o_element_count; } /* init */ (*o_column_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_DESC ); fclose( l_csc_file_handle ); /* close mtx file */ return; } /* now we read the actual content */ } else { unsigned int l_row = 0, l_column = 0; double l_value = 0; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csc_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_ELEMS ); return; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_row_idx)[l_i] = l_row; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_column_idx_id[l_column] = 1; (*o_column_idx)[l_column+1] = l_i; } } } /* close mtx file */ fclose( l_csc_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_LEN ); return; } if ( l_column_idx_id != NULL ) { /* let's handle empty columns */ for ( l_i = 0; l_i < (*o_column_count); l_i++) { if ( l_column_idx_id[l_i] == 0 ) { (*o_column_idx)[l_i+1] = (*o_column_idx)[l_i]; } } /* free helper data structure */ free( l_column_idx_id ); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Issue #287: made CSR/CSC readers more robust against invalid input (case #1).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int my_csr_reader( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, REALTYPE** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, "cannot open CSR file!\n" ); return -1; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, "could not read file length!\n" ); return -1; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (REALTYPE*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, "could not allocate sp data!\n" ); return -1; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, "could not csr description!\n" ); return -1; } /* now we read the actual content */ } else { unsigned int l_row, l_column; REALTYPE l_value; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, "could not read element!\n" ); return -1; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, "we were not able to read all elements!\n" ); return -1; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Issue #287: made CSR/CSC readers more robust against invalid input (case #1).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void edge_sparse_csr_reader_double( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, "cannot open CSR file!\n" ); return; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, "could not read file length!\n" ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, "could not allocate sp data!\n" ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, "could not csr description!\n" ); return; } /* now we read the actual content */ } else { unsigned int l_row, l_column; double l_value; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, "could not read element!\n" ); return; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, "we were not able to read all elements!\n" ); return; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Issue #287: made CSR/CSC readers more robust against invalid input (case #1).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main(int argc, char *argv[]) { g_test_init(&argc, &argv, NULL); /* try to create a surface with no issues, should succeed */ g_test_add_func("/server/qxl-parsing-no-issues", test_no_issues); /* try to create a surface with a stride too small to fit * the entire width. * This can be used to cause buffer overflows so refuse it. */ g_test_add_func("/server/qxl-parsing/stride-too-small", test_stride_too_small); /* try to create a surface quite large. * The sizes (width and height) were chosen so the multiplication * using 32 bit values gives a very small value. * These kind of values should be refused as they will cause * overflows. Also the total memory for the card is not enough to * hold the surface so surely can't be accepted. */ g_test_add_func("/server/qxl-parsing/too-big-image", test_too_big_image); /* test base cursor with no problems */ g_test_add_func("/server/qxl-parsing/base-cursor-command", test_cursor_command); /* a circular list of empty chunks should not be a problems */ g_test_add_func("/server/qxl-parsing/circular-empty-chunks", test_circular_empty_chunks); /* a circular list of small chunks should not be a problems */ g_test_add_func("/server/qxl-parsing/circular-small-chunks", test_circular_small_chunks); return g_test_run(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-193'], 'message': 'memslot: Fix off-by-one error in group/slot boundary check RedMemSlotInfo keeps an array of groups, and each group contains an array of slots. Unfortunately, these checks are off by 1, they check that the index is greater or equal to the number of elements in the array, while these arrays are 0 based. The check should only check for strictly greater than the number of elements. For the group array, this is not a big issue, as these memslot groups are created by spice-server users (eg QEMU), and the group ids used to index that array are also generated by the spice-server user, so it should not be possible for the guest to set them to arbitrary values. The slot id is more problematic, as it's calculated from a QXLPHYSICAL address, and such addresses are usually set by the guest QXL driver, so the guest can set these to arbitrary values, including malicious values, which are probably easy to build from the guest PCI configuration. This patch fixes the arrays bound check, and adds a test case for this. This fixes CVE-2019-3813. Signed-off-by: Christophe Fergeau <[email protected]> Acked-by: Frediano Ziglio <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static const URI_CHAR * URI_FUNC(ParseIPv6address2)( URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory) { int zipperEver = 0; int quadsDone = 0; int digitCount = 0; unsigned char digitHistory[4]; int ip4OctetsDone = 0; unsigned char quadsAfterZipper[14]; int quadsAfterZipperCount = 0; for (;;) { if (first >= afterLast) { URI_FUNC(StopSyntax)(state, first, memory); return NULL; } /* Inside IPv4 part? */ if (ip4OctetsDone > 0) { /* Eat rest of IPv4 address */ for (;;) { switch (*first) { case URI_SET_DIGIT: if (digitCount == 4) { URI_FUNC(StopSyntax)(state, first, memory); return NULL; } digitHistory[digitCount++] = (unsigned char)(9 + *first - _UT('9')); break; case _UT('.'): if ((ip4OctetsDone == 4) /* NOTE! */ || (digitCount == 0) || (digitCount == 4)) { /* Invalid digit or octet count */ URI_FUNC(StopSyntax)(state, first, memory); return NULL; } else if ((digitCount > 1) && (digitHistory[0] == 0)) { /* Leading zero */ URI_FUNC(StopSyntax)(state, first - digitCount, memory); return NULL; } else if ((digitCount > 2) && (digitHistory[1] == 0)) { /* Leading zero */ URI_FUNC(StopSyntax)(state, first - digitCount + 1, memory); return NULL; } else if ((digitCount == 3) && (100 * digitHistory[0] + 10 * digitHistory[1] + digitHistory[2] > 255)) { /* Octet value too large */ if (digitHistory[0] > 2) { URI_FUNC(StopSyntax)(state, first - 3, memory); } else if (digitHistory[1] > 5) { URI_FUNC(StopSyntax)(state, first - 2, memory); } else { URI_FUNC(StopSyntax)(state, first - 1, memory); } return NULL; } /* Copy IPv4 octet */ state->uri->hostData.ip6->data[16 - 4 + ip4OctetsDone] = uriGetOctetValue(digitHistory, digitCount); digitCount = 0; ip4OctetsDone++; break; case _UT(']'): if ((ip4OctetsDone != 3) /* NOTE! */ || (digitCount == 0) || (digitCount == 4)) { /* Invalid digit or octet count */ URI_FUNC(StopSyntax)(state, first, memory); return NULL; } else if ((digitCount > 1) && (digitHistory[0] == 0)) { /* Leading zero */ URI_FUNC(StopSyntax)(state, first - digitCount, memory); return NULL; } else if ((digitCount > 2) && (digitHistory[1] == 0)) { /* Leading zero */ URI_FUNC(StopSyntax)(state, first - digitCount + 1, memory); return NULL; } else if ((digitCount == 3) && (100 * digitHistory[0] + 10 * digitHistory[1] + digitHistory[2] > 255)) { /* Octet value too large */ if (digitHistory[0] > 2) { URI_FUNC(StopSyntax)(state, first - 3, memory); } else if (digitHistory[1] > 5) { URI_FUNC(StopSyntax)(state, first - 2, memory); } else { URI_FUNC(StopSyntax)(state, first - 1, memory); } return NULL; } state->uri->hostText.afterLast = first; /* HOST END */ /* Copy missing quads right before IPv4 */ memcpy(state->uri->hostData.ip6->data + 16 - 4 - 2 * quadsAfterZipperCount, quadsAfterZipper, 2 * quadsAfterZipperCount); /* Copy last IPv4 octet */ state->uri->hostData.ip6->data[16 - 4 + 3] = uriGetOctetValue(digitHistory, digitCount); return first + 1; default: URI_FUNC(StopSyntax)(state, first, memory); return NULL; } first++; } } else { /* Eat while no dot in sight */ int letterAmong = 0; int walking = 1; do { switch (*first) { case URI_SET_HEX_LETTER_LOWER: letterAmong = 1; if (digitCount == 4) { URI_FUNC(StopSyntax)(state, first, memory); return NULL; } digitHistory[digitCount] = (unsigned char)(15 + *first - _UT('f')); digitCount++; break; case URI_SET_HEX_LETTER_UPPER: letterAmong = 1; if (digitCount == 4) { URI_FUNC(StopSyntax)(state, first, memory); return NULL; } digitHistory[digitCount] = (unsigned char)(15 + *first - _UT('F')); digitCount++; break; case URI_SET_DIGIT: if (digitCount == 4) { URI_FUNC(StopSyntax)(state, first, memory); return NULL; } digitHistory[digitCount] = (unsigned char)(9 + *first - _UT('9')); digitCount++; break; case _UT(':'): { int setZipper = 0; if (digitCount > 0) { if (zipperEver) { uriWriteQuadToDoubleByte(digitHistory, digitCount, quadsAfterZipper + 2 * quadsAfterZipperCount); quadsAfterZipperCount++; } else { uriWriteQuadToDoubleByte(digitHistory, digitCount, state->uri->hostData.ip6->data + 2 * quadsDone); } quadsDone++; digitCount = 0; } letterAmong = 0; /* Too many quads? */ if (quadsDone >= 8 - zipperEver) { URI_FUNC(StopSyntax)(state, first, memory); return NULL; } /* "::"? */ if (first + 1 >= afterLast) { URI_FUNC(StopSyntax)(state, first + 1, memory); return NULL; } if (first[1] == _UT(':')) { const int resetOffset = 2 * (quadsDone + (digitCount > 0)); first++; if (zipperEver) { URI_FUNC(StopSyntax)(state, first, memory); return NULL; /* "::.+::" */ } /* Zero everything after zipper */ memset(state->uri->hostData.ip6->data + resetOffset, 0, 16 - resetOffset); setZipper = 1; /* ":::+"? */ if (first + 1 >= afterLast) { URI_FUNC(StopSyntax)(state, first + 1, memory); return NULL; /* No ']' yet */ } if (first[1] == _UT(':')) { URI_FUNC(StopSyntax)(state, first + 1, memory); return NULL; /* ":::+ "*/ } } if (setZipper) { zipperEver = 1; } } break; case _UT('.'): if ((quadsDone > 6) /* NOTE */ || (!zipperEver && (quadsDone < 6)) || letterAmong || (digitCount == 0) || (digitCount == 4)) { /* Invalid octet before */ URI_FUNC(StopSyntax)(state, first, memory); return NULL; } else if ((digitCount > 1) && (digitHistory[0] == 0)) { /* Leading zero */ URI_FUNC(StopSyntax)(state, first - digitCount, memory); return NULL; } else if ((digitCount > 2) && (digitHistory[1] == 0)) { /* Leading zero */ URI_FUNC(StopSyntax)(state, first - digitCount + 1, memory); return NULL; } else if ((digitCount == 3) && (100 * digitHistory[0] + 10 * digitHistory[1] + digitHistory[2] > 255)) { /* Octet value too large */ if (digitHistory[0] > 2) { URI_FUNC(StopSyntax)(state, first - 3, memory); } else if (digitHistory[1] > 5) { URI_FUNC(StopSyntax)(state, first - 2, memory); } else { URI_FUNC(StopSyntax)(state, first - 1, memory); } return NULL; } /* Copy first IPv4 octet */ state->uri->hostData.ip6->data[16 - 4] = uriGetOctetValue(digitHistory, digitCount); digitCount = 0; /* Switch over to IPv4 loop */ ip4OctetsDone = 1; walking = 0; break; case _UT(']'): /* Too little quads? */ if (!zipperEver && !((quadsDone == 7) && (digitCount > 0))) { URI_FUNC(StopSyntax)(state, first, memory); return NULL; } if (digitCount > 0) { if (zipperEver) { uriWriteQuadToDoubleByte(digitHistory, digitCount, quadsAfterZipper + 2 * quadsAfterZipperCount); quadsAfterZipperCount++; } else { uriWriteQuadToDoubleByte(digitHistory, digitCount, state->uri->hostData.ip6->data + 2 * quadsDone); } /* quadsDone++; digitCount = 0; */ } /* Copy missing quads to the end */ memcpy(state->uri->hostData.ip6->data + 16 - 2 * quadsAfterZipperCount, quadsAfterZipper, 2 * quadsAfterZipperCount); state->uri->hostText.afterLast = first; /* HOST END */ return first + 1; /* Fine */ default: URI_FUNC(StopSyntax)(state, first, memory); return NULL; } first++; if (first >= afterLast) { URI_FUNC(StopSyntax)(state, first, memory); return NULL; /* No ']' yet */ } } while (walking); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix uriParse*Ex* out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int hso_get_config_data(struct usb_interface *interface) { struct usb_device *usbdev = interface_to_usbdev(interface); u8 *config_data = kmalloc(17, GFP_KERNEL); u32 if_num = interface->cur_altsetting->desc.bInterfaceNumber; s32 result; if (!config_data) return -ENOMEM; if (usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0), 0x86, 0xC0, 0, 0, config_data, 17, USB_CTRL_SET_TIMEOUT) != 0x11) { kfree(config_data); return -EIO; } switch (config_data[if_num]) { case 0x0: result = 0; break; case 0x1: result = HSO_PORT_DIAG; break; case 0x2: result = HSO_PORT_GPS; break; case 0x3: result = HSO_PORT_GPS_CONTROL; break; case 0x4: result = HSO_PORT_APP; break; case 0x5: result = HSO_PORT_APP2; break; case 0x6: result = HSO_PORT_CONTROL; break; case 0x7: result = HSO_PORT_NETWORK; break; case 0x8: result = HSO_PORT_MODEM; break; case 0x9: result = HSO_PORT_MSD; break; case 0xa: result = HSO_PORT_PCSC; break; case 0xb: result = HSO_PORT_VOICE; break; default: result = 0; } if (result) result |= HSO_INTF_BULK; if (config_data[16] & 0x1) result |= HSO_INFO_CRC_BUG; kfree(config_data); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'USB: hso: Fix OOB memory access in hso_probe/hso_get_config_data The function hso_probe reads if_num from the USB device (as an u8) and uses it without a length check to index an array, resulting in an OOB memory read in hso_probe or hso_get_config_data. Add a length check for both locations and updated hso_probe to bail on error. This issue has been assigned CVE-2018-19985. Reported-by: Hui Peng <[email protected]> Reported-by: Mathias Payer <[email protected]> Signed-off-by: Hui Peng <[email protected]> Signed-off-by: Mathias Payer <[email protected]> Reviewed-by: Sebastian Andrzej Siewior <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int udhcpc_main(int argc UNUSED_PARAM, char **argv) { uint8_t *message; const char *str_V, *str_h, *str_F, *str_r; IF_FEATURE_UDHCPC_ARPING(const char *str_a = "2000";) IF_FEATURE_UDHCP_PORT(char *str_P;) void *clientid_mac_ptr; llist_t *list_O = NULL; llist_t *list_x = NULL; int tryagain_timeout = 20; int discover_timeout = 3; int discover_retries = 3; uint32_t server_addr = server_addr; /* for compiler */ uint32_t requested_ip = 0; uint32_t xid = xid; /* for compiler */ int packet_num; int timeout; /* must be signed */ unsigned already_waited_sec; unsigned opt; IF_FEATURE_UDHCPC_ARPING(unsigned arpping_ms;) int retval; setup_common_bufsiz(); /* Default options */ IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;) IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;) client_config.interface = "eth0"; client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT; str_V = "udhcp "BB_VER; /* Parse command line */ opt = getopt32long(argv, "^" /* O,x: list; -T,-t,-A take numeric param */ "CV:H:h:F:i:np:qRr:s:T:+t:+SA:+O:*ox:*fB" USE_FOR_MMU("b") IF_FEATURE_UDHCPC_ARPING("a::") IF_FEATURE_UDHCP_PORT("P:") "v" "\0" IF_UDHCP_VERBOSE("vv") /* -v is a counter */ , udhcpc_longopts , &str_V, &str_h, &str_h, &str_F , &client_config.interface, &client_config.pidfile /* i,p */ , &str_r /* r */ , &client_config.script /* s */ , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */ , &list_O , &list_x IF_FEATURE_UDHCPC_ARPING(, &str_a) IF_FEATURE_UDHCP_PORT(, &str_P) IF_UDHCP_VERBOSE(, &dhcp_verbose) ); if (opt & (OPT_h|OPT_H)) { //msg added 2011-11 bb_error_msg("option -h NAME is deprecated, use -x hostname:NAME"); client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0); } if (opt & OPT_F) { /* FQDN option format: [0x51][len][flags][0][0]<fqdn> */ client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3); /* Flag bits: 0000NEOS * S: 1 = Client requests server to update A RR in DNS as well as PTR * O: 1 = Server indicates to client that DNS has been updated regardless * E: 1 = Name is in DNS format, i.e. <4>host<6>domain<3>com<0>, * not "host.domain.com". Format 0 is obsolete. * N: 1 = Client requests server to not update DNS (S must be 0 then) * Two [0] bytes which follow are deprecated and must be 0. */ client_config.fqdn[OPT_DATA + 0] = 0x1; /*client_config.fqdn[OPT_DATA + 1] = 0; - xzalloc did it */ /*client_config.fqdn[OPT_DATA + 2] = 0; */ } if (opt & OPT_r) requested_ip = inet_addr(str_r); #if ENABLE_FEATURE_UDHCP_PORT if (opt & OPT_P) { CLIENT_PORT = xatou16(str_P); SERVER_PORT = CLIENT_PORT - 1; } #endif IF_FEATURE_UDHCPC_ARPING(arpping_ms = xatou(str_a);) while (list_O) { char *optstr = llist_pop(&list_O); unsigned n = bb_strtou(optstr, NULL, 0); if (errno || n > 254) { n = udhcp_option_idx(optstr, dhcp_option_strings); n = dhcp_optflags[n].code; } client_config.opt_mask[n >> 3] |= 1 << (n & 7); } if (!(opt & OPT_o)) { unsigned i, n; for (i = 0; (n = dhcp_optflags[i].code) != 0; i++) { if (dhcp_optflags[i].flags & OPTION_REQ) { client_config.opt_mask[n >> 3] |= 1 << (n & 7); } } } while (list_x) { char *optstr = xstrdup(llist_pop(&list_x)); udhcp_str2optset(optstr, &client_config.options, dhcp_optflags, dhcp_option_strings, /*dhcpv6:*/ 0 ); free(optstr); } if (udhcp_read_interface(client_config.interface, &client_config.ifindex, NULL, client_config.client_mac) ) { return 1; } clientid_mac_ptr = NULL; if (!(opt & OPT_C) && !udhcp_find_option(client_config.options, DHCP_CLIENT_ID)) { /* not suppressed and not set, set the default client ID */ client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7); client_config.clientid[OPT_DATA] = 1; /* type: ethernet */ clientid_mac_ptr = client_config.clientid + OPT_DATA+1; memcpy(clientid_mac_ptr, client_config.client_mac, 6); } if (str_V[0] != '\0') { // can drop -V, str_V, client_config.vendorclass, // but need to add "vendor" to the list of recognized // string opts for this to work; // and need to tweak add_client_options() too... // ...so the question is, should we? //bb_error_msg("option -V VENDOR is deprecated, use -x vendor:VENDOR"); client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0); } #if !BB_MMU /* on NOMMU reexec (i.e., background) early */ if (!(opt & OPT_f)) { bb_daemonize_or_rexec(0 /* flags */, argv); logmode = LOGMODE_NONE; } #endif if (opt & OPT_S) { openlog(applet_name, LOG_PID, LOG_DAEMON); logmode |= LOGMODE_SYSLOG; } /* Make sure fd 0,1,2 are open */ bb_sanitize_stdio(); /* Create pidfile */ write_pidfile(client_config.pidfile); /* Goes to stdout (unless NOMMU) and possibly syslog */ bb_error_msg("started, v"BB_VER); /* Set up the signal pipe */ udhcp_sp_setup(); /* We want random_xid to be random... */ srand(monotonic_us()); state = INIT_SELECTING; udhcp_run_script(NULL, "deconfig"); change_listen_mode(LISTEN_RAW); packet_num = 0; timeout = 0; already_waited_sec = 0; /* Main event loop. select() waits on signal pipe and possibly * on sockfd. * "continue" statements in code below jump to the top of the loop. */ for (;;) { int tv; struct pollfd pfds[2]; struct dhcp_packet packet; /* silence "uninitialized!" warning */ unsigned timestamp_before_wait = timestamp_before_wait; //bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode); /* Was opening raw or udp socket here * if (listen_mode != LISTEN_NONE && sockfd < 0), * but on fast network renew responses return faster * than we open sockets. Thus this code is moved * to change_listen_mode(). Thus we open listen socket * BEFORE we send renew request (see "case BOUND:"). */ udhcp_sp_fd_set(pfds, sockfd); tv = timeout - already_waited_sec; retval = 0; /* If we already timed out, fall through with retval = 0, else... */ if (tv > 0) { log1("waiting %u seconds", tv); timestamp_before_wait = (unsigned)monotonic_sec(); retval = poll(pfds, 2, tv < INT_MAX/1000 ? tv * 1000 : INT_MAX); if (retval < 0) { /* EINTR? A signal was caught, don't panic */ if (errno == EINTR) { already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait; continue; } /* Else: an error occurred, panic! */ bb_perror_msg_and_die("poll"); } } /* If timeout dropped to zero, time to become active: * resend discover/renew/whatever */ if (retval == 0) { /* When running on a bridge, the ifindex may have changed * (e.g. if member interfaces were added/removed * or if the status of the bridge changed). * Refresh ifindex and client_mac: */ if (udhcp_read_interface(client_config.interface, &client_config.ifindex, NULL, client_config.client_mac) ) { goto ret0; /* iface is gone? */ } if (clientid_mac_ptr) memcpy(clientid_mac_ptr, client_config.client_mac, 6); /* We will restart the wait in any case */ already_waited_sec = 0; switch (state) { case INIT_SELECTING: if (!discover_retries || packet_num < discover_retries) { if (packet_num == 0) xid = random_xid(); /* broadcast */ send_discover(xid, requested_ip); timeout = discover_timeout; packet_num++; continue; } leasefail: udhcp_run_script(NULL, "leasefail"); #if BB_MMU /* -b is not supported on NOMMU */ if (opt & OPT_b) { /* background if no lease */ bb_error_msg("no lease, forking to background"); client_background(); /* do not background again! */ opt = ((opt & ~OPT_b) | OPT_f); } else #endif if (opt & OPT_n) { /* abort if no lease */ bb_error_msg("no lease, failing"); retval = 1; goto ret; } /* wait before trying again */ timeout = tryagain_timeout; packet_num = 0; continue; case REQUESTING: if (packet_num < 3) { /* send broadcast select packet */ send_select(xid, server_addr, requested_ip); timeout = discover_timeout; packet_num++; continue; } /* Timed out, go back to init state. * "discover...select...discover..." loops * were seen in the wild. Treat them similarly * to "no response to discover" case */ change_listen_mode(LISTEN_RAW); state = INIT_SELECTING; goto leasefail; case BOUND: /* 1/2 lease passed, enter renewing state */ state = RENEWING; client_config.first_secs = 0; /* make secs field count from 0 */ change_listen_mode(LISTEN_KERNEL); log1("entering renew state"); /* fall right through */ case RENEW_REQUESTED: /* manual (SIGUSR1) renew */ case_RENEW_REQUESTED: case RENEWING: if (timeout >= 60) { /* send an unicast renew request */ /* Sometimes observed to fail (EADDRNOTAVAIL) to bind * a new UDP socket for sending inside send_renew. * I hazard to guess existing listening socket * is somehow conflicting with it, but why is it * not deterministic then?! Strange. * Anyway, it does recover by eventually failing through * into INIT_SELECTING state. */ if (send_renew(xid, server_addr, requested_ip) >= 0) { timeout >>= 1; //TODO: the timeout to receive an answer for our renew should not be selected //with "timeout = lease_seconds / 2; ...; timeout = timeout / 2": it is often huge. //Waiting e.g. 4*3600 seconds for a reply does not make sense //(if reply isn't coming, we keep an open socket for hours), //it should be something like 10 seconds. //Also, it's probably best to try sending renew in kernel mode a few (3-5) times //and fall back to raw mode if it does not work. continue; } /* else: error sending. * example: ENETUNREACH seen with server * which gave us bogus server ID 1.1.1.1 * which wasn't reachable (and probably did not exist). */ } /* Timed out or error, enter rebinding state */ log1("entering rebinding state"); state = REBINDING; /* fall right through */ case REBINDING: /* Switch to bcast receive */ change_listen_mode(LISTEN_RAW); /* Lease is *really* about to run out, * try to find DHCP server using broadcast */ if (timeout > 0) { /* send a broadcast renew request */ send_renew(xid, 0 /*INADDR_ANY*/, requested_ip); timeout >>= 1; continue; } /* Timed out, enter init state */ bb_error_msg("lease lost, entering init state"); udhcp_run_script(NULL, "deconfig"); state = INIT_SELECTING; client_config.first_secs = 0; /* make secs field count from 0 */ /*timeout = 0; - already is */ packet_num = 0; continue; /* case RELEASED: */ } /* yah, I know, *you* say it would never happen */ timeout = INT_MAX; continue; /* back to main loop */ } /* if poll timed out */ /* poll() didn't timeout, something happened */ /* Is it a signal? */ switch (udhcp_sp_read()) { case SIGUSR1: client_config.first_secs = 0; /* make secs field count from 0 */ already_waited_sec = 0; perform_renew(); if (state == RENEW_REQUESTED) { /* We might be either on the same network * (in which case renew might work), * or we might be on a completely different one * (in which case renew won't ever succeed). * For the second case, must make sure timeout * is not too big, or else we can send * futile renew requests for hours. */ if (timeout > 60) timeout = 60; goto case_RENEW_REQUESTED; } /* Start things over */ packet_num = 0; /* Kill any timeouts, user wants this to hurry along */ timeout = 0; continue; case SIGUSR2: perform_release(server_addr, requested_ip); timeout = INT_MAX; continue; case SIGTERM: bb_error_msg("received %s", "SIGTERM"); goto ret0; } /* Is it a packet? */ if (!pfds[1].revents) continue; /* no */ { int len; /* A packet is ready, read it */ if (listen_mode == LISTEN_KERNEL) len = udhcp_recv_kernel_packet(&packet, sockfd); else len = udhcp_recv_raw_packet(&packet, sockfd); if (len == -1) { /* Error is severe, reopen socket */ bb_error_msg("read error: "STRERROR_FMT", reopening socket" STRERROR_ERRNO); sleep(discover_timeout); /* 3 seconds by default */ change_listen_mode(listen_mode); /* just close and reopen */ } /* If this packet will turn out to be unrelated/bogus, * we will go back and wait for next one. * Be sure timeout is properly decreased. */ already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait; if (len < 0) continue; } if (packet.xid != xid) { log1("xid %x (our is %x), ignoring packet", (unsigned)packet.xid, (unsigned)xid); continue; } /* Ignore packets that aren't for us */ if (packet.hlen != 6 || memcmp(packet.chaddr, client_config.client_mac, 6) != 0 ) { //FIXME: need to also check that last 10 bytes are zero log1("chaddr does not match, ignoring packet"); // log2? continue; } message = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE); if (message == NULL) { bb_error_msg("no message type option, ignoring packet"); continue; } switch (state) { case INIT_SELECTING: /* Must be a DHCPOFFER */ if (*message == DHCPOFFER) { uint8_t *temp; /* What exactly is server's IP? There are several values. * Example DHCP offer captured with tchdump: * * 10.34.25.254:67 > 10.34.25.202:68 // IP header's src * BOOTP fields: * Your-IP 10.34.25.202 * Server-IP 10.34.32.125 // "next server" IP * Gateway-IP 10.34.25.254 // relay's address (if DHCP relays are in use) * DHCP options: * DHCP-Message Option 53, length 1: Offer * Server-ID Option 54, length 4: 10.34.255.7 // "server ID" * Default-Gateway Option 3, length 4: 10.34.25.254 // router * * We think that real server IP (one to use in renew/release) * is one in Server-ID option. But I am not 100% sure. * IP header's src and Gateway-IP (same in this example) * might work too. * "Next server" and router are definitely wrong ones to use, though... */ /* We used to ignore pcakets without DHCP_SERVER_ID. * I've got user reports from people who run "address-less" servers. * They either supply DHCP_SERVER_ID of 0.0.0.0 or don't supply it at all. * They say ISC DHCP client supports this case. */ server_addr = 0; temp = udhcp_get_option(&packet, DHCP_SERVER_ID); if (!temp) { bb_error_msg("no server ID, using 0.0.0.0"); } else { /* it IS unaligned sometimes, don't "optimize" */ move_from_unaligned32(server_addr, temp); } /*xid = packet.xid; - already is */ requested_ip = packet.yiaddr; /* enter requesting state */ state = REQUESTING; timeout = 0; packet_num = 0; already_waited_sec = 0; } continue; case REQUESTING: case RENEWING: case RENEW_REQUESTED: case REBINDING: if (*message == DHCPACK) { unsigned start; uint32_t lease_seconds; struct in_addr temp_addr; uint8_t *temp; temp = udhcp_get_option(&packet, DHCP_LEASE_TIME); if (!temp) { bb_error_msg("no lease time with ACK, using 1 hour lease"); lease_seconds = 60 * 60; } else { /* it IS unaligned sometimes, don't "optimize" */ move_from_unaligned32(lease_seconds, temp); lease_seconds = ntohl(lease_seconds); /* paranoia: must not be too small and not prone to overflows */ /* timeout > 60 - ensures at least one unicast renew attempt */ if (lease_seconds < 2 * 61) lease_seconds = 2 * 61; //if (lease_seconds > 0x7fffffff) // lease_seconds = 0x7fffffff; //^^^not necessary since "timeout = lease_seconds / 2" //does not overflow even for 0xffffffff. } #if ENABLE_FEATURE_UDHCPC_ARPING if (opt & OPT_a) { /* RFC 2131 3.1 paragraph 5: * "The client receives the DHCPACK message with configuration * parameters. The client SHOULD perform a final check on the * parameters (e.g., ARP for allocated network address), and notes * the duration of the lease specified in the DHCPACK message. At this * point, the client is configured. If the client detects that the * address is already in use (e.g., through the use of ARP), * the client MUST send a DHCPDECLINE message to the server and restarts * the configuration process..." */ if (!arpping(packet.yiaddr, NULL, (uint32_t) 0, client_config.client_mac, client_config.interface, arpping_ms) ) { bb_error_msg("offered address is in use " "(got ARP reply), declining"); send_decline(/*xid,*/ server_addr, packet.yiaddr); if (state != REQUESTING) udhcp_run_script(NULL, "deconfig"); change_listen_mode(LISTEN_RAW); state = INIT_SELECTING; client_config.first_secs = 0; /* make secs field count from 0 */ requested_ip = 0; timeout = tryagain_timeout; packet_num = 0; already_waited_sec = 0; continue; /* back to main loop */ } } #endif /* enter bound state */ temp_addr.s_addr = packet.yiaddr; bb_error_msg("lease of %s obtained, lease time %u", inet_ntoa(temp_addr), (unsigned)lease_seconds); requested_ip = packet.yiaddr; start = monotonic_sec(); udhcp_run_script(&packet, state == REQUESTING ? "bound" : "renew"); already_waited_sec = (unsigned)monotonic_sec() - start; timeout = lease_seconds / 2; if ((unsigned)timeout < already_waited_sec) { /* Something went wrong. Back to discover state */ timeout = already_waited_sec = 0; } state = BOUND; change_listen_mode(LISTEN_NONE); if (opt & OPT_q) { /* quit after lease */ goto ret0; } /* future renew failures should not exit (JM) */ opt &= ~OPT_n; #if BB_MMU /* NOMMU case backgrounded earlier */ if (!(opt & OPT_f)) { client_background(); /* do not background again! */ opt = ((opt & ~OPT_b) | OPT_f); } #endif /* make future renew packets use different xid */ /* xid = random_xid(); ...but why bother? */ continue; /* back to main loop */ } if (*message == DHCPNAK) { /* If network has more than one DHCP server, * "wrong" server can reply first, with a NAK. * Do not interpret it as a NAK from "our" server. */ if (server_addr != 0) { uint32_t svid; uint8_t *temp; temp = udhcp_get_option(&packet, DHCP_SERVER_ID); if (!temp) { non_matching_svid: log1("received DHCP NAK with wrong" " server ID, ignoring packet"); continue; } move_from_unaligned32(svid, temp); if (svid != server_addr) goto non_matching_svid; } /* return to init state */ bb_error_msg("received %s", "DHCP NAK"); udhcp_run_script(&packet, "nak"); if (state != REQUESTING) udhcp_run_script(NULL, "deconfig"); change_listen_mode(LISTEN_RAW); sleep(3); /* avoid excessive network traffic */ state = INIT_SELECTING; client_config.first_secs = 0; /* make secs field count from 0 */ requested_ip = 0; timeout = 0; packet_num = 0; already_waited_sec = 0; } continue; /* case BOUND: - ignore all packets */ /* case RELEASED: - ignore all packets */ } /* back to main loop */ } /* for (;;) - main loop ends */ ret0: if (opt & OPT_R) /* release on quit */ perform_release(server_addr, requested_ip); retval = 0; ret: /*if (client_config.pidfile) - remove_pidfile has its own check */ remove_pidfile(client_config.pidfile); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'udhcpc: check that 4-byte options are indeed 4-byte, closes 11506 function old new delta udhcp_get_option32 - 27 +27 udhcp_get_option 231 248 +17 ------------------------------------------------------------------------------ (add/remove: 1/0 grow/shrink: 1/0 up/down: 44/0) Total: 44 bytes Signed-off-by: Denys Vlasenko <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static uint32_t select_lease_time(struct dhcp_packet *packet) { uint32_t lease_time_sec = server_config.max_lease_sec; uint8_t *lease_time_opt = udhcp_get_option(packet, DHCP_LEASE_TIME); if (lease_time_opt) { move_from_unaligned32(lease_time_sec, lease_time_opt); lease_time_sec = ntohl(lease_time_sec); if (lease_time_sec > server_config.max_lease_sec) lease_time_sec = server_config.max_lease_sec; if (lease_time_sec < server_config.min_lease_sec) lease_time_sec = server_config.min_lease_sec; } return lease_time_sec; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'udhcpc: check that 4-byte options are indeed 4-byte, closes 11506 function old new delta udhcp_get_option32 - 27 +27 udhcp_get_option 231 248 +17 ------------------------------------------------------------------------------ (add/remove: 1/0 grow/shrink: 1/0 up/down: 44/0) Total: 44 bytes Signed-off-by: Denys Vlasenko <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static char **fill_envp(struct dhcp_packet *packet) { int envc; int i; char **envp, **curr; const char *opt_name; uint8_t *temp; uint8_t overload = 0; #define BITMAP unsigned #define BBITS (sizeof(BITMAP) * 8) #define BMASK(i) (1 << (i & (sizeof(BITMAP) * 8 - 1))) #define FOUND_OPTS(i) (found_opts[(unsigned)i / BBITS]) BITMAP found_opts[256 / BBITS]; memset(found_opts, 0, sizeof(found_opts)); /* We need 6 elements for: * "interface=IFACE" * "ip=N.N.N.N" from packet->yiaddr * "siaddr=IP" from packet->siaddr_nip (unless 0) * "boot_file=FILE" from packet->file (unless overloaded) * "sname=SERVER_HOSTNAME" from packet->sname (unless overloaded) * terminating NULL */ envc = 6; /* +1 element for each option, +2 for subnet option: */ if (packet) { /* note: do not search for "pad" (0) and "end" (255) options */ //TODO: change logic to scan packet _once_ for (i = 1; i < 255; i++) { temp = udhcp_get_option(packet, i); if (temp) { if (i == DHCP_OPTION_OVERLOAD) overload |= *temp; else if (i == DHCP_SUBNET) envc++; /* for $mask */ envc++; /*if (i != DHCP_MESSAGE_TYPE)*/ FOUND_OPTS(i) |= BMASK(i); } } } curr = envp = xzalloc(sizeof(envp[0]) * envc); *curr = xasprintf("interface=%s", client_config.interface); putenv(*curr++); if (!packet) return envp; /* Export BOOTP fields. Fields we don't (yet?) export: * uint8_t op; // always BOOTREPLY * uint8_t htype; // hardware address type. 1 = 10mb ethernet * uint8_t hlen; // hardware address length * uint8_t hops; // used by relay agents only * uint32_t xid; * uint16_t secs; // elapsed since client began acquisition/renewal * uint16_t flags; // only one flag so far: bcast. Never set by server * uint32_t ciaddr; // client IP (usually == yiaddr. can it be different * // if during renew server wants to give us different IP?) * uint32_t gateway_nip; // relay agent IP address * uint8_t chaddr[16]; // link-layer client hardware address (MAC) * TODO: export gateway_nip as $giaddr? */ /* Most important one: yiaddr as $ip */ *curr = xmalloc(sizeof("ip=255.255.255.255")); sprint_nip(*curr, "ip=", (uint8_t *) &packet->yiaddr); putenv(*curr++); if (packet->siaddr_nip) { /* IP address of next server to use in bootstrap */ *curr = xmalloc(sizeof("siaddr=255.255.255.255")); sprint_nip(*curr, "siaddr=", (uint8_t *) &packet->siaddr_nip); putenv(*curr++); } if (!(overload & FILE_FIELD) && packet->file[0]) { /* watch out for invalid packets */ *curr = xasprintf("boot_file=%."DHCP_PKT_FILE_LEN_STR"s", packet->file); putenv(*curr++); } if (!(overload & SNAME_FIELD) && packet->sname[0]) { /* watch out for invalid packets */ *curr = xasprintf("sname=%."DHCP_PKT_SNAME_LEN_STR"s", packet->sname); putenv(*curr++); } /* Export known DHCP options */ opt_name = dhcp_option_strings; i = 0; while (*opt_name) { uint8_t code = dhcp_optflags[i].code; BITMAP *found_ptr = &FOUND_OPTS(code); BITMAP found_mask = BMASK(code); if (!(*found_ptr & found_mask)) goto next; *found_ptr &= ~found_mask; /* leave only unknown options */ temp = udhcp_get_option(packet, code); *curr = xmalloc_optname_optval(temp, &dhcp_optflags[i], opt_name); putenv(*curr++); if (code == DHCP_SUBNET) { /* Subnet option: make things like "$ip/$mask" possible */ uint32_t subnet; move_from_unaligned32(subnet, temp); *curr = xasprintf("mask=%u", mton(subnet)); putenv(*curr++); } next: opt_name += strlen(opt_name) + 1; i++; } /* Export unknown options */ for (i = 0; i < 256;) { BITMAP bitmap = FOUND_OPTS(i); if (!bitmap) { i += BBITS; continue; } if (bitmap & BMASK(i)) { unsigned len, ofs; temp = udhcp_get_option(packet, i); /* udhcp_get_option returns ptr to data portion, * need to go back to get len */ len = temp[-OPT_DATA + OPT_LEN]; *curr = xmalloc(sizeof("optNNN=") + 1 + len*2); ofs = sprintf(*curr, "opt%u=", i); *bin2hex(*curr + ofs, (void*) temp, len) = '\0'; putenv(*curr++); } i++; } return envp; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'udhcpc: when decoding DHCP_SUBNET, ensure it is 4 bytes long function old new delta udhcp_run_script 795 801 +6 Signed-off-by: Denys Vlasenko <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void comps_objrtree_unite(COMPS_ObjRTree *rt1, COMPS_ObjRTree *rt2) { COMPS_HSList *tmplist, *tmp_subnodes; COMPS_HSListItem *it; struct Pair { COMPS_HSList * subnodes; char * key; char added; } *pair, *parent_pair; pair = malloc(sizeof(struct Pair)); pair->subnodes = rt2->subnodes; pair->key = NULL; tmplist = comps_hslist_create(); comps_hslist_init(tmplist, NULL, NULL, &free); comps_hslist_append(tmplist, pair, 0); while (tmplist->first != NULL) { it = tmplist->first; comps_hslist_remove(tmplist, tmplist->first); tmp_subnodes = ((struct Pair*)it->data)->subnodes; parent_pair = (struct Pair*) it->data; //printf("key-part:%s\n", parent_pair->key); free(it); //pair->added = 0; for (it = tmp_subnodes->first; it != NULL; it=it->next) { pair = malloc(sizeof(struct Pair)); pair->subnodes = ((COMPS_ObjRTreeData*)it->data)->subnodes; if (parent_pair->key != NULL) { pair->key = malloc(sizeof(char) * (strlen(((COMPS_ObjRTreeData*)it->data)->key) + strlen(parent_pair->key) + 1)); memcpy(pair->key, parent_pair->key, sizeof(char) * strlen(parent_pair->key)); memcpy(pair->key + strlen(parent_pair->key), ((COMPS_ObjRTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_ObjRTreeData*)it->data)->key)+1)); } else { pair->key = malloc(sizeof(char)* (strlen(((COMPS_ObjRTreeData*)it->data)->key) +1)); memcpy(pair->key, ((COMPS_ObjRTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_ObjRTreeData*)it->data)->key)+1)); } /* current node has data */ if (((COMPS_ObjRTreeData*)it->data)->data != NULL) { comps_objrtree_set(rt1, pair->key, (((COMPS_ObjRTreeData*)it->data)->data)); } if (((COMPS_ObjRTreeData*)it->data)->subnodes->first) { comps_hslist_append(tmplist, pair, 0); } else { free(pair->key); free(pair); } } free(parent_pair->key); free(parent_pair); } comps_hslist_destroy(&tmplist); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-862'], 'message': 'Fix UAF in comps_objmrtree_unite function The added field is not used at all in many places and it is probably the left-over of some copy-paste.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void comps_rtree_unite(COMPS_RTree *rt1, COMPS_RTree *rt2) { COMPS_HSList *tmplist, *tmp_subnodes; COMPS_HSListItem *it; struct Pair { COMPS_HSList * subnodes; char * key; char added; } *pair, *parent_pair; pair = malloc(sizeof(struct Pair)); pair->subnodes = rt2->subnodes; pair->key = NULL; tmplist = comps_hslist_create(); comps_hslist_init(tmplist, NULL, NULL, &free); comps_hslist_append(tmplist, pair, 0); while (tmplist->first != NULL) { it = tmplist->first; comps_hslist_remove(tmplist, tmplist->first); tmp_subnodes = ((struct Pair*)it->data)->subnodes; parent_pair = (struct Pair*) it->data; free(it); for (it = tmp_subnodes->first; it != NULL; it=it->next) { pair = malloc(sizeof(struct Pair)); pair->subnodes = ((COMPS_RTreeData*)it->data)->subnodes; if (parent_pair->key != NULL) { pair->key = malloc(sizeof(char) * (strlen(((COMPS_RTreeData*)it->data)->key) + strlen(parent_pair->key) + 1)); memcpy(pair->key, parent_pair->key, sizeof(char) * strlen(parent_pair->key)); memcpy(pair->key + strlen(parent_pair->key), ((COMPS_RTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_RTreeData*)it->data)->key)+1)); } else { pair->key = malloc(sizeof(char)* (strlen(((COMPS_RTreeData*)it->data)->key) +1)); memcpy(pair->key, ((COMPS_RTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_RTreeData*)it->data)->key)+1)); } /* current node has data */ if (((COMPS_RTreeData*)it->data)->data != NULL) { comps_rtree_set(rt1, pair->key, rt2->data_cloner(((COMPS_RTreeData*)it->data)->data)); } if (((COMPS_RTreeData*)it->data)->subnodes->first) { comps_hslist_append(tmplist, pair, 0); } else { free(pair->key); free(pair); } } free(parent_pair->key); free(parent_pair); } comps_hslist_destroy(&tmplist); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-862'], 'message': 'Fix UAF in comps_objmrtree_unite function The added field is not used at all in many places and it is probably the left-over of some copy-paste.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static const char* getenv_harder(pam_handle_t *handle, const char *key, const char *fallback) { const char *v; assert(handle); assert(key); /* Looks for an environment variable, preferrably in the environment block associated with the specified PAM * handle, falling back to the process' block instead. */ v = pam_getenv(handle, key); if (!isempty(v)) return v; v = getenv(key); if (!isempty(v)) return v; return fallback; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-863'], 'message': 'pam-systemd: use secure_getenv() rather than getenv() And explain why in a comment.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: i915_gem_execbuffer2_ioctl(struct drm_device *dev, void *data, struct drm_file *file) { struct drm_i915_gem_execbuffer2 *args = data; struct drm_i915_gem_exec_object2 *exec2_list; struct drm_syncobj **fences = NULL; const size_t count = args->buffer_count; int err; if (!check_buffer_count(count)) { DRM_DEBUG("execbuf2 with %zd buffers\n", count); return -EINVAL; } if (!i915_gem_check_execbuffer(args)) return -EINVAL; /* Allocate an extra slot for use by the command parser */ exec2_list = kvmalloc_array(count + 1, eb_element_size(), __GFP_NOWARN | GFP_KERNEL); if (exec2_list == NULL) { DRM_DEBUG("Failed to allocate exec list for %zd buffers\n", count); return -ENOMEM; } if (copy_from_user(exec2_list, u64_to_user_ptr(args->buffers_ptr), sizeof(*exec2_list) * count)) { DRM_DEBUG("copy %zd exec entries failed\n", count); kvfree(exec2_list); return -EFAULT; } if (args->flags & I915_EXEC_FENCE_ARRAY) { fences = get_fence_array(args, file); if (IS_ERR(fences)) { kvfree(exec2_list); return PTR_ERR(fences); } } err = i915_gem_do_execbuffer(dev, file, args, exec2_list, fences); /* * Now that we have begun execution of the batchbuffer, we ignore * any new error after this point. Also given that we have already * updated the associated relocations, we try to write out the current * object locations irrespective of any error. */ if (args->flags & __EXEC_HAS_RELOC) { struct drm_i915_gem_exec_object2 __user *user_exec_list = u64_to_user_ptr(args->buffers_ptr); unsigned int i; /* Copy the new buffer offsets back to the user's exec list. */ user_access_begin(); for (i = 0; i < args->buffer_count; i++) { if (!(exec2_list[i].offset & UPDATE)) continue; exec2_list[i].offset = gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK); unsafe_put_user(exec2_list[i].offset, &user_exec_list[i].offset, end_user); } end_user: user_access_end(); } args->flags &= ~__I915_EXEC_UNKNOWN_FLAGS; put_fence_array(args, fences); kvfree(exec2_list); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'make 'user_access_begin()' do 'access_ok()' Originally, the rule used to be that you'd have to do access_ok() separately, and then user_access_begin() before actually doing the direct (optimized) user access. But experience has shown that people then decide not to do access_ok() at all, and instead rely on it being implied by other operations or similar. Which makes it very hard to verify that the access has actually been range-checked. If you use the unsafe direct user accesses, hardware features (either SMAP - Supervisor Mode Access Protection - on x86, or PAN - Privileged Access Never - on ARM) do force you to use user_access_begin(). But nothing really forces the range check. By putting the range check into user_access_begin(), we actually force people to do the right thing (tm), and the range check vill be visible near the actual accesses. We have way too long a history of people trying to avoid them. Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: long strncpy_from_user(char *dst, const char __user *src, long count) { unsigned long max_addr, src_addr; if (unlikely(count <= 0)) return 0; max_addr = user_addr_max(); src_addr = (unsigned long)src; if (likely(src_addr < max_addr)) { unsigned long max = max_addr - src_addr; long retval; kasan_check_write(dst, count); check_object_size(dst, count, false); user_access_begin(); retval = do_strncpy_from_user(dst, src, count, max); user_access_end(); return retval; } return -EFAULT; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'make 'user_access_begin()' do 'access_ok()' Originally, the rule used to be that you'd have to do access_ok() separately, and then user_access_begin() before actually doing the direct (optimized) user access. But experience has shown that people then decide not to do access_ok() at all, and instead rely on it being implied by other operations or similar. Which makes it very hard to verify that the access has actually been range-checked. If you use the unsafe direct user accesses, hardware features (either SMAP - Supervisor Mode Access Protection - on x86, or PAN - Privileged Access Never - on ARM) do force you to use user_access_begin(). But nothing really forces the range check. By putting the range check into user_access_begin(), we actually force people to do the right thing (tm), and the range check vill be visible near the actual accesses. We have way too long a history of people trying to avoid them. Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: long compat_get_bitmap(unsigned long *mask, const compat_ulong_t __user *umask, unsigned long bitmap_size) { unsigned long nr_compat_longs; /* align bitmap up to nearest compat_long_t boundary */ bitmap_size = ALIGN(bitmap_size, BITS_PER_COMPAT_LONG); nr_compat_longs = BITS_TO_COMPAT_LONGS(bitmap_size); if (!access_ok(umask, bitmap_size / 8)) return -EFAULT; user_access_begin(); while (nr_compat_longs > 1) { compat_ulong_t l1, l2; unsafe_get_user(l1, umask++, Efault); unsafe_get_user(l2, umask++, Efault); *mask++ = ((unsigned long)l2 << BITS_PER_COMPAT_LONG) | l1; nr_compat_longs -= 2; } if (nr_compat_longs) unsafe_get_user(*mask, umask++, Efault); user_access_end(); return 0; Efault: user_access_end(); return -EFAULT; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'make 'user_access_begin()' do 'access_ok()' Originally, the rule used to be that you'd have to do access_ok() separately, and then user_access_begin() before actually doing the direct (optimized) user access. But experience has shown that people then decide not to do access_ok() at all, and instead rely on it being implied by other operations or similar. Which makes it very hard to verify that the access has actually been range-checked. If you use the unsafe direct user accesses, hardware features (either SMAP - Supervisor Mode Access Protection - on x86, or PAN - Privileged Access Never - on ARM) do force you to use user_access_begin(). But nothing really forces the range check. By putting the range check into user_access_begin(), we actually force people to do the right thing (tm), and the range check vill be visible near the actual accesses. We have way too long a history of people trying to avoid them. Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: long compat_put_bitmap(compat_ulong_t __user *umask, unsigned long *mask, unsigned long bitmap_size) { unsigned long nr_compat_longs; /* align bitmap up to nearest compat_long_t boundary */ bitmap_size = ALIGN(bitmap_size, BITS_PER_COMPAT_LONG); nr_compat_longs = BITS_TO_COMPAT_LONGS(bitmap_size); if (!access_ok(umask, bitmap_size / 8)) return -EFAULT; user_access_begin(); while (nr_compat_longs > 1) { unsigned long m = *mask++; unsafe_put_user((compat_ulong_t)m, umask++, Efault); unsafe_put_user(m >> BITS_PER_COMPAT_LONG, umask++, Efault); nr_compat_longs -= 2; } if (nr_compat_longs) unsafe_put_user((compat_ulong_t)*mask, umask++, Efault); user_access_end(); return 0; Efault: user_access_end(); return -EFAULT; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'make 'user_access_begin()' do 'access_ok()' Originally, the rule used to be that you'd have to do access_ok() separately, and then user_access_begin() before actually doing the direct (optimized) user access. But experience has shown that people then decide not to do access_ok() at all, and instead rely on it being implied by other operations or similar. Which makes it very hard to verify that the access has actually been range-checked. If you use the unsafe direct user accesses, hardware features (either SMAP - Supervisor Mode Access Protection - on x86, or PAN - Privileged Access Never - on ARM) do force you to use user_access_begin(). But nothing really forces the range check. By putting the range check into user_access_begin(), we actually force people to do the right thing (tm), and the range check vill be visible near the actual accesses. We have way too long a history of people trying to avoid them. Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void hid_dump_input(struct hid_device *hdev, struct hid_usage *usage, __s32 value) { char *buf; int len; buf = hid_resolv_usage(usage->hid, NULL); if (!buf) return; len = strlen(buf); snprintf(buf + len, HID_DEBUG_BUFSIZE - len - 1, " = %d\n", value); hid_debug_event(hdev, buf); kfree(buf); wake_up_interruptible(&hdev->debug_wait); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'HID: debug: fix the ring buffer implementation Ring buffer implementation in hid_debug_event() and hid_debug_events_read() is strange allowing lost or corrupted data. After commit 717adfdaf147 ("HID: debug: check length before copy_to_user()") it is possible to enter an infinite loop in hid_debug_events_read() by providing 0 as count, this locks up a system. Fix this by rewriting the ring buffer implementation with kfifo and simplify the code. This fixes CVE-2019-3819. v2: fix an execution logic and add a comment v3: use __set_current_state() instead of set_current_state() Link: https://bugzilla.redhat.com/show_bug.cgi?id=1669187 Cc: [email protected] # v4.18+ Fixes: cd667ce24796 ("HID: use debugfs for events/reports dumping") Fixes: 717adfdaf147 ("HID: debug: check length before copy_to_user()") Signed-off-by: Vladis Dronov <[email protected]> Reviewed-by: Oleg Nesterov <[email protected]> Signed-off-by: Benjamin Tissoires <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void hid_debug_event(struct hid_device *hdev, char *buf) { unsigned i; struct hid_debug_list *list; unsigned long flags; spin_lock_irqsave(&hdev->debug_list_lock, flags); list_for_each_entry(list, &hdev->debug_list, node) { for (i = 0; buf[i]; i++) list->hid_debug_buf[(list->tail + i) % HID_DEBUG_BUFSIZE] = buf[i]; list->tail = (list->tail + i) % HID_DEBUG_BUFSIZE; } spin_unlock_irqrestore(&hdev->debug_list_lock, flags); wake_up_interruptible(&hdev->debug_wait); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'HID: debug: fix the ring buffer implementation Ring buffer implementation in hid_debug_event() and hid_debug_events_read() is strange allowing lost or corrupted data. After commit 717adfdaf147 ("HID: debug: check length before copy_to_user()") it is possible to enter an infinite loop in hid_debug_events_read() by providing 0 as count, this locks up a system. Fix this by rewriting the ring buffer implementation with kfifo and simplify the code. This fixes CVE-2019-3819. v2: fix an execution logic and add a comment v3: use __set_current_state() instead of set_current_state() Link: https://bugzilla.redhat.com/show_bug.cgi?id=1669187 Cc: [email protected] # v4.18+ Fixes: cd667ce24796 ("HID: use debugfs for events/reports dumping") Fixes: 717adfdaf147 ("HID: debug: check length before copy_to_user()") Signed-off-by: Vladis Dronov <[email protected]> Reviewed-by: Oleg Nesterov <[email protected]> Signed-off-by: Benjamin Tissoires <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t hid_debug_events_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos) { struct hid_debug_list *list = file->private_data; int ret = 0, len; DECLARE_WAITQUEUE(wait, current); mutex_lock(&list->read_mutex); while (ret == 0) { if (list->head == list->tail) { add_wait_queue(&list->hdev->debug_wait, &wait); set_current_state(TASK_INTERRUPTIBLE); while (list->head == list->tail) { if (file->f_flags & O_NONBLOCK) { ret = -EAGAIN; break; } if (signal_pending(current)) { ret = -ERESTARTSYS; break; } if (!list->hdev || !list->hdev->debug) { ret = -EIO; set_current_state(TASK_RUNNING); goto out; } /* allow O_NONBLOCK from other threads */ mutex_unlock(&list->read_mutex); schedule(); mutex_lock(&list->read_mutex); set_current_state(TASK_INTERRUPTIBLE); } set_current_state(TASK_RUNNING); remove_wait_queue(&list->hdev->debug_wait, &wait); } if (ret) goto out; /* pass the ringbuffer contents to userspace */ copy_rest: if (list->tail == list->head) goto out; if (list->tail > list->head) { len = list->tail - list->head; if (len > count) len = count; if (copy_to_user(buffer + ret, &list->hid_debug_buf[list->head], len)) { ret = -EFAULT; goto out; } ret += len; list->head += len; } else { len = HID_DEBUG_BUFSIZE - list->head; if (len > count) len = count; if (copy_to_user(buffer, &list->hid_debug_buf[list->head], len)) { ret = -EFAULT; goto out; } list->head = 0; ret += len; count -= len; if (count > 0) goto copy_rest; } } out: mutex_unlock(&list->read_mutex); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'HID: debug: fix the ring buffer implementation Ring buffer implementation in hid_debug_event() and hid_debug_events_read() is strange allowing lost or corrupted data. After commit 717adfdaf147 ("HID: debug: check length before copy_to_user()") it is possible to enter an infinite loop in hid_debug_events_read() by providing 0 as count, this locks up a system. Fix this by rewriting the ring buffer implementation with kfifo and simplify the code. This fixes CVE-2019-3819. v2: fix an execution logic and add a comment v3: use __set_current_state() instead of set_current_state() Link: https://bugzilla.redhat.com/show_bug.cgi?id=1669187 Cc: [email protected] # v4.18+ Fixes: cd667ce24796 ("HID: use debugfs for events/reports dumping") Fixes: 717adfdaf147 ("HID: debug: check length before copy_to_user()") Signed-off-by: Vladis Dronov <[email protected]> Reviewed-by: Oleg Nesterov <[email protected]> Signed-off-by: Benjamin Tissoires <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: seamless_process(STREAM s) { unsigned int pkglen; char *buf; pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); #if 0 printf("seamless recv:\n"); hexdump(s->p, pkglen); #endif str_handle_lines(buf, &seamless_rest, seamless_line_handler, NULL); xfree(buf); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mcs_parse_domain_params(STREAM s) { int length; ber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length); in_uint8s(s, length); return s_check(s); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: lspci_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); #if 0 printf("lspci recv:\n"); hexdump(s->p, pkglen); #endif str_handle_lines(buf, &rest, lspci_process_line, NULL); xfree(buf); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: process_bitmap_updates(STREAM s) { uint16 num_updates; uint16 left, top, right, bottom, width, height; uint16 cx, cy, bpp, Bpp, compress, bufsize, size; uint8 *data, *bmpdata; int i; in_uint16_le(s, num_updates); for (i = 0; i < num_updates; i++) { in_uint16_le(s, left); in_uint16_le(s, top); in_uint16_le(s, right); in_uint16_le(s, bottom); in_uint16_le(s, width); in_uint16_le(s, height); in_uint16_le(s, bpp); Bpp = (bpp + 7) / 8; in_uint16_le(s, compress); in_uint16_le(s, bufsize); cx = right - left + 1; cy = bottom - top + 1; DEBUG(("BITMAP_UPDATE(l=%d,t=%d,r=%d,b=%d,w=%d,h=%d,Bpp=%d,cmp=%d)\n", left, top, right, bottom, width, height, Bpp, compress)); if (!compress) { int y; bmpdata = (uint8 *) xmalloc(width * height * Bpp); for (y = 0; y < height; y++) { in_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)], width * Bpp); } ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata); xfree(bmpdata); continue; } if (compress & 0x400) { size = bufsize; } else { in_uint8s(s, 2); /* pad */ in_uint16_le(s, size); in_uint8s(s, 4); /* line_size, final_size */ } in_uint8p(s, data, size); bmpdata = (uint8 *) xmalloc(width * height * Bpp); if (bitmap_decompress(bmpdata, width, height, data, size, Bpp)) { ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata); } else { DEBUG_RDP5(("Failed to decompress data\n")); } xfree(bmpdata); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mcs_recv_connect_response(STREAM mcs_data) { uint8 result; int length; STREAM s; s = iso_recv(NULL); if (s == NULL) return False; ber_parse_header(s, MCS_CONNECT_RESPONSE, &length); ber_parse_header(s, BER_TAG_RESULT, &length); in_uint8(s, result); if (result != 0) { error("MCS connect: %d\n", result); return False; } ber_parse_header(s, BER_TAG_INTEGER, &length); in_uint8s(s, length); /* connect id */ mcs_parse_domain_params(s); ber_parse_header(s, BER_TAG_OCTET_STRING, &length); sec_process_mcs_data(s); /* if (length > mcs_data->size) { error("MCS data length %d, expected %d\n", length, mcs_data->size); length = mcs_data->size; } in_uint8a(s, mcs_data->data, length); mcs_data->p = mcs_data->data; mcs_data->end = mcs_data->data + length; */ return s_check_end(s); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: process_secondary_order(STREAM s) { /* The length isn't calculated correctly by the server. * For very compact orders the length becomes negative * so a signed integer must be used. */ uint16 length; uint16 flags; uint8 type; uint8 *next_order; in_uint16_le(s, length); in_uint16_le(s, flags); /* used by bmpcache2 */ in_uint8(s, type); next_order = s->p + (sint16) length + 7; switch (type) { case RDP_ORDER_RAW_BMPCACHE: process_raw_bmpcache(s); break; case RDP_ORDER_COLCACHE: process_colcache(s); break; case RDP_ORDER_BMPCACHE: process_bmpcache(s); break; case RDP_ORDER_FONTCACHE: process_fontcache(s); break; case RDP_ORDER_RAW_BMPCACHE2: process_bmpcache2(s, flags, False); /* uncompressed */ break; case RDP_ORDER_BMPCACHE2: process_bmpcache2(s, flags, True); /* compressed */ break; case RDP_ORDER_BRUSHCACHE: process_brushcache(s, flags); break; default: unimpl("secondary order %d\n", type); } s->p = next_order; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: sec_parse_crypt_info(STREAM s, uint32 * rc4_key_size, uint8 ** server_random, uint8 * modulus, uint8 * exponent) { uint32 crypt_level, random_len, rsa_info_len; uint32 cacert_len, cert_len, flags; RDSSL_CERT *cacert, *server_cert; RDSSL_RKEY *server_public_key; uint16 tag, length; uint8 *next_tag, *end; in_uint32_le(s, *rc4_key_size); /* 1 = 40-bit, 2 = 128-bit */ in_uint32_le(s, crypt_level); /* 1 = low, 2 = medium, 3 = high */ if (crypt_level == 0) { /* no encryption */ return False; } in_uint32_le(s, random_len); in_uint32_le(s, rsa_info_len); if (random_len != SEC_RANDOM_SIZE) { error("random len %d, expected %d\n", random_len, SEC_RANDOM_SIZE); return False; } in_uint8p(s, *server_random, random_len); /* RSA info */ end = s->p + rsa_info_len; if (end > s->end) return False; in_uint32_le(s, flags); /* 1 = RDP4-style, 0x80000002 = X.509 */ if (flags & 1) { DEBUG_RDP5(("We're going for the RDP4-style encryption\n")); in_uint8s(s, 8); /* unknown */ while (s->p < end) { in_uint16_le(s, tag); in_uint16_le(s, length); next_tag = s->p + length; switch (tag) { case SEC_TAG_PUBKEY: if (!sec_parse_public_key(s, modulus, exponent)) return False; DEBUG_RDP5(("Got Public key, RDP4-style\n")); break; case SEC_TAG_KEYSIG: if (!sec_parse_public_sig(s, length, modulus, exponent)) return False; break; default: unimpl("crypt tag 0x%x\n", tag); } s->p = next_tag; } } else { uint32 certcount; DEBUG_RDP5(("We're going for the RDP5-style encryption\n")); in_uint32_le(s, certcount); /* Number of certificates */ if (certcount < 2) { error("Server didn't send enough X509 certificates\n"); return False; } for (; certcount > 2; certcount--) { /* ignore all the certificates between the root and the signing CA */ uint32 ignorelen; RDSSL_CERT *ignorecert; DEBUG_RDP5(("Ignored certs left: %d\n", certcount)); in_uint32_le(s, ignorelen); DEBUG_RDP5(("Ignored Certificate length is %d\n", ignorelen)); ignorecert = rdssl_cert_read(s->p, ignorelen); in_uint8s(s, ignorelen); if (ignorecert == NULL) { /* XXX: error out? */ DEBUG_RDP5(("got a bad cert: this will probably screw up the rest of the communication\n")); } #ifdef WITH_DEBUG_RDP5 DEBUG_RDP5(("cert #%d (ignored):\n", certcount)); rdssl_cert_print_fp(stdout, ignorecert); #endif } /* Do da funky X.509 stuffy "How did I find out about this? I looked up and saw a bright light and when I came to I had a scar on my forehead and knew about X.500" - Peter Gutman in a early version of http://www.cs.auckland.ac.nz/~pgut001/pubs/x509guide.txt */ in_uint32_le(s, cacert_len); DEBUG_RDP5(("CA Certificate length is %d\n", cacert_len)); cacert = rdssl_cert_read(s->p, cacert_len); in_uint8s(s, cacert_len); if (NULL == cacert) { error("Couldn't load CA Certificate from server\n"); return False; } in_uint32_le(s, cert_len); DEBUG_RDP5(("Certificate length is %d\n", cert_len)); server_cert = rdssl_cert_read(s->p, cert_len); in_uint8s(s, cert_len); if (NULL == server_cert) { rdssl_cert_free(cacert); error("Couldn't load Certificate from server\n"); return False; } if (!rdssl_certs_ok(server_cert, cacert)) { rdssl_cert_free(server_cert); rdssl_cert_free(cacert); error("Security error CA Certificate invalid\n"); return False; } rdssl_cert_free(cacert); in_uint8s(s, 16); /* Padding */ server_public_key = rdssl_cert_to_rkey(server_cert, &g_server_public_key_len); if (NULL == server_public_key) { DEBUG_RDP5(("Didn't parse X509 correctly\n")); rdssl_cert_free(server_cert); return False; } rdssl_cert_free(server_cert); if ((g_server_public_key_len < SEC_MODULUS_SIZE) || (g_server_public_key_len > SEC_MAX_MODULUS_SIZE)) { error("Bad server public key size (%u bits)\n", g_server_public_key_len * 8); rdssl_rkey_free(server_public_key); return False; } if (rdssl_rkey_get_exp_mod(server_public_key, exponent, SEC_EXPONENT_SIZE, modulus, SEC_MAX_MODULUS_SIZE) != 0) { error("Problem extracting RSA exponent, modulus"); rdssl_rkey_free(server_public_key); return False; } rdssl_rkey_free(server_public_key); return True; /* There's some garbage here we don't care about */ } return s_check_end(s); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: process_plane(uint8 * in, int width, int height, uint8 * out, int size) { int indexw; int indexh; int code; int collen; int replen; int color; int x; int revcode; uint8 * last_line; uint8 * this_line; uint8 * org_in; uint8 * org_out; org_in = in; org_out = out; last_line = 0; indexh = 0; while (indexh < height) { out = (org_out + width * height * 4) - ((indexh + 1) * width * 4); color = 0; this_line = out; indexw = 0; if (last_line == 0) { while (indexw < width) { code = CVAL(in); replen = code & 0xf; collen = (code >> 4) & 0xf; revcode = (replen << 4) | collen; if ((revcode <= 47) && (revcode >= 16)) { replen = revcode; collen = 0; } while (collen > 0) { color = CVAL(in); *out = color; out += 4; indexw++; collen--; } while (replen > 0) { *out = color; out += 4; indexw++; replen--; } } } else { while (indexw < width) { code = CVAL(in); replen = code & 0xf; collen = (code >> 4) & 0xf; revcode = (replen << 4) | collen; if ((revcode <= 47) && (revcode >= 16)) { replen = revcode; collen = 0; } while (collen > 0) { x = CVAL(in); if (x & 1) { x = x >> 1; x = x + 1; color = -x; } else { x = x >> 1; color = x; } x = last_line[indexw * 4] + color; *out = x; out += 4; indexw++; collen--; } while (replen > 0) { x = last_line[indexw * 4] + color; *out = x; out += 4; indexw++; replen--; } } } indexh++; last_line = this_line; } return (int) (in - org_in); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cssp_read_tsrequest(STREAM token, STREAM pubkey) { STREAM s; int length; int tagval; s = tcp_recv(NULL, 4); if (s == NULL) return False; // verify ASN.1 header if (s->p[0] != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) { error("Expected BER_TAG_SEQUENCE|BER_TAG_CONSTRUCTED, got %x", s->p[0]); return False; } // peek at first 4 bytes to get full message length if (s->p[1] < 0x80) length = s->p[1] - 2; else if (s->p[1] == 0x81) length = s->p[2] - 1; else if (s->p[1] == 0x82) length = (s->p[2] << 8) | s->p[3]; else return False; // receive the remainings of message s = tcp_recv(s, length); #if WITH_DEBUG_CREDSSP streamsave(s, "tsrequest_in.raw"); printf("In TSRequest token %ld bytes\n", s_length(s)); hexdump(s->data, s_length(s)); #endif // parse the response and into nego token if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; // version [0] if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0)) return False; in_uint8s(s, length); // negoToken [1] if (token) { if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING) return False; token->end = token->p = token->data; out_uint8p(token, s->p, length); s_mark_end(token); } // pubKey [3] if (pubkey) { if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING) return False; pubkey->data = pubkey->p = s->p; pubkey->end = pubkey->data + length; pubkey->size = length; } return True; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: seamless_process_line(const char *line, void *data) { char *p, *l; char *tok1, *tok2, *tok3, *tok4, *tok5, *tok6, *tok7, *tok8; unsigned long id, flags; char *endptr; l = xstrdup(line); p = l; DEBUG_SEAMLESS(("seamlessrdp got:%s\n", p)); tok1 = seamless_get_token(&p); tok2 = seamless_get_token(&p); tok3 = seamless_get_token(&p); tok4 = seamless_get_token(&p); tok5 = seamless_get_token(&p); tok6 = seamless_get_token(&p); tok7 = seamless_get_token(&p); tok8 = seamless_get_token(&p); if (!strcmp("CREATE", tok1)) { unsigned long group, parent; if (!tok6) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; group = strtoul(tok4, &endptr, 0); if (*endptr) return False; parent = strtoul(tok5, &endptr, 0); if (*endptr) return False; flags = strtoul(tok6, &endptr, 0); if (*endptr) return False; ui_seamless_create_window(id, group, parent, flags); } else if (!strcmp("DESTROY", tok1)) { if (!tok4) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; flags = strtoul(tok4, &endptr, 0); if (*endptr) return False; ui_seamless_destroy_window(id, flags); } else if (!strcmp("DESTROYGRP", tok1)) { if (!tok4) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; flags = strtoul(tok4, &endptr, 0); if (*endptr) return False; ui_seamless_destroy_group(id, flags); } else if (!strcmp("SETICON", tok1)) { int chunk, width, height, len; char byte[3]; if (!tok8) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; chunk = strtoul(tok4, &endptr, 0); if (*endptr) return False; width = strtoul(tok6, &endptr, 0); if (*endptr) return False; height = strtoul(tok7, &endptr, 0); if (*endptr) return False; byte[2] = '\0'; len = 0; while (*tok8 != '\0') { byte[0] = *tok8; tok8++; if (*tok8 == '\0') return False; byte[1] = *tok8; tok8++; icon_buf[len] = strtol(byte, NULL, 16); len++; } ui_seamless_seticon(id, tok5, width, height, chunk, icon_buf, len); } else if (!strcmp("DELICON", tok1)) { int width, height; if (!tok6) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; width = strtoul(tok5, &endptr, 0); if (*endptr) return False; height = strtoul(tok6, &endptr, 0); if (*endptr) return False; ui_seamless_delicon(id, tok4, width, height); } else if (!strcmp("POSITION", tok1)) { int x, y, width, height; if (!tok8) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; x = strtol(tok4, &endptr, 0); if (*endptr) return False; y = strtol(tok5, &endptr, 0); if (*endptr) return False; width = strtol(tok6, &endptr, 0); if (*endptr) return False; height = strtol(tok7, &endptr, 0); if (*endptr) return False; flags = strtoul(tok8, &endptr, 0); if (*endptr) return False; ui_seamless_move_window(id, x, y, width, height, flags); } else if (!strcmp("ZCHANGE", tok1)) { unsigned long behind; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; behind = strtoul(tok4, &endptr, 0); if (*endptr) return False; flags = strtoul(tok5, &endptr, 0); if (*endptr) return False; ui_seamless_restack_window(id, behind, flags); } else if (!strcmp("TITLE", tok1)) { if (!tok5) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; flags = strtoul(tok5, &endptr, 0); if (*endptr) return False; ui_seamless_settitle(id, tok4, flags); } else if (!strcmp("STATE", tok1)) { unsigned int state; if (!tok5) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; state = strtoul(tok4, &endptr, 0); if (*endptr) return False; flags = strtoul(tok5, &endptr, 0); if (*endptr) return False; ui_seamless_setstate(id, state, flags); } else if (!strcmp("DEBUG", tok1)) { DEBUG_SEAMLESS(("SeamlessRDP:%s\n", line)); } else if (!strcmp("SYNCBEGIN", tok1)) { if (!tok3) return False; flags = strtoul(tok3, &endptr, 0); if (*endptr) return False; ui_seamless_syncbegin(flags); } else if (!strcmp("SYNCEND", tok1)) { if (!tok3) return False; flags = strtoul(tok3, &endptr, 0); if (*endptr) return False; /* do nothing, currently */ } else if (!strcmp("HELLO", tok1)) { if (!tok3) return False; flags = strtoul(tok3, &endptr, 0); if (*endptr) return False; ui_seamless_begin(! !(flags & SEAMLESSRDP_HELLO_HIDDEN)); } else if (!strcmp("ACK", tok1)) { unsigned int serial; serial = strtoul(tok3, &endptr, 0); if (*endptr) return False; ui_seamless_ack(serial); } else if (!strcmp("HIDE", tok1)) { if (!tok3) return False; flags = strtoul(tok3, &endptr, 0); if (*endptr) return False; ui_seamless_hide_desktop(); } else if (!strcmp("UNHIDE", tok1)) { if (!tok3) return False; flags = strtoul(tok3, &endptr, 0); if (*endptr) return False; ui_seamless_unhide_desktop(); } xfree(l); return True; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static INLINE BOOL zgfx_GetBits(ZGFX_CONTEXT* _zgfx, UINT32 _nbits) { if (!_zgfx) return FALSE; while (_zgfx->cBitsCurrent < _nbits) { _zgfx->BitsCurrent <<= 8; if (_zgfx->pbInputCurrent < _zgfx->pbInputEnd) _zgfx->BitsCurrent += *(_zgfx->pbInputCurrent)++; _zgfx->cBitsCurrent += 8; } _zgfx->cBitsRemaining -= _nbits; _zgfx->cBitsCurrent -= _nbits; _zgfx->bits = _zgfx->BitsCurrent >> _zgfx->cBitsCurrent; _zgfx->BitsCurrent &= ((1 << _zgfx->cBitsCurrent) - 1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-125', 'CWE-787'], 'message': 'Fixed CVE-2018-8784 Thanks to Eyal Itkin from Check Point Software Technologies.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int zgfx_decompress(ZGFX_CONTEXT* zgfx, const BYTE* pSrcData, UINT32 SrcSize, BYTE** ppDstData, UINT32* pDstSize, UINT32 flags) { int status = -1; BYTE descriptor; wStream* stream = Stream_New((BYTE*)pSrcData, SrcSize); if (!stream) return -1; if (Stream_GetRemainingLength(stream) < 1) goto fail; Stream_Read_UINT8(stream, descriptor); /* descriptor (1 byte) */ if (descriptor == ZGFX_SEGMENTED_SINGLE) { if (!zgfx_decompress_segment(zgfx, stream, Stream_GetRemainingLength(stream))) goto fail; *ppDstData = NULL; if (zgfx->OutputCount > 0) *ppDstData = (BYTE*) malloc(zgfx->OutputCount); if (!*ppDstData) goto fail; *pDstSize = zgfx->OutputCount; CopyMemory(*ppDstData, zgfx->OutputBuffer, zgfx->OutputCount); } else if (descriptor == ZGFX_SEGMENTED_MULTIPART) { UINT32 segmentSize; UINT16 segmentNumber; UINT16 segmentCount; UINT32 uncompressedSize; BYTE* pConcatenated; if (Stream_GetRemainingLength(stream) < 6) goto fail; Stream_Read_UINT16(stream, segmentCount); /* segmentCount (2 bytes) */ Stream_Read_UINT32(stream, uncompressedSize); /* uncompressedSize (4 bytes) */ if (Stream_GetRemainingLength(stream) < segmentCount * sizeof(UINT32)) goto fail; pConcatenated = (BYTE*) malloc(uncompressedSize); if (!pConcatenated) goto fail; *ppDstData = pConcatenated; *pDstSize = uncompressedSize; for (segmentNumber = 0; segmentNumber < segmentCount; segmentNumber++) { if (Stream_GetRemainingLength(stream) < sizeof(UINT32)) goto fail; Stream_Read_UINT32(stream, segmentSize); /* segmentSize (4 bytes) */ if (!zgfx_decompress_segment(zgfx, stream, segmentSize)) goto fail; CopyMemory(pConcatenated, zgfx->OutputBuffer, zgfx->OutputCount); pConcatenated += zgfx->OutputCount; } } else { goto fail; } status = 1; fail: Stream_Free(stream, FALSE); return status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fixed CVE-2018-8785 Thanks to Eyal Itkin from Check Point Software Technologies.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s) { UINT32 i; BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE)); if (!bitmapUpdate) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %"PRIu32"", bitmapUpdate->number); if (bitmapUpdate->number > bitmapUpdate->count) { UINT16 count; BITMAP_DATA* newdata; count = bitmapUpdate->number * 2; newdata = (BITMAP_DATA*) realloc(bitmapUpdate->rectangles, sizeof(BITMAP_DATA) * count); if (!newdata) goto fail; bitmapUpdate->rectangles = newdata; ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count], sizeof(BITMAP_DATA) * (count - bitmapUpdate->count)); bitmapUpdate->count = count; } /* rectangles */ for (i = 0; i < bitmapUpdate->number; i++) { if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) goto fail; } return bitmapUpdate; fail: free_bitmap_update(update->context, bitmapUpdate); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fixed CVE-2018-8786 Thanks to Eyal Itkin from Check Point Software Technologies.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void nsc_decode(NSC_CONTEXT* context) { UINT16 x; UINT16 y; UINT16 rw = ROUND_UP_TO(context->width, 8); BYTE shift = context->ColorLossLevel - 1; /* colorloss recovery + YCoCg shift */ BYTE* bmpdata = context->BitmapData; for (y = 0; y < context->height; y++) { const BYTE* yplane; const BYTE* coplane; const BYTE* cgplane; const BYTE* aplane = context->priv->PlaneBuffers[3] + y * context->width; /* A */ if (context->ChromaSubsamplingLevel) { yplane = context->priv->PlaneBuffers[0] + y * rw; /* Y */ coplane = context->priv->PlaneBuffers[1] + (y >> 1) * (rw >> 1); /* Co, supersampled */ cgplane = context->priv->PlaneBuffers[2] + (y >> 1) * (rw >> 1); /* Cg, supersampled */ } else { yplane = context->priv->PlaneBuffers[0] + y * context->width; /* Y */ coplane = context->priv->PlaneBuffers[1] + y * context->width; /* Co */ cgplane = context->priv->PlaneBuffers[2] + y * context->width; /* Cg */ } for (x = 0; x < context->width; x++) { INT16 y_val = (INT16) * yplane; INT16 co_val = (INT16)(INT8)(*coplane << shift); INT16 cg_val = (INT16)(INT8)(*cgplane << shift); INT16 r_val = y_val + co_val - cg_val; INT16 g_val = y_val + cg_val; INT16 b_val = y_val - co_val - cg_val; *bmpdata++ = MINMAX(b_val, 0, 0xFF); *bmpdata++ = MINMAX(g_val, 0, 0xFF); *bmpdata++ = MINMAX(r_val, 0, 0xFF); *bmpdata++ = *aplane; yplane++; coplane += (context->ChromaSubsamplingLevel ? x % 2 : 1); cgplane += (context->ChromaSubsamplingLevel ? x % 2 : 1); aplane++; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-787'], 'message': 'Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: BOOL nsc_process_message(NSC_CONTEXT* context, UINT16 bpp, UINT32 width, UINT32 height, const BYTE* data, UINT32 length, BYTE* pDstData, UINT32 DstFormat, UINT32 nDstStride, UINT32 nXDst, UINT32 nYDst, UINT32 nWidth, UINT32 nHeight, UINT32 flip) { wStream* s; BOOL ret; s = Stream_New((BYTE*)data, length); if (!s) return FALSE; if (nDstStride == 0) nDstStride = nWidth * GetBytesPerPixel(DstFormat); switch (bpp) { case 32: context->format = PIXEL_FORMAT_BGRA32; break; case 24: context->format = PIXEL_FORMAT_BGR24; break; case 16: context->format = PIXEL_FORMAT_BGR16; break; case 8: context->format = PIXEL_FORMAT_RGB8; break; case 4: context->format = PIXEL_FORMAT_A4; break; default: Stream_Free(s, TRUE); return FALSE; } context->width = width; context->height = height; ret = nsc_context_initialize(context, s); Stream_Free(s, FALSE); if (!ret) return FALSE; /* RLE decode */ PROFILER_ENTER(context->priv->prof_nsc_rle_decompress_data) nsc_rle_decompress_data(context); PROFILER_EXIT(context->priv->prof_nsc_rle_decompress_data) /* Colorloss recover, Chroma supersample and AYCoCg to ARGB Conversion in one step */ PROFILER_ENTER(context->priv->prof_nsc_decode) context->decode(context); PROFILER_EXIT(context->priv->prof_nsc_decode) if (!freerdp_image_copy(pDstData, DstFormat, nDstStride, nXDst, nYDst, width, height, context->BitmapData, PIXEL_FORMAT_BGRA32, 0, 0, 0, NULL, flip)) return FALSE; return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-787'], 'message': 'Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride) { nsc_encode_argb_to_aycocg(context, bmpdata, rowstride); if (context->ChromaSubsamplingLevel) { nsc_encode_subsampling(context); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-787'], 'message': 'Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void nsc_encode_subsampling(NSC_CONTEXT* context) { UINT16 x; UINT16 y; BYTE* co_dst; BYTE* cg_dst; INT8* co_src0; INT8* co_src1; INT8* cg_src0; INT8* cg_src1; UINT32 tempWidth; UINT32 tempHeight; tempWidth = ROUND_UP_TO(context->width, 8); tempHeight = ROUND_UP_TO(context->height, 2); for (y = 0; y < tempHeight >> 1; y++) { co_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1); cg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1); co_src0 = (INT8*) context->priv->PlaneBuffers[1] + (y << 1) * tempWidth; co_src1 = co_src0 + tempWidth; cg_src0 = (INT8*) context->priv->PlaneBuffers[2] + (y << 1) * tempWidth; cg_src1 = cg_src0 + tempWidth; for (x = 0; x < tempWidth >> 1; x++) { *co_dst++ = (BYTE)(((INT16) * co_src0 + (INT16) * (co_src0 + 1) + (INT16) * co_src1 + (INT16) * (co_src1 + 1)) >> 2); *cg_dst++ = (BYTE)(((INT16) * cg_src0 + (INT16) * (cg_src0 + 1) + (INT16) * cg_src1 + (INT16) * (cg_src1 + 1)) >> 2); co_src0 += 2; co_src1 += 2; cg_src0 += 2; cg_src1 += 2; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-787'], 'message': 'Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data, UINT32 scanline) { UINT16 x; UINT16 y; UINT16 rw; BYTE ccl; const BYTE* src; BYTE* yplane = NULL; BYTE* coplane = NULL; BYTE* cgplane = NULL; BYTE* aplane = NULL; INT16 r_val; INT16 g_val; INT16 b_val; BYTE a_val; UINT32 tempWidth; tempWidth = ROUND_UP_TO(context->width, 8); rw = (context->ChromaSubsamplingLevel ? tempWidth : context->width); ccl = context->ColorLossLevel; for (y = 0; y < context->height; y++) { src = data + (context->height - 1 - y) * scanline; yplane = context->priv->PlaneBuffers[0] + y * rw; coplane = context->priv->PlaneBuffers[1] + y * rw; cgplane = context->priv->PlaneBuffers[2] + y * rw; aplane = context->priv->PlaneBuffers[3] + y * context->width; for (x = 0; x < context->width; x++) { switch (context->format) { case PIXEL_FORMAT_BGRX32: b_val = *src++; g_val = *src++; r_val = *src++; src++; a_val = 0xFF; break; case PIXEL_FORMAT_BGRA32: b_val = *src++; g_val = *src++; r_val = *src++; a_val = *src++; break; case PIXEL_FORMAT_RGBX32: r_val = *src++; g_val = *src++; b_val = *src++; src++; a_val = 0xFF; break; case PIXEL_FORMAT_RGBA32: r_val = *src++; g_val = *src++; b_val = *src++; a_val = *src++; break; case PIXEL_FORMAT_BGR24: b_val = *src++; g_val = *src++; r_val = *src++; a_val = 0xFF; break; case PIXEL_FORMAT_RGB24: r_val = *src++; g_val = *src++; b_val = *src++; a_val = 0xFF; break; case PIXEL_FORMAT_BGR16: b_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5)); g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3)); r_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07)); a_val = 0xFF; src += 2; break; case PIXEL_FORMAT_RGB16: r_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5)); g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3)); b_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07)); a_val = 0xFF; src += 2; break; case PIXEL_FORMAT_A4: { int shift; BYTE idx; shift = (7 - (x % 8)); idx = ((*src) >> shift) & 1; idx |= (((*(src + 1)) >> shift) & 1) << 1; idx |= (((*(src + 2)) >> shift) & 1) << 2; idx |= (((*(src + 3)) >> shift) & 1) << 3; idx *= 3; r_val = (INT16) context->palette[idx]; g_val = (INT16) context->palette[idx + 1]; b_val = (INT16) context->palette[idx + 2]; if (shift == 0) src += 4; } a_val = 0xFF; break; case PIXEL_FORMAT_RGB8: { int idx = (*src) * 3; r_val = (INT16) context->palette[idx]; g_val = (INT16) context->palette[idx + 1]; b_val = (INT16) context->palette[idx + 2]; src++; } a_val = 0xFF; break; default: r_val = g_val = b_val = a_val = 0; break; } *yplane++ = (BYTE)((r_val >> 2) + (g_val >> 1) + (b_val >> 2)); /* Perform color loss reduction here */ *coplane++ = (BYTE)((r_val - b_val) >> ccl); *cgplane++ = (BYTE)((-(r_val >> 1) + g_val - (b_val >> 1)) >> ccl); *aplane++ = a_val; } if (context->ChromaSubsamplingLevel && (x % 2) == 1) { *yplane = *(yplane - 1); *coplane = *(coplane - 1); *cgplane = *(cgplane - 1); } } if (context->ChromaSubsamplingLevel && (y % 2) == 1) { yplane = context->priv->PlaneBuffers[0] + y * rw; coplane = context->priv->PlaneBuffers[1] + y * rw; cgplane = context->priv->PlaneBuffers[2] + y * rw; CopyMemory(yplane, yplane - rw, rw); CopyMemory(coplane, coplane - rw, rw); CopyMemory(cgplane, cgplane - rw, rw); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-787'], 'message': 'Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ntlm_print_negotiate_flags(UINT32 flags) { int i; const char* str; WLog_INFO(TAG, "negotiateFlags \"0x%08"PRIX32"\"", flags); for (i = 31; i >= 0; i--) { if ((flags >> i) & 1) { str = NTLM_NEGOTIATE_STRINGS[(31 - i)]; WLog_INFO(TAG, "\t%s (%d),", str, (31 - i)); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-125'], 'message': 'Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (Stream_GetRemainingLength(s) < 8) return -1; Stream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */ Stream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */ Stream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */ return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-125'], 'message': 'Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType) { CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE)); header->MessageType = MessageType; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-125'], 'message': 'Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ntlm_write_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { Stream_SetPosition(s, fields->BufferOffset); Stream_Write(s, fields->Buffer, fields->Len); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-125'], 'message': 'Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) { if (Stream_GetRemainingLength(s) < 12) return -1; Stream_Read(s, header->Signature, 8); Stream_Read_UINT32(s, header->MessageType); if (strncmp((char*) header->Signature, NTLM_SIGNATURE, 8) != 0) return -1; return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-125'], 'message': 'Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Expression_Obj Parser::parse_value() { lex< css_comments >(false); if (lex< ampersand >()) { if (match< ampersand >()) { warning("In Sass, \"&&\" means two copies of the parent selector. You probably want to use \"and\" instead.", pstate); } return SASS_MEMORY_NEW(Parent_Selector, pstate); } if (lex< kwd_important >()) { return SASS_MEMORY_NEW(String_Constant, pstate, "!important"); } // parse `10%4px` into separated items and not a schema if (lex< sequence < percentage, lookahead < number > > >()) { return lexed_percentage(lexed); } if (lex< sequence < number, lookahead< sequence < op, number > > > >()) { return lexed_number(lexed); } // string may be interpolated if (lex< sequence < quoted_string, lookahead < exactly <'-'> > > >()) { return parse_string(); } if (const char* stop = peek< value_schema >()) { return parse_value_schema(stop); } // string may be interpolated if (lex< quoted_string >()) { return parse_string(); } if (lex< kwd_true >()) { return SASS_MEMORY_NEW(Boolean, pstate, true); } if (lex< kwd_false >()) { return SASS_MEMORY_NEW(Boolean, pstate, false); } if (lex< kwd_null >()) { return SASS_MEMORY_NEW(Null, pstate); } if (lex< identifier >()) { return color_or_string(lexed); } if (lex< percentage >()) { return lexed_percentage(lexed); } // match hex number first because 0x000 looks like a number followed by an identifier if (lex< sequence < alternatives< hex, hex0 >, negate < exactly<'-'> > > >()) { return lexed_hex_color(lexed); } if (lex< hexa >()) { std::string s = lexed.to_string(); deprecated( "The value \""+s+"\" is currently parsed as a string, but it will be parsed as a color in", "future versions of Sass. Use \"unquote('"+s+"')\" to continue parsing it as a string.", true, pstate ); return SASS_MEMORY_NEW(String_Quoted, pstate, lexed); } if (lex< sequence < exactly <'#'>, identifier > >()) { return SASS_MEMORY_NEW(String_Quoted, pstate, lexed); } // also handle the 10em- foo special case // alternatives < exactly < '.' >, .. > -- `1.5em-.75em` is split into a list, not a binary expression if (lex< sequence< dimension, optional< sequence< exactly<'-'>, lookahead< alternatives < space > > > > > >()) { return lexed_dimension(lexed); } if (lex< sequence< static_component, one_plus< strict_identifier > > >()) { return SASS_MEMORY_NEW(String_Constant, pstate, lexed); } if (lex< number >()) { return lexed_number(lexed); } if (lex< variable >()) { return SASS_MEMORY_NEW(Variable, pstate, Util::normalize_underscores(lexed)); } // Special case handling for `%` proceeding an interpolant. if (lex< sequence< exactly<'%'>, optional< percentage > > >()) { return SASS_MEMORY_NEW(String_Constant, pstate, lexed); } css_error("Invalid CSS", " after ", ": expected expression (e.g. 1px, bold), was "); // unreachable statement return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Remove legacy workaround for parsing modulo operator Fixes #2659'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: BGD_DECLARE(void *) gdImageWBMPPtr(gdImagePtr im, int *size, int fg) { void *rv; gdIOCtx *out = gdNewDynamicCtx(2048, NULL); if (out == NULL) return NULL; gdImageWBMPCtx(im, fg, out); rv = gdDPExtractData(out, size); out->gd_free(out); return rv; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Fix #492: Potential double-free in gdImage*Ptr() Whenever `gdImage*Ptr()` calls `gdImage*Ctx()` and the latter fails, we must not call `gdDPExtractData()`; otherwise a double-free would happen. Since `gdImage*Ctx()` are void functions, and we can't change that for BC reasons, we're introducing static helpers which are used internally. We're adding a regression test for `gdImageJpegPtr()`, but not for `gdImageGifPtr()` and `gdImageWbmpPtr()` since we don't know how to trigger failure of the respective `gdImage*Ctx()` calls. This potential security issue has been reported by Solmaz Salimi (aka. Rooney).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: BGD_DECLARE(void *) gdImageGifPtr(gdImagePtr im, int *size) { void *rv; gdIOCtx *out = gdNewDynamicCtx(2048, NULL); if (out == NULL) return NULL; gdImageGifCtx(im, out); rv = gdDPExtractData(out, size); out->gd_free(out); return rv; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Fix #492: Potential double-free in gdImage*Ptr() Whenever `gdImage*Ptr()` calls `gdImage*Ctx()` and the latter fails, we must not call `gdDPExtractData()`; otherwise a double-free would happen. Since `gdImage*Ctx()` are void functions, and we can't change that for BC reasons, we're introducing static helpers which are used internally. We're adding a regression test for `gdImageJpegPtr()`, but not for `gdImageGifPtr()` and `gdImageWbmpPtr()` since we don't know how to trigger failure of the respective `gdImage*Ctx()` calls. This potential security issue has been reported by Solmaz Salimi (aka. Rooney).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: BGD_DECLARE(void) gdImageJpegCtx(gdImagePtr im, gdIOCtx *outfile, int quality) { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; int i, j, jidx; /* volatile so we can gdFree it on return from longjmp */ volatile JSAMPROW row = 0; JSAMPROW rowptr[1]; jmpbuf_wrapper jmpbufw; JDIMENSION nlines; char comment[255]; #ifdef JPEG_DEBUG gd_error_ex(GD_DEBUG, "gd-jpeg: gd JPEG version %s\n", GD_JPEG_VERSION); gd_error_ex(GD_DEBUG, "gd-jpeg: JPEG library version %d, %d-bit sample values\n", JPEG_LIB_VERSION, BITS_IN_JSAMPLE); if (!im->trueColor) { for(i = 0; i < im->colorsTotal; i++) { if(!im->open[i]) { gd_error_ex(GD_DEBUG, "gd-jpeg: gd colormap index %d: (%d, %d, %d)\n", i, im->red[i], im->green[i], im->blue[i]); } } } #endif /* JPEG_DEBUG */ memset(&cinfo, 0, sizeof(cinfo)); memset(&jerr, 0, sizeof(jerr)); cinfo.err = jpeg_std_error(&jerr); cinfo.client_data = &jmpbufw; if(setjmp(jmpbufw.jmpbuf) != 0) { /* we're here courtesy of longjmp */ if(row) { gdFree(row); } return; } cinfo.err->emit_message = jpeg_emit_message; cinfo.err->error_exit = fatal_jpeg_error; jpeg_create_compress(&cinfo); cinfo.image_width = im->sx; cinfo.image_height = im->sy; cinfo.input_components = 3; /* # of color components per pixel */ cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ jpeg_set_defaults(&cinfo); cinfo.density_unit = 1; cinfo.X_density = im->res_x; cinfo.Y_density = im->res_y; if(quality >= 0) { jpeg_set_quality(&cinfo, quality, TRUE); if (quality >= 90) { cinfo.comp_info[0].h_samp_factor = 1; cinfo.comp_info[0].v_samp_factor = 1; } } /* If user requests interlace, translate that to progressive JPEG */ if(gdImageGetInterlaced(im)) { #ifdef JPEG_DEBUG gd_error_ex(GD_DEBUG, "gd-jpeg: interlace set, outputting progressive JPEG image\n"); #endif jpeg_simple_progression(&cinfo); } jpeg_gdIOCtx_dest(&cinfo, outfile); row = (JSAMPROW)gdCalloc(1, cinfo.image_width * cinfo.input_components * sizeof(JSAMPLE)); if(row == 0) { gd_error("gd-jpeg: error: unable to allocate JPEG row structure: gdCalloc returns NULL\n"); jpeg_destroy_compress(&cinfo); return; } rowptr[0] = row; jpeg_start_compress(&cinfo, TRUE); sprintf(comment, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d),", GD_JPEG_VERSION, JPEG_LIB_VERSION); if(quality >= 0) { sprintf (comment + strlen(comment), " quality = %d\n", quality); } else { strcat(comment + strlen(comment), " default quality\n"); } jpeg_write_marker(&cinfo, JPEG_COM, (unsigned char *) comment, (unsigned int)strlen(comment)); if(im->trueColor) { #if BITS_IN_JSAMPLE == 12 gd_error( "gd-jpeg: error: jpeg library was compiled for 12-bit\n" "precision. This is mostly useless, because JPEGs on the web are\n" "8-bit and such versions of the jpeg library won't read or write\n" "them. GD doesn't support these unusual images. Edit your\n" "jmorecfg.h file to specify the correct precision and completely\n" "'make clean' and 'make install' libjpeg again. Sorry.\n" ); goto error; #endif /* BITS_IN_JSAMPLE == 12 */ for(i = 0; i < im->sy; i++) { for(jidx = 0, j = 0; j < im->sx; j++) { int val = im->tpixels[i][j]; row[jidx++] = gdTrueColorGetRed(val); row[jidx++] = gdTrueColorGetGreen(val); row[jidx++] = gdTrueColorGetBlue(val); } nlines = jpeg_write_scanlines(&cinfo, rowptr, 1); if(nlines != 1) { gd_error("gd_jpeg: warning: jpeg_write_scanlines returns %u -- expected 1\n", nlines); } } } else { for(i = 0; i < im->sy; i++) { for(jidx = 0, j = 0; j < im->sx; j++) { int idx = im->pixels[i][j]; /* * NB: Although gd RGB values are ints, their max value is * 255 (see the documentation for gdImageColorAllocate()) * -- perfect for 8-bit JPEG encoding (which is the norm) */ #if BITS_IN_JSAMPLE == 8 row[jidx++] = im->red[idx]; row[jidx++] = im->green[idx]; row[jidx++] = im->blue[idx]; #elif BITS_IN_JSAMPLE == 12 row[jidx++] = im->red[idx] << 4; row[jidx++] = im->green[idx] << 4; row[jidx++] = im->blue[idx] << 4; #else #error IJG JPEG library BITS_IN_JSAMPLE value must be 8 or 12 #endif } nlines = jpeg_write_scanlines(&cinfo, rowptr, 1); if(nlines != 1) { gd_error("gd_jpeg: warning: jpeg_write_scanlines" " returns %u -- expected 1\n", nlines); } } } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); gdFree(row); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Fix #492: Potential double-free in gdImage*Ptr() Whenever `gdImage*Ptr()` calls `gdImage*Ctx()` and the latter fails, we must not call `gdDPExtractData()`; otherwise a double-free would happen. Since `gdImage*Ctx()` are void functions, and we can't change that for BC reasons, we're introducing static helpers which are used internally. We're adding a regression test for `gdImageJpegPtr()`, but not for `gdImageGifPtr()` and `gdImageWbmpPtr()` since we don't know how to trigger failure of the respective `gdImage*Ctx()` calls. This potential security issue has been reported by Solmaz Salimi (aka. Rooney).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void *gdImageJpegPtr (gdImagePtr im, int *size, int quality) { void *rv; gdIOCtx *out = gdNewDynamicCtx (2048, NULL); gdImageJpegCtx (im, out, quality); rv = gdDPExtractData (out, size); out->gd_free (out); return rv; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Sync with upstream Even though libgd/libgd#492 is not a relevant bug fix for PHP, since the binding doesn't use the `gdImage*Ptr()` functions at all, we're porting the fix to stay in sync here.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void gdImageJpegCtx (gdImagePtr im, gdIOCtx * outfile, int quality) { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; int i, j, jidx; /* volatile so we can gdFree it on return from longjmp */ volatile JSAMPROW row = 0; JSAMPROW rowptr[1]; jmpbuf_wrapper jmpbufw; JDIMENSION nlines; char comment[255]; memset (&cinfo, 0, sizeof (cinfo)); memset (&jerr, 0, sizeof (jerr)); cinfo.err = jpeg_std_error (&jerr); cinfo.client_data = &jmpbufw; if (setjmp (jmpbufw.jmpbuf) != 0) { /* we're here courtesy of longjmp */ if (row) { gdFree (row); } return; } cinfo.err->error_exit = fatal_jpeg_error; jpeg_create_compress (&cinfo); cinfo.image_width = im->sx; cinfo.image_height = im->sy; cinfo.input_components = 3; /* # of color components per pixel */ cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ jpeg_set_defaults (&cinfo); cinfo.density_unit = 1; cinfo.X_density = im->res_x; cinfo.Y_density = im->res_y; if (quality >= 0) { jpeg_set_quality (&cinfo, quality, TRUE); } /* If user requests interlace, translate that to progressive JPEG */ if (gdImageGetInterlaced (im)) { jpeg_simple_progression (&cinfo); } jpeg_gdIOCtx_dest (&cinfo, outfile); row = (JSAMPROW) safe_emalloc(cinfo.image_width * cinfo.input_components, sizeof(JSAMPLE), 0); memset(row, 0, cinfo.image_width * cinfo.input_components * sizeof(JSAMPLE)); rowptr[0] = row; jpeg_start_compress (&cinfo, TRUE); if (quality >= 0) { snprintf(comment, sizeof(comment)-1, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d), quality = %d\n", GD_JPEG_VERSION, JPEG_LIB_VERSION, quality); } else { snprintf(comment, sizeof(comment)-1, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d), default quality\n", GD_JPEG_VERSION, JPEG_LIB_VERSION); } jpeg_write_marker (&cinfo, JPEG_COM, (unsigned char *) comment, (unsigned int) strlen (comment)); if (im->trueColor) { #if BITS_IN_JSAMPLE == 12 gd_error("gd-jpeg: error: jpeg library was compiled for 12-bit precision. This is mostly useless, because JPEGs on the web are 8-bit and such versions of the jpeg library won't read or write them. GD doesn't support these unusual images. Edit your jmorecfg.h file to specify the correct precision and completely 'make clean' and 'make install' libjpeg again. Sorry"); goto error; #endif /* BITS_IN_JSAMPLE == 12 */ for (i = 0; i < im->sy; i++) { for (jidx = 0, j = 0; j < im->sx; j++) { int val = im->tpixels[i][j]; row[jidx++] = gdTrueColorGetRed (val); row[jidx++] = gdTrueColorGetGreen (val); row[jidx++] = gdTrueColorGetBlue (val); } nlines = jpeg_write_scanlines (&cinfo, rowptr, 1); if (nlines != 1) { gd_error_ex(GD_WARNING, "gd_jpeg: warning: jpeg_write_scanlines returns %u -- expected 1", nlines); } } } else { for (i = 0; i < im->sy; i++) { for (jidx = 0, j = 0; j < im->sx; j++) { int idx = im->pixels[i][j]; /* NB: Although gd RGB values are ints, their max value is * 255 (see the documentation for gdImageColorAllocate()) * -- perfect for 8-bit JPEG encoding (which is the norm) */ #if BITS_IN_JSAMPLE == 8 row[jidx++] = im->red[idx]; row[jidx++] = im->green[idx]; row[jidx++] = im->blue[idx]; #elif BITS_IN_JSAMPLE == 12 row[jidx++] = im->red[idx] << 4; row[jidx++] = im->green[idx] << 4; row[jidx++] = im->blue[idx] << 4; #else #error IJG JPEG library BITS_IN_JSAMPLE value must be 8 or 12 #endif } nlines = jpeg_write_scanlines (&cinfo, rowptr, 1); if (nlines != 1) { gd_error_ex(GD_WARNING, "gd_jpeg: warning: jpeg_write_scanlines returns %u -- expected 1", nlines); } } } jpeg_finish_compress (&cinfo); jpeg_destroy_compress (&cinfo); gdFree (row); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Sync with upstream Even though libgd/libgd#492 is not a relevant bug fix for PHP, since the binding doesn't use the `gdImage*Ptr()` functions at all, we're porting the fix to stay in sync here.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void gdImageWBMPCtx (gdImagePtr image, int fg, gdIOCtx * out) { int x, y, pos; Wbmp *wbmp; /* create the WBMP */ if ((wbmp = createwbmp (gdImageSX (image), gdImageSY (image), WBMP_WHITE)) == NULL) { gd_error("Could not create WBMP"); return; } /* fill up the WBMP structure */ pos = 0; for (y = 0; y < gdImageSY(image); y++) { for (x = 0; x < gdImageSX(image); x++) { if (gdImageGetPixel (image, x, y) == fg) { wbmp->bitmap[pos] = WBMP_BLACK; } pos++; } } /* write the WBMP to a gd file descriptor */ if (writewbmp (wbmp, &gd_putout, out)) { gd_error("Could not save WBMP"); } /* des submitted this bugfix: gdFree the memory. */ freewbmp(wbmp); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Sync with upstream Even though libgd/libgd#492 is not a relevant bug fix for PHP, since the binding doesn't use the `gdImage*Ptr()` functions at all, we're porting the fix to stay in sync here.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length) { char *buffer=NULL; int n=0; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, NULL); /* We later alloc length+1, which might wrap around on 32-bit systems if length equals 0XFFFFFFFF, i.e. SIZE_MAX for 32-bit systems. On 64-bit systems, a length of 0XFFFFFFFF will safely be allocated since this check will never trigger and malloc() can digest length+1 without problems as length is a uint32_t. */ if(length == SIZE_MAX) { rfbErr("rfbProcessFileTransferReadBuffer: too big file transfer length requested: %u", (unsigned int)length); rfbCloseClient(cl); return NULL; } if (length>0) { buffer=malloc((size_t)length+1); if (buffer!=NULL) { if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessFileTransferReadBuffer: read"); rfbCloseClient(cl); /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return NULL; } /* Null Terminate */ buffer[length]=0; } } return buffer; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-787'], 'message': 'Limit lenght to INT_MAX bytes in rfbProcessFileTransferReadBuffer() This ammends 15bb719c03cc70f14c36a843dcb16ed69b405707 fix for a heap out-of-bound write access in rfbProcessFileTransferReadBuffer() when reading a transfered file content in a server. The former fix did not work on platforms with a 32-bit int type (expected by rfbReadExact()). CVE-2018-15127 <https://github.com/LibVNC/libvncserver/issues/243> <https://github.com/LibVNC/libvncserver/issues/273>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: InitialiseRFBConnection(rfbClient* client) { rfbProtocolVersionMsg pv; int major,minor; uint32_t authScheme; uint32_t subAuthScheme; rfbClientInitMsg ci; /* if the connection is immediately closed, don't report anything, so that pmw's monitor can make test connections */ if (client->listenSpecified) errorMessageOnReadFailure = FALSE; if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; pv[sz_rfbProtocolVersionMsg]=0; errorMessageOnReadFailure = TRUE; pv[sz_rfbProtocolVersionMsg] = 0; if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2) { rfbClientLog("Not a valid VNC server (%s)\n",pv); return FALSE; } DefaultSupportedMessages(client); client->major = major; client->minor = minor; /* fall back to viewer supported version */ if ((major==rfbProtocolMajorVersion) && (minor>rfbProtocolMinorVersion)) client->minor = rfbProtocolMinorVersion; /* UltraVNC uses minor codes 4 and 6 for the server */ if (major==3 && (minor==4 || minor==6)) { rfbClientLog("UltraVNC server detected, enabling UltraVNC specific messages\n",pv); DefaultSupportedMessagesUltraVNC(client); } /* UltraVNC Single Click uses minor codes 14 and 16 for the server */ if (major==3 && (minor==14 || minor==16)) { minor = minor - 10; client->minor = minor; rfbClientLog("UltraVNC Single Click server detected, enabling UltraVNC specific messages\n",pv); DefaultSupportedMessagesUltraVNC(client); } /* TightVNC uses minor codes 5 for the server */ if (major==3 && minor==5) { rfbClientLog("TightVNC server detected, enabling TightVNC specific messages\n",pv); DefaultSupportedMessagesTightVNC(client); } /* we do not support > RFB3.8 */ if ((major==3 && minor>8) || major>3) { client->major=3; client->minor=8; } rfbClientLog("VNC server supports protocol version %d.%d (viewer %d.%d)\n", major, minor, rfbProtocolMajorVersion, rfbProtocolMinorVersion); sprintf(pv,rfbProtocolVersionFormat,client->major,client->minor); if (!WriteToRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; /* 3.7 and onwards sends a # of security types first */ if (client->major==3 && client->minor > 6) { if (!ReadSupportedSecurityType(client, &authScheme, FALSE)) return FALSE; } else { if (!ReadFromRFBServer(client, (char *)&authScheme, 4)) return FALSE; authScheme = rfbClientSwap32IfLE(authScheme); } rfbClientLog("Selected Security Scheme %d\n", authScheme); client->authScheme = authScheme; switch (authScheme) { case rfbConnFailed: ReadReason(client); return FALSE; case rfbNoAuth: rfbClientLog("No authentication needed\n"); /* 3.8 and upwards sends a Security Result for rfbNoAuth */ if ((client->major==3 && client->minor > 7) || client->major>3) if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVncAuth: if (!HandleVncAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ case rfbMSLogon: if (!HandleMSLogonAuth(client)) return FALSE; break; case rfbARD: #ifndef LIBVNCSERVER_WITH_CLIENT_GCRYPT rfbClientLog("GCrypt support was not compiled in\n"); return FALSE; #else if (!HandleARDAuth(client)) return FALSE; #endif break; case rfbTLS: if (!HandleAnonTLSAuth(client)) return FALSE; /* After the TLS session is established, sub auth types are expected. * Note that all following reading/writing are through the TLS session from here. */ if (!ReadSupportedSecurityType(client, &subAuthScheme, TRUE)) return FALSE; client->subAuthScheme = subAuthScheme; switch (subAuthScheme) { case rfbConnFailed: ReadReason(client); return FALSE; case rfbNoAuth: rfbClientLog("No sub authentication needed\n"); /* 3.8 and upwards sends a Security Result for rfbNoAuth */ if ((client->major==3 && client->minor > 7) || client->major>3) if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVncAuth: if (!HandleVncAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ default: rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n", (int)subAuthScheme); return FALSE; } break; case rfbVeNCrypt: if (!HandleVeNCryptAuth(client)) return FALSE; switch (client->subAuthScheme) { case rfbVeNCryptTLSNone: case rfbVeNCryptX509None: rfbClientLog("No sub authentication needed\n"); if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVeNCryptTLSVNC: case rfbVeNCryptX509VNC: if (!HandleVncAuth(client)) return FALSE; break; case rfbVeNCryptTLSPlain: case rfbVeNCryptX509Plain: if (!HandlePlainAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbVeNCryptX509SASL: case rfbVeNCryptTLSSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ default: rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n", client->subAuthScheme); return FALSE; } break; default: { rfbBool authHandled=FALSE; rfbClientProtocolExtension* e; for (e = rfbClientExtensions; e; e = e->next) { uint32_t const* secType; if (!e->handleAuthentication) continue; for (secType = e->securityTypes; secType && *secType; secType++) { if (authScheme==*secType) { if (!e->handleAuthentication(client, authScheme)) return FALSE; if (!rfbHandleAuthResult(client)) return FALSE; authHandled=TRUE; } } } if (authHandled) break; } rfbClientLog("Unknown authentication scheme from VNC server: %d\n", (int)authScheme); return FALSE; } ci.shared = (client->appData.shareDesktop ? 1 : 0); if (!WriteToRFBServer(client, (char *)&ci, sz_rfbClientInitMsg)) return FALSE; if (!ReadFromRFBServer(client, (char *)&client->si, sz_rfbServerInitMsg)) return FALSE; client->si.framebufferWidth = rfbClientSwap16IfLE(client->si.framebufferWidth); client->si.framebufferHeight = rfbClientSwap16IfLE(client->si.framebufferHeight); client->si.format.redMax = rfbClientSwap16IfLE(client->si.format.redMax); client->si.format.greenMax = rfbClientSwap16IfLE(client->si.format.greenMax); client->si.format.blueMax = rfbClientSwap16IfLE(client->si.format.blueMax); client->si.nameLength = rfbClientSwap32IfLE(client->si.nameLength); /* To guard against integer wrap-around, si.nameLength is cast to 64 bit */ client->desktopName = malloc((uint64_t)client->si.nameLength + 1); if (!client->desktopName) { rfbClientLog("Error allocating memory for desktop name, %lu bytes\n", (unsigned long)client->si.nameLength); return FALSE; } if (!ReadFromRFBServer(client, client->desktopName, client->si.nameLength)) return FALSE; client->desktopName[client->si.nameLength] = 0; rfbClientLog("Desktop name \"%s\"\n",client->desktopName); rfbClientLog("Connected to VNC server, using protocol version %d.%d\n", client->major, client->minor); rfbClientLog("VNC server default format:\n"); PrintPixelFormat(&client->si.format); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'LibVNCClient: fail on server-sent desktop name lengths longer than 1MB re #273'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rfbHandleAuthResult(rfbClient* client) { uint32_t authResult=0, reasonLen=0; char *reason=NULL; if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE; authResult = rfbClientSwap32IfLE(authResult); switch (authResult) { case rfbVncAuthOK: rfbClientLog("VNC authentication succeeded\n"); return TRUE; break; case rfbVncAuthFailed: if (client->major==3 && client->minor>7) { /* we have an error following */ if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return FALSE; reasonLen = rfbClientSwap32IfLE(reasonLen); reason = malloc((uint64_t)reasonLen+1); if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return FALSE; } reason[reasonLen]=0; rfbClientLog("VNC connection failed: %s\n",reason); free(reason); return FALSE; } rfbClientLog("VNC authentication failed\n"); return FALSE; case rfbVncAuthTooMany: rfbClientLog("VNC authentication failed - too many tries\n"); return FALSE; } rfbClientLog("Unknown VNC authentication result: %d\n", (int)authResult); return FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'LibVNCClient: ignore server-sent reason strings longer than 1MB Fixes #273'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ldb_wildcard_compare(struct ldb_context *ldb, const struct ldb_parse_tree *tree, const struct ldb_val value, bool *matched) { const struct ldb_schema_attribute *a; struct ldb_val val; struct ldb_val cnk; struct ldb_val *chunk; uint8_t *save_p = NULL; unsigned int c = 0; if (tree->operation != LDB_OP_SUBSTRING) { *matched = false; return LDB_ERR_INAPPROPRIATE_MATCHING; } a = ldb_schema_attribute_by_name(ldb, tree->u.substring.attr); if (!a) { return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX; } if (tree->u.substring.chunks == NULL) { *matched = false; return LDB_SUCCESS; } if (a->syntax->canonicalise_fn(ldb, ldb, &value, &val) != 0) { return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX; } save_p = val.data; cnk.data = NULL; if ( ! tree->u.substring.start_with_wildcard ) { chunk = tree->u.substring.chunks[c]; if (a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch; /* This deals with wildcard prefix searches on binary attributes (eg objectGUID) */ if (cnk.length > val.length) { goto mismatch; } /* * Empty strings are returned as length 0. Ensure * we can cope with this. */ if (cnk.length == 0) { goto mismatch; } if (memcmp((char *)val.data, (char *)cnk.data, cnk.length) != 0) goto mismatch; val.length -= cnk.length; val.data += cnk.length; c++; talloc_free(cnk.data); cnk.data = NULL; } while (tree->u.substring.chunks[c]) { uint8_t *p; chunk = tree->u.substring.chunks[c]; if(a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch; /* * Empty strings are returned as length 0. Ensure * we can cope with this. */ if (cnk.length == 0) { goto mismatch; } /* * Values might be binary blobs. Don't use string * search, but memory search instead. */ p = memmem((const void *)val.data,val.length, (const void *)cnk.data, cnk.length); if (p == NULL) goto mismatch; /* * At this point we know cnk.length <= val.length as * otherwise there could be no match */ if ( (! tree->u.substring.chunks[c + 1]) && (! tree->u.substring.end_with_wildcard) ) { uint8_t *g; uint8_t *end = val.data + val.length; do { /* greedy */ /* * haystack is a valid pointer in val * because the memmem() can only * succeed if the needle (cnk.length) * is <= haystacklen * * p will be a pointer at least * cnk.length from the end of haystack */ uint8_t *haystack = p + cnk.length; size_t haystacklen = end - (haystack); g = memmem(haystack, haystacklen, (const uint8_t *)cnk.data, cnk.length); if (g) { p = g; } } while(g); } val.length = val.length - (p - (uint8_t *)(val.data)) - cnk.length; val.data = (uint8_t *)(p + cnk.length); c++; talloc_free(cnk.data); cnk.data = NULL; } /* last chunk may not have reached end of string */ if ( (! tree->u.substring.end_with_wildcard) && (*(val.data) != 0) ) goto mismatch; talloc_free(save_p); *matched = true; return LDB_SUCCESS; mismatch: *matched = false; talloc_free(save_p); talloc_free(cnk.data); return LDB_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2019-3824 ldb: wildcard_match end of data check ldb_handler_copy and ldb_val_dup over allocate by one and add a trailing '\0' to the data, to make them safe to use the C string functions on. However testing for the trailing '\0' is not the correct way to test for the end of a value, the length should be checked instead. BUG: https://bugzilla.samba.org/show_bug.cgi?id=13773 Signed-off-by: Gary Lockyer <[email protected]> Reviewed-by: Andrew Bartlett <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct ldb_parse_tree *ldb_parse_simple(TALLOC_CTX *mem_ctx, const char **s) { char *attr, *value; struct ldb_parse_tree *ret; enum ldb_parse_op filtertype; ret = talloc(mem_ctx, struct ldb_parse_tree); if (!ret) { errno = ENOMEM; return NULL; } filtertype = ldb_parse_filtertype(ret, &attr, &value, s); if (!filtertype) { talloc_free(ret); return NULL; } switch (filtertype) { case LDB_OP_PRESENT: ret->operation = LDB_OP_PRESENT; ret->u.present.attr = attr; break; case LDB_OP_EQUALITY: if (strcmp(value, "*") == 0) { ret->operation = LDB_OP_PRESENT; ret->u.present.attr = attr; break; } if (ldb_parse_find_wildcard(value) != NULL) { ret->operation = LDB_OP_SUBSTRING; ret->u.substring.attr = attr; ret->u.substring.start_with_wildcard = 0; ret->u.substring.end_with_wildcard = 0; ret->u.substring.chunks = ldb_wildcard_decode(ret, value); if (ret->u.substring.chunks == NULL){ talloc_free(ret); return NULL; } if (value[0] == '*') ret->u.substring.start_with_wildcard = 1; if (value[strlen(value) - 1] == '*') ret->u.substring.end_with_wildcard = 1; talloc_free(value); break; } ret->operation = LDB_OP_EQUALITY; ret->u.equality.attr = attr; ret->u.equality.value = ldb_binary_decode(ret, value); if (ret->u.equality.value.data == NULL) { talloc_free(ret); return NULL; } talloc_free(value); break; case LDB_OP_GREATER: ret->operation = LDB_OP_GREATER; ret->u.comparison.attr = attr; ret->u.comparison.value = ldb_binary_decode(ret, value); if (ret->u.comparison.value.data == NULL) { talloc_free(ret); return NULL; } talloc_free(value); break; case LDB_OP_LESS: ret->operation = LDB_OP_LESS; ret->u.comparison.attr = attr; ret->u.comparison.value = ldb_binary_decode(ret, value); if (ret->u.comparison.value.data == NULL) { talloc_free(ret); return NULL; } talloc_free(value); break; case LDB_OP_APPROX: ret->operation = LDB_OP_APPROX; ret->u.comparison.attr = attr; ret->u.comparison.value = ldb_binary_decode(ret, value); if (ret->u.comparison.value.data == NULL) { talloc_free(ret); return NULL; } talloc_free(value); break; case LDB_OP_EXTENDED: ret = ldb_parse_extended(ret, attr, value); break; default: talloc_free(ret); return NULL; } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2019-3824 ldb: ldb_parse_tree use talloc_zero Initialise the created ldb_parse_tree with talloc_zero, this ensures that it is correctly initialised if inadvertently passed to a function expecting a different operation type. BUG: https://bugzilla.samba.org/show_bug.cgi?id=13773 Signed-off-by: Gary Lockyer <[email protected]> Reviewed-by: Andrew Bartlett <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ldb_wildcard_compare(struct ldb_context *ldb, const struct ldb_parse_tree *tree, const struct ldb_val value, bool *matched) { const struct ldb_schema_attribute *a; struct ldb_val val; struct ldb_val cnk; struct ldb_val *chunk; uint8_t *save_p = NULL; unsigned int c = 0; a = ldb_schema_attribute_by_name(ldb, tree->u.substring.attr); if (!a) { return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX; } if (tree->u.substring.chunks == NULL) { *matched = false; return LDB_SUCCESS; } if (a->syntax->canonicalise_fn(ldb, ldb, &value, &val) != 0) { return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX; } save_p = val.data; cnk.data = NULL; if ( ! tree->u.substring.start_with_wildcard ) { chunk = tree->u.substring.chunks[c]; if (a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch; /* This deals with wildcard prefix searches on binary attributes (eg objectGUID) */ if (cnk.length > val.length) { goto mismatch; } /* * Empty strings are returned as length 0. Ensure * we can cope with this. */ if (cnk.length == 0) { goto mismatch; } if (memcmp((char *)val.data, (char *)cnk.data, cnk.length) != 0) goto mismatch; val.length -= cnk.length; val.data += cnk.length; c++; talloc_free(cnk.data); cnk.data = NULL; } while (tree->u.substring.chunks[c]) { uint8_t *p; chunk = tree->u.substring.chunks[c]; if(a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch; /* * Empty strings are returned as length 0. Ensure * we can cope with this. */ if (cnk.length == 0) { goto mismatch; } /* * Values might be binary blobs. Don't use string * search, but memory search instead. */ p = memmem((const void *)val.data,val.length, (const void *)cnk.data, cnk.length); if (p == NULL) goto mismatch; if ( (! tree->u.substring.chunks[c + 1]) && (! tree->u.substring.end_with_wildcard) ) { uint8_t *g; uint8_t *end = val.data + val.length; do { /* greedy */ g = memmem(p + cnk.length, end - (p + cnk.length), (const uint8_t *)cnk.data, cnk.length); if (g) p = g; } while(g); } val.length = val.length - (p - (uint8_t *)(val.data)) - cnk.length; val.data = (uint8_t *)(p + cnk.length); c++; talloc_free(cnk.data); cnk.data = NULL; } /* last chunk may not have reached end of string */ if ( (! tree->u.substring.end_with_wildcard) && (*(val.data) != 0) ) goto mismatch; talloc_free(save_p); *matched = true; return LDB_SUCCESS; mismatch: *matched = false; talloc_free(save_p); talloc_free(cnk.data); return LDB_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2019-3824 ldb: Extra comments to clarify no pointer wrap in wildcard processing BUG: https://bugzilla.samba.org/show_bug.cgi?id=13773 Signed-off-by: Andrew Bartlett <[email protected]> Reviewed-by: Gary Lockyer <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: __xfs_get_blocks( struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create, bool direct, bool dax_fault) { struct xfs_inode *ip = XFS_I(inode); struct xfs_mount *mp = ip->i_mount; xfs_fileoff_t offset_fsb, end_fsb; int error = 0; int lockmode = 0; struct xfs_bmbt_irec imap; int nimaps = 1; xfs_off_t offset; ssize_t size; int new = 0; bool is_cow = false; bool need_alloc = false; BUG_ON(create && !direct); if (XFS_FORCED_SHUTDOWN(mp)) return -EIO; offset = (xfs_off_t)iblock << inode->i_blkbits; ASSERT(bh_result->b_size >= (1 << inode->i_blkbits)); size = bh_result->b_size; if (!create && offset >= i_size_read(inode)) return 0; /* * Direct I/O is usually done on preallocated files, so try getting * a block mapping without an exclusive lock first. */ lockmode = xfs_ilock_data_map_shared(ip); ASSERT(offset <= mp->m_super->s_maxbytes); if (offset + size > mp->m_super->s_maxbytes) size = mp->m_super->s_maxbytes - offset; end_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)offset + size); offset_fsb = XFS_B_TO_FSBT(mp, offset); if (create && direct && xfs_is_reflink_inode(ip)) is_cow = xfs_reflink_find_cow_mapping(ip, offset, &imap, &need_alloc); if (!is_cow) { error = xfs_bmapi_read(ip, offset_fsb, end_fsb - offset_fsb, &imap, &nimaps, XFS_BMAPI_ENTIRE); /* * Truncate an overwrite extent if there's a pending CoW * reservation before the end of this extent. This * forces us to come back to get_blocks to take care of * the CoW. */ if (create && direct && nimaps && imap.br_startblock != HOLESTARTBLOCK && imap.br_startblock != DELAYSTARTBLOCK && !ISUNWRITTEN(&imap)) xfs_reflink_trim_irec_to_next_cow(ip, offset_fsb, &imap); } ASSERT(!need_alloc); if (error) goto out_unlock; /* for DAX, we convert unwritten extents directly */ if (create && (!nimaps || (imap.br_startblock == HOLESTARTBLOCK || imap.br_startblock == DELAYSTARTBLOCK) || (IS_DAX(inode) && ISUNWRITTEN(&imap)))) { /* * xfs_iomap_write_direct() expects the shared lock. It * is unlocked on return. */ if (lockmode == XFS_ILOCK_EXCL) xfs_ilock_demote(ip, lockmode); error = xfs_iomap_write_direct(ip, offset, size, &imap, nimaps); if (error) return error; new = 1; trace_xfs_get_blocks_alloc(ip, offset, size, ISUNWRITTEN(&imap) ? XFS_IO_UNWRITTEN : XFS_IO_DELALLOC, &imap); } else if (nimaps) { trace_xfs_get_blocks_found(ip, offset, size, ISUNWRITTEN(&imap) ? XFS_IO_UNWRITTEN : XFS_IO_OVERWRITE, &imap); xfs_iunlock(ip, lockmode); } else { trace_xfs_get_blocks_notfound(ip, offset, size); goto out_unlock; } if (IS_DAX(inode) && create) { ASSERT(!ISUNWRITTEN(&imap)); /* zeroing is not needed at a higher layer */ new = 0; } /* trim mapping down to size requested */ xfs_map_trim_size(inode, iblock, bh_result, &imap, offset, size); /* * For unwritten extents do not report a disk address in the buffered * read case (treat as if we're reading into a hole). */ if (imap.br_startblock != HOLESTARTBLOCK && imap.br_startblock != DELAYSTARTBLOCK && (create || !ISUNWRITTEN(&imap))) { if (create && direct && !is_cow) { error = xfs_bounce_unaligned_dio_write(ip, offset_fsb, &imap); if (error) return error; } xfs_map_buffer(inode, bh_result, &imap, offset); if (ISUNWRITTEN(&imap)) set_buffer_unwritten(bh_result); /* direct IO needs special help */ if (create) { if (dax_fault) ASSERT(!ISUNWRITTEN(&imap)); else xfs_map_direct(inode, bh_result, &imap, offset, is_cow); } } /* * If this is a realtime file, data may be on a different device. * to that pointed to from the buffer_head b_bdev currently. */ bh_result->b_bdev = xfs_find_bdev_for_inode(inode); /* * If we previously allocated a block out beyond eof and we are now * coming back to use it then we will need to flag it as new even if it * has a disk address. * * With sub-block writes into unwritten extents we also need to mark * the buffer as new so that the unwritten parts of the buffer gets * correctly zeroed. */ if (create && ((!buffer_mapped(bh_result) && !buffer_uptodate(bh_result)) || (offset >= i_size_read(inode)) || (new || ISUNWRITTEN(&imap)))) set_buffer_new(bh_result); BUG_ON(direct && imap.br_startblock == DELAYSTARTBLOCK); return 0; out_unlock: xfs_iunlock(ip, lockmode); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'xfs: don't BUG() on mixed direct and mapped I/O We've had reports of generic/095 causing XFS to BUG() in __xfs_get_blocks() due to the existence of delalloc blocks on a direct I/O read. generic/095 issues a mix of various types of I/O, including direct and memory mapped I/O to a single file. This is clearly not supported behavior and is known to lead to such problems. E.g., the lack of exclusion between the direct I/O and write fault paths means that a write fault can allocate delalloc blocks in a region of a file that was previously a hole after the direct read has attempted to flush/inval the file range, but before it actually reads the block mapping. In turn, the direct read discovers a delalloc extent and cannot proceed. While the appropriate solution here is to not mix direct and memory mapped I/O to the same regions of the same file, the current BUG_ON() behavior is probably overkill as it can crash the entire system. Instead, localize the failure to the I/O in question by returning an error for a direct I/O that cannot be handled safely due to delalloc blocks. Be careful to allow the case of a direct write to post-eof delalloc blocks. This can occur due to speculative preallocation and is safe as post-eof blocks are not accompanied by dirty pages in pagecache (conversely, preallocation within eof must have been zeroed, and thus dirtied, before the inode size could have been increased beyond said blocks). Finally, provide an additional warning if a direct I/O write occurs while the file is memory mapped. This may not catch all problematic scenarios, but provides a hint that some known-to-be-problematic I/O methods are in use. Signed-off-by: Brian Foster <[email protected]> Reviewed-by: Dave Chinner <[email protected]> Signed-off-by: Dave Chinner <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int check_cond_jmp_op(struct bpf_verifier_env *env, struct bpf_insn *insn, int *insn_idx) { struct bpf_verifier_state *this_branch = env->cur_state; struct bpf_verifier_state *other_branch; struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; struct bpf_reg_state *dst_reg, *other_branch_regs; u8 opcode = BPF_OP(insn->code); int err; if (opcode > BPF_JSLE) { verbose(env, "invalid BPF_JMP opcode %x\n", opcode); return -EINVAL; } if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0) { verbose(env, "BPF_JMP uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->src_reg); return -EACCES; } } else { if (insn->src_reg != BPF_REG_0) { verbose(env, "BPF_JMP uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; dst_reg = &regs[insn->dst_reg]; if (BPF_SRC(insn->code) == BPF_K) { int pred = is_branch_taken(dst_reg, insn->imm, opcode); if (pred == 1) { /* only follow the goto, ignore fall-through */ *insn_idx += insn->off; return 0; } else if (pred == 0) { /* only follow fall-through branch, since * that's where the program will go */ return 0; } } other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx); if (!other_branch) return -EFAULT; other_branch_regs = other_branch->frame[other_branch->curframe]->regs; /* detect if we are comparing against a constant value so we can adjust * our min/max values for our dst register. * this is only legit if both are scalars (or pointers to the same * object, I suppose, but we don't support that right now), because * otherwise the different base pointers mean the offsets aren't * comparable. */ if (BPF_SRC(insn->code) == BPF_X) { if (dst_reg->type == SCALAR_VALUE && regs[insn->src_reg].type == SCALAR_VALUE) { if (tnum_is_const(regs[insn->src_reg].var_off)) reg_set_min_max(&other_branch_regs[insn->dst_reg], dst_reg, regs[insn->src_reg].var_off.value, opcode); else if (tnum_is_const(dst_reg->var_off)) reg_set_min_max_inv(&other_branch_regs[insn->src_reg], &regs[insn->src_reg], dst_reg->var_off.value, opcode); else if (opcode == BPF_JEQ || opcode == BPF_JNE) /* Comparing for equality, we can combine knowledge */ reg_combine_min_max(&other_branch_regs[insn->src_reg], &other_branch_regs[insn->dst_reg], &regs[insn->src_reg], &regs[insn->dst_reg], opcode); } } else if (dst_reg->type == SCALAR_VALUE) { reg_set_min_max(&other_branch_regs[insn->dst_reg], dst_reg, insn->imm, opcode); } /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */ if (BPF_SRC(insn->code) == BPF_K && insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && reg_type_may_be_null(dst_reg->type)) { /* Mark all identical registers in each branch as either * safe or unknown depending R == 0 or R != 0 conditional. */ mark_ptr_or_null_regs(this_branch, insn->dst_reg, opcode == BPF_JNE); mark_ptr_or_null_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ); } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg], this_branch, other_branch) && is_pointer_value(env, insn->dst_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->dst_reg); return -EACCES; } if (env->log.level) print_verifier_state(env, this_branch->frame[this_branch->curframe]); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'bpf: prevent out of bounds speculation on pointer arithmetic Jann reported that the original commit back in b2157399cc98 ("bpf: prevent out-of-bounds speculation") was not sufficient to stop CPU from speculating out of bounds memory access: While b2157399cc98 only focussed on masking array map access for unprivileged users for tail calls and data access such that the user provided index gets sanitized from BPF program and syscall side, there is still a more generic form affected from BPF programs that applies to most maps that hold user data in relation to dynamic map access when dealing with unknown scalars or "slow" known scalars as access offset, for example: - Load a map value pointer into R6 - Load an index into R7 - Do a slow computation (e.g. with a memory dependency) that loads a limit into R8 (e.g. load the limit from a map for high latency, then mask it to make the verifier happy) - Exit if R7 >= R8 (mispredicted branch) - Load R0 = R6[R7] - Load R0 = R6[R0] For unknown scalars there are two options in the BPF verifier where we could derive knowledge from in order to guarantee safe access to the memory: i) While </>/<=/>= variants won't allow to derive any lower or upper bounds from the unknown scalar where it would be safe to add it to the map value pointer, it is possible through ==/!= test however. ii) another option is to transform the unknown scalar into a known scalar, for example, through ALU ops combination such as R &= <imm> followed by R |= <imm> or any similar combination where the original information from the unknown scalar would be destroyed entirely leaving R with a constant. The initial slow load still precedes the latter ALU ops on that register, so the CPU executes speculatively from that point. Once we have the known scalar, any compare operation would work then. A third option only involving registers with known scalars could be crafted as described in [0] where a CPU port (e.g. Slow Int unit) would be filled with many dependent computations such that the subsequent condition depending on its outcome has to wait for evaluation on its execution port and thereby executing speculatively if the speculated code can be scheduled on a different execution port, or any other form of mistraining as described in [1], for example. Given this is not limited to only unknown scalars, not only map but also stack access is affected since both is accessible for unprivileged users and could potentially be used for out of bounds access under speculation. In order to prevent any of these cases, the verifier is now sanitizing pointer arithmetic on the offset such that any out of bounds speculation would be masked in a way where the pointer arithmetic result in the destination register will stay unchanged, meaning offset masked into zero similar as in array_index_nospec() case. With regards to implementation, there are three options that were considered: i) new insn for sanitation, ii) push/pop insn and sanitation as inlined BPF, iii) reuse of ax register and sanitation as inlined BPF. Option i) has the downside that we end up using from reserved bits in the opcode space, but also that we would require each JIT to emit masking as native arch opcodes meaning mitigation would have slow adoption till everyone implements it eventually which is counter-productive. Option ii) and iii) have both in common that a temporary register is needed in order to implement the sanitation as inlined BPF since we are not allowed to modify the source register. While a push / pop insn in ii) would be useful to have in any case, it requires once again that every JIT needs to implement it first. While possible, amount of changes needed would also be unsuitable for a -stable patch. Therefore, the path which has fewer changes, less BPF instructions for the mitigation and does not require anything to be changed in the JITs is option iii) which this work is pursuing. The ax register is already mapped to a register in all JITs (modulo arm32 where it's mapped to stack as various other BPF registers there) and used in constant blinding for JITs-only so far. It can be reused for verifier rewrites under certain constraints. The interpreter's tmp "register" has therefore been remapped into extending the register set with hidden ax register and reusing that for a number of instructions that needed the prior temporary variable internally (e.g. div, mod). This allows for zero increase in stack space usage in the interpreter, and enables (restricted) generic use in rewrites otherwise as long as such a patchlet does not make use of these instructions. The sanitation mask is dynamic and relative to the offset the map value or stack pointer currently holds. There are various cases that need to be taken under consideration for the masking, e.g. such operation could look as follows: ptr += val or val += ptr or ptr -= val. Thus, the value to be sanitized could reside either in source or in destination register, and the limit is different depending on whether the ALU op is addition or subtraction and depending on the current known and bounded offset. The limit is derived as follows: limit := max_value_size - (smin_value + off). For subtraction: limit := umax_value + off. This holds because we do not allow any pointer arithmetic that would temporarily go out of bounds or would have an unknown value with mixed signed bounds where it is unclear at verification time whether the actual runtime value would be either negative or positive. For example, we have a derived map pointer value with constant offset and bounded one, so limit based on smin_value works because the verifier requires that statically analyzed arithmetic on the pointer must be in bounds, and thus it checks if resulting smin_value + off and umax_value + off is still within map value bounds at time of arithmetic in addition to time of access. Similarly, for the case of stack access we derive the limit as follows: MAX_BPF_STACK + off for subtraction and -off for the case of addition where off := ptr_reg->off + ptr_reg->var_off.value. Subtraction is a special case for the masking which can be in form of ptr += -val, ptr -= -val, or ptr -= val. In the first two cases where we know that the value is negative, we need to temporarily negate the value in order to do the sanitation on a positive value where we later swap the ALU op, and restore original source register if the value was in source. The sanitation of pointer arithmetic alone is still not fully sufficient as is, since a scenario like the following could happen ... PTR += 0x1000 (e.g. K-based imm) PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON PTR += 0x1000 PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON [...] ... which under speculation could end up as ... PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] [...] ... and therefore still access out of bounds. To prevent such case, the verifier is also analyzing safety for potential out of bounds access under speculative execution. Meaning, it is also simulating pointer access under truncation. We therefore "branch off" and push the current verification state after the ALU operation with known 0 to the verification stack for later analysis. Given the current path analysis succeeded it is likely that the one under speculation can be pruned. In any case, it is also subject to existing complexity limits and therefore anything beyond this point will be rejected. In terms of pruning, it needs to be ensured that the verification state from speculative execution simulation must never prune a non-speculative execution path, therefore, we mark verifier state accordingly at the time of push_stack(). If verifier detects out of bounds access under speculative execution from one of the possible paths that includes a truncation, it will reject such program. Given we mask every reg-based pointer arithmetic for unprivileged programs, we've been looking into how it could affect real-world programs in terms of size increase. As the majority of programs are targeted for privileged-only use case, we've unconditionally enabled masking (with its alu restrictions on top of it) for privileged programs for the sake of testing in order to check i) whether they get rejected in its current form, and ii) by how much the number of instructions and size will increase. We've tested this by using Katran, Cilium and test_l4lb from the kernel selftests. For Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o and an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb we've used test_l4lb.o as well as test_l4lb_noinline.o. We found that none of the programs got rejected by the verifier with this change, and that impact is rather minimal to none. balancer_kern.o had 13,904 bytes (1,738 insns) xlated and 7,797 bytes JITed before and after the change. Most complex program in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated and 18,538 bytes JITed before and after and none of the other tail call programs in bpf_lxc.o had any changes either. For the older bpf_lxc_opt_-DUNKNOWN.o object we found a small increase from 20,616 bytes (2,576 insns) and 12,536 bytes JITed before to 20,664 bytes (2,582 insns) and 12,558 bytes JITed after the change. Other programs from that object file had similar small increase. Both test_l4lb.o had no change and remained at 6,544 bytes (817 insns) xlated and 3,401 bytes JITed and for test_l4lb_noinline.o constant at 5,080 bytes (634 insns) xlated and 3,313 bytes JITed. This can be explained in that LLVM typically optimizes stack based pointer arithmetic by using K-based operations and that use of dynamic map access is not overly frequent. However, in future we may decide to optimize the algorithm further under known guarantees from branch and value speculation. Latter seems also unclear in terms of prediction heuristics that today's CPUs apply as well as whether there could be collisions in e.g. the predictor's Value History/Pattern Table for triggering out of bounds access, thus masking is performed unconditionally at this point but could be subject to relaxation later on. We were generally also brainstorming various other approaches for mitigation, but the blocker was always lack of available registers at runtime and/or overhead for runtime tracking of limits belonging to a specific pointer. Thus, we found this to be minimally intrusive under given constraints. With that in place, a simple example with sanitized access on unprivileged load at post-verification time looks as follows: # bpftool prog dump xlated id 282 [...] 28: (79) r1 = *(u64 *)(r7 +0) 29: (79) r2 = *(u64 *)(r7 +8) 30: (57) r1 &= 15 31: (79) r3 = *(u64 *)(r0 +4608) 32: (57) r3 &= 1 33: (47) r3 |= 1 34: (2d) if r2 > r3 goto pc+19 35: (b4) (u32) r11 = (u32) 20479 | 36: (1f) r11 -= r2 | Dynamic sanitation for pointer 37: (4f) r11 |= r2 | arithmetic with registers 38: (87) r11 = -r11 | containing bounded or known 39: (c7) r11 s>>= 63 | scalars in order to prevent 40: (5f) r11 &= r2 | out of bounds speculation. 41: (0f) r4 += r11 | 42: (71) r4 = *(u8 *)(r4 +0) 43: (6f) r4 <<= r1 [...] For the case where the scalar sits in the destination register as opposed to the source register, the following code is emitted for the above example: [...] 16: (b4) (u32) r11 = (u32) 20479 17: (1f) r11 -= r2 18: (4f) r11 |= r2 19: (87) r11 = -r11 20: (c7) r11 s>>= 63 21: (5f) r2 &= r11 22: (0f) r2 += r0 23: (61) r0 = *(u32 *)(r2 +0) [...] JIT blinding example with non-conflicting use of r10: [...] d5: je 0x0000000000000106 _ d7: mov 0x0(%rax),%edi | da: mov $0xf153246,%r10d | Index load from map value and e0: xor $0xf153259,%r10 | (const blinded) mask with 0x1f. e7: and %r10,%rdi |_ ea: mov $0x2f,%r10d | f0: sub %rdi,%r10 | Sanitized addition. Both use r10 f3: or %rdi,%r10 | but do not interfere with each f6: neg %r10 | other. (Neither do these instructions f9: sar $0x3f,%r10 | interfere with the use of ax as temp fd: and %r10,%rdi | in interpreter.) 100: add %rax,%rdi |_ 103: mov 0x0(%rdi),%eax [...] Tested that it fixes Jann's reproducer, and also checked that test_verifier and test_progs suite with interpreter, JIT and JIT with hardening enabled on x86-64 and arm64 runs successfully. [0] Speculose: Analyzing the Security Implications of Speculative Execution in CPUs, Giorgi Maisuradze and Christian Rossow, https://arxiv.org/pdf/1801.04084.pdf [1] A Systematic Evaluation of Transient Execution Attacks and Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz, Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens, Dmitry Evtyushkin, Daniel Gruss, https://arxiv.org/pdf/1811.05441.pdf Fixes: b2157399cc98 ("bpf: prevent out-of-bounds speculation") Reported-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Alexei Starovoitov <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool states_equal(struct bpf_verifier_env *env, struct bpf_verifier_state *old, struct bpf_verifier_state *cur) { int i; if (old->curframe != cur->curframe) return false; /* for states to be equal callsites have to be the same * and all frame states need to be equivalent */ for (i = 0; i <= old->curframe; i++) { if (old->frame[i]->callsite != cur->frame[i]->callsite) return false; if (!func_states_equal(old->frame[i], cur->frame[i])) return false; } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'bpf: prevent out of bounds speculation on pointer arithmetic Jann reported that the original commit back in b2157399cc98 ("bpf: prevent out-of-bounds speculation") was not sufficient to stop CPU from speculating out of bounds memory access: While b2157399cc98 only focussed on masking array map access for unprivileged users for tail calls and data access such that the user provided index gets sanitized from BPF program and syscall side, there is still a more generic form affected from BPF programs that applies to most maps that hold user data in relation to dynamic map access when dealing with unknown scalars or "slow" known scalars as access offset, for example: - Load a map value pointer into R6 - Load an index into R7 - Do a slow computation (e.g. with a memory dependency) that loads a limit into R8 (e.g. load the limit from a map for high latency, then mask it to make the verifier happy) - Exit if R7 >= R8 (mispredicted branch) - Load R0 = R6[R7] - Load R0 = R6[R0] For unknown scalars there are two options in the BPF verifier where we could derive knowledge from in order to guarantee safe access to the memory: i) While </>/<=/>= variants won't allow to derive any lower or upper bounds from the unknown scalar where it would be safe to add it to the map value pointer, it is possible through ==/!= test however. ii) another option is to transform the unknown scalar into a known scalar, for example, through ALU ops combination such as R &= <imm> followed by R |= <imm> or any similar combination where the original information from the unknown scalar would be destroyed entirely leaving R with a constant. The initial slow load still precedes the latter ALU ops on that register, so the CPU executes speculatively from that point. Once we have the known scalar, any compare operation would work then. A third option only involving registers with known scalars could be crafted as described in [0] where a CPU port (e.g. Slow Int unit) would be filled with many dependent computations such that the subsequent condition depending on its outcome has to wait for evaluation on its execution port and thereby executing speculatively if the speculated code can be scheduled on a different execution port, or any other form of mistraining as described in [1], for example. Given this is not limited to only unknown scalars, not only map but also stack access is affected since both is accessible for unprivileged users and could potentially be used for out of bounds access under speculation. In order to prevent any of these cases, the verifier is now sanitizing pointer arithmetic on the offset such that any out of bounds speculation would be masked in a way where the pointer arithmetic result in the destination register will stay unchanged, meaning offset masked into zero similar as in array_index_nospec() case. With regards to implementation, there are three options that were considered: i) new insn for sanitation, ii) push/pop insn and sanitation as inlined BPF, iii) reuse of ax register and sanitation as inlined BPF. Option i) has the downside that we end up using from reserved bits in the opcode space, but also that we would require each JIT to emit masking as native arch opcodes meaning mitigation would have slow adoption till everyone implements it eventually which is counter-productive. Option ii) and iii) have both in common that a temporary register is needed in order to implement the sanitation as inlined BPF since we are not allowed to modify the source register. While a push / pop insn in ii) would be useful to have in any case, it requires once again that every JIT needs to implement it first. While possible, amount of changes needed would also be unsuitable for a -stable patch. Therefore, the path which has fewer changes, less BPF instructions for the mitigation and does not require anything to be changed in the JITs is option iii) which this work is pursuing. The ax register is already mapped to a register in all JITs (modulo arm32 where it's mapped to stack as various other BPF registers there) and used in constant blinding for JITs-only so far. It can be reused for verifier rewrites under certain constraints. The interpreter's tmp "register" has therefore been remapped into extending the register set with hidden ax register and reusing that for a number of instructions that needed the prior temporary variable internally (e.g. div, mod). This allows for zero increase in stack space usage in the interpreter, and enables (restricted) generic use in rewrites otherwise as long as such a patchlet does not make use of these instructions. The sanitation mask is dynamic and relative to the offset the map value or stack pointer currently holds. There are various cases that need to be taken under consideration for the masking, e.g. such operation could look as follows: ptr += val or val += ptr or ptr -= val. Thus, the value to be sanitized could reside either in source or in destination register, and the limit is different depending on whether the ALU op is addition or subtraction and depending on the current known and bounded offset. The limit is derived as follows: limit := max_value_size - (smin_value + off). For subtraction: limit := umax_value + off. This holds because we do not allow any pointer arithmetic that would temporarily go out of bounds or would have an unknown value with mixed signed bounds where it is unclear at verification time whether the actual runtime value would be either negative or positive. For example, we have a derived map pointer value with constant offset and bounded one, so limit based on smin_value works because the verifier requires that statically analyzed arithmetic on the pointer must be in bounds, and thus it checks if resulting smin_value + off and umax_value + off is still within map value bounds at time of arithmetic in addition to time of access. Similarly, for the case of stack access we derive the limit as follows: MAX_BPF_STACK + off for subtraction and -off for the case of addition where off := ptr_reg->off + ptr_reg->var_off.value. Subtraction is a special case for the masking which can be in form of ptr += -val, ptr -= -val, or ptr -= val. In the first two cases where we know that the value is negative, we need to temporarily negate the value in order to do the sanitation on a positive value where we later swap the ALU op, and restore original source register if the value was in source. The sanitation of pointer arithmetic alone is still not fully sufficient as is, since a scenario like the following could happen ... PTR += 0x1000 (e.g. K-based imm) PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON PTR += 0x1000 PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON [...] ... which under speculation could end up as ... PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] [...] ... and therefore still access out of bounds. To prevent such case, the verifier is also analyzing safety for potential out of bounds access under speculative execution. Meaning, it is also simulating pointer access under truncation. We therefore "branch off" and push the current verification state after the ALU operation with known 0 to the verification stack for later analysis. Given the current path analysis succeeded it is likely that the one under speculation can be pruned. In any case, it is also subject to existing complexity limits and therefore anything beyond this point will be rejected. In terms of pruning, it needs to be ensured that the verification state from speculative execution simulation must never prune a non-speculative execution path, therefore, we mark verifier state accordingly at the time of push_stack(). If verifier detects out of bounds access under speculative execution from one of the possible paths that includes a truncation, it will reject such program. Given we mask every reg-based pointer arithmetic for unprivileged programs, we've been looking into how it could affect real-world programs in terms of size increase. As the majority of programs are targeted for privileged-only use case, we've unconditionally enabled masking (with its alu restrictions on top of it) for privileged programs for the sake of testing in order to check i) whether they get rejected in its current form, and ii) by how much the number of instructions and size will increase. We've tested this by using Katran, Cilium and test_l4lb from the kernel selftests. For Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o and an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb we've used test_l4lb.o as well as test_l4lb_noinline.o. We found that none of the programs got rejected by the verifier with this change, and that impact is rather minimal to none. balancer_kern.o had 13,904 bytes (1,738 insns) xlated and 7,797 bytes JITed before and after the change. Most complex program in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated and 18,538 bytes JITed before and after and none of the other tail call programs in bpf_lxc.o had any changes either. For the older bpf_lxc_opt_-DUNKNOWN.o object we found a small increase from 20,616 bytes (2,576 insns) and 12,536 bytes JITed before to 20,664 bytes (2,582 insns) and 12,558 bytes JITed after the change. Other programs from that object file had similar small increase. Both test_l4lb.o had no change and remained at 6,544 bytes (817 insns) xlated and 3,401 bytes JITed and for test_l4lb_noinline.o constant at 5,080 bytes (634 insns) xlated and 3,313 bytes JITed. This can be explained in that LLVM typically optimizes stack based pointer arithmetic by using K-based operations and that use of dynamic map access is not overly frequent. However, in future we may decide to optimize the algorithm further under known guarantees from branch and value speculation. Latter seems also unclear in terms of prediction heuristics that today's CPUs apply as well as whether there could be collisions in e.g. the predictor's Value History/Pattern Table for triggering out of bounds access, thus masking is performed unconditionally at this point but could be subject to relaxation later on. We were generally also brainstorming various other approaches for mitigation, but the blocker was always lack of available registers at runtime and/or overhead for runtime tracking of limits belonging to a specific pointer. Thus, we found this to be minimally intrusive under given constraints. With that in place, a simple example with sanitized access on unprivileged load at post-verification time looks as follows: # bpftool prog dump xlated id 282 [...] 28: (79) r1 = *(u64 *)(r7 +0) 29: (79) r2 = *(u64 *)(r7 +8) 30: (57) r1 &= 15 31: (79) r3 = *(u64 *)(r0 +4608) 32: (57) r3 &= 1 33: (47) r3 |= 1 34: (2d) if r2 > r3 goto pc+19 35: (b4) (u32) r11 = (u32) 20479 | 36: (1f) r11 -= r2 | Dynamic sanitation for pointer 37: (4f) r11 |= r2 | arithmetic with registers 38: (87) r11 = -r11 | containing bounded or known 39: (c7) r11 s>>= 63 | scalars in order to prevent 40: (5f) r11 &= r2 | out of bounds speculation. 41: (0f) r4 += r11 | 42: (71) r4 = *(u8 *)(r4 +0) 43: (6f) r4 <<= r1 [...] For the case where the scalar sits in the destination register as opposed to the source register, the following code is emitted for the above example: [...] 16: (b4) (u32) r11 = (u32) 20479 17: (1f) r11 -= r2 18: (4f) r11 |= r2 19: (87) r11 = -r11 20: (c7) r11 s>>= 63 21: (5f) r2 &= r11 22: (0f) r2 += r0 23: (61) r0 = *(u32 *)(r2 +0) [...] JIT blinding example with non-conflicting use of r10: [...] d5: je 0x0000000000000106 _ d7: mov 0x0(%rax),%edi | da: mov $0xf153246,%r10d | Index load from map value and e0: xor $0xf153259,%r10 | (const blinded) mask with 0x1f. e7: and %r10,%rdi |_ ea: mov $0x2f,%r10d | f0: sub %rdi,%r10 | Sanitized addition. Both use r10 f3: or %rdi,%r10 | but do not interfere with each f6: neg %r10 | other. (Neither do these instructions f9: sar $0x3f,%r10 | interfere with the use of ax as temp fd: and %r10,%rdi | in interpreter.) 100: add %rax,%rdi |_ 103: mov 0x0(%rdi),%eax [...] Tested that it fixes Jann's reproducer, and also checked that test_verifier and test_progs suite with interpreter, JIT and JIT with hardening enabled on x86-64 and arm64 runs successfully. [0] Speculose: Analyzing the Security Implications of Speculative Execution in CPUs, Giorgi Maisuradze and Christian Rossow, https://arxiv.org/pdf/1801.04084.pdf [1] A Systematic Evaluation of Transient Execution Attacks and Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz, Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens, Dmitry Evtyushkin, Daniel Gruss, https://arxiv.org/pdf/1811.05441.pdf Fixes: b2157399cc98 ("bpf: prevent out-of-bounds speculation") Reported-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Alexei Starovoitov <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, const struct bpf_reg_state *ptr_reg, const struct bpf_reg_state *off_reg) { struct bpf_verifier_state *vstate = env->cur_state; struct bpf_func_state *state = vstate->frame[vstate->curframe]; struct bpf_reg_state *regs = state->regs, *dst_reg; bool known = tnum_is_const(off_reg->var_off); s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; u32 dst = insn->dst_reg, src = insn->src_reg; u8 opcode = BPF_OP(insn->code); dst_reg = &regs[dst]; if ((known && (smin_val != smax_val || umin_val != umax_val)) || smin_val > smax_val || umin_val > umax_val) { /* Taint dst register if offset had invalid bounds derived from * e.g. dead branches. */ __mark_reg_unknown(dst_reg); return 0; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops on pointers produce (meaningless) scalars */ verbose(env, "R%d 32-bit pointer arithmetic prohibited\n", dst); return -EACCES; } switch (ptr_reg->type) { case PTR_TO_MAP_VALUE_OR_NULL: verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", dst, reg_type_str[ptr_reg->type]); return -EACCES; case CONST_PTR_TO_MAP: case PTR_TO_PACKET_END: case PTR_TO_SOCKET: case PTR_TO_SOCKET_OR_NULL: verbose(env, "R%d pointer arithmetic on %s prohibited\n", dst, reg_type_str[ptr_reg->type]); return -EACCES; case PTR_TO_MAP_VALUE: if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) { verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n", off_reg == dst_reg ? dst : src); return -EACCES; } /* fall-through */ default: break; } /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. * The id may be overwritten later if we create a new variable offset. */ dst_reg->type = ptr_reg->type; dst_reg->id = ptr_reg->id; if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) return -EINVAL; switch (opcode) { case BPF_ADD: /* We can take a fixed offset as long as it doesn't overflow * the s32 'off' field */ if (known && (ptr_reg->off + smin_val == (s64)(s32)(ptr_reg->off + smin_val))) { /* pointer += K. Accumulate it into fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->off = ptr_reg->off + smin_val; dst_reg->raw = ptr_reg->raw; break; } /* A new variable offset is created. Note that off_reg->off * == 0, since it's a scalar. * dst_reg gets the pointer type and since some positive * integer value was added to the pointer, give it a new 'id' * if it's a PTR_TO_PACKET. * this creates a new 'base' pointer, off_reg (variable) gets * added into the variable offset, and we copy the fixed offset * from ptr_reg. */ if (signed_add_overflows(smin_ptr, smin_val) || signed_add_overflows(smax_ptr, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr + smin_val; dst_reg->smax_value = smax_ptr + smax_val; } if (umin_ptr + umin_val < umin_ptr || umax_ptr + umax_val < umax_ptr) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value = umin_ptr + umin_val; dst_reg->umax_value = umax_ptr + umax_val; } dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; dst_reg->raw = ptr_reg->raw; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ dst_reg->raw = 0; } break; case BPF_SUB: if (dst_reg == off_reg) { /* scalar -= pointer. Creates an unknown scalar */ verbose(env, "R%d tried to subtract pointer from scalar\n", dst); return -EACCES; } /* We don't allow subtraction from FP, because (according to * test_verifier.c test "invalid fp arithmetic", JITs might not * be able to deal with it. */ if (ptr_reg->type == PTR_TO_STACK) { verbose(env, "R%d subtraction from stack pointer prohibited\n", dst); return -EACCES; } if (known && (ptr_reg->off - smin_val == (s64)(s32)(ptr_reg->off - smin_val))) { /* pointer -= K. Subtract it from fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->id = ptr_reg->id; dst_reg->off = ptr_reg->off - smin_val; dst_reg->raw = ptr_reg->raw; break; } /* A new variable offset is created. If the subtrahend is known * nonnegative, then any reg->range we had before is still good. */ if (signed_sub_overflows(smin_ptr, smax_val) || signed_sub_overflows(smax_ptr, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr - smax_val; dst_reg->smax_value = smax_ptr - smin_val; } if (umin_ptr < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value = umin_ptr - umax_val; dst_reg->umax_value = umax_ptr - umin_val; } dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; dst_reg->raw = ptr_reg->raw; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ if (smin_val < 0) dst_reg->raw = 0; } break; case BPF_AND: case BPF_OR: case BPF_XOR: /* bitwise ops on pointers are troublesome, prohibit. */ verbose(env, "R%d bitwise operator %s on pointer prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; default: /* other operators (e.g. MUL,LSH) produce non-pointer results */ verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; } if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) return -EINVAL; __update_reg_bounds(dst_reg); __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); /* For unprivileged we require that resulting offset must be in bounds * in order to be able to sanitize access later on. */ if (!env->allow_ptr_leaks) { if (dst_reg->type == PTR_TO_MAP_VALUE && check_map_access(env, dst, dst_reg->off, 1, false)) { verbose(env, "R%d pointer arithmetic of map value goes out of range, " "prohibited for !root\n", dst); return -EACCES; } else if (dst_reg->type == PTR_TO_STACK && check_stack_access(env, dst_reg, dst_reg->off + dst_reg->var_off.value, 1)) { verbose(env, "R%d stack pointer arithmetic goes out of range, " "prohibited for !root\n", dst); return -EACCES; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'bpf: prevent out of bounds speculation on pointer arithmetic Jann reported that the original commit back in b2157399cc98 ("bpf: prevent out-of-bounds speculation") was not sufficient to stop CPU from speculating out of bounds memory access: While b2157399cc98 only focussed on masking array map access for unprivileged users for tail calls and data access such that the user provided index gets sanitized from BPF program and syscall side, there is still a more generic form affected from BPF programs that applies to most maps that hold user data in relation to dynamic map access when dealing with unknown scalars or "slow" known scalars as access offset, for example: - Load a map value pointer into R6 - Load an index into R7 - Do a slow computation (e.g. with a memory dependency) that loads a limit into R8 (e.g. load the limit from a map for high latency, then mask it to make the verifier happy) - Exit if R7 >= R8 (mispredicted branch) - Load R0 = R6[R7] - Load R0 = R6[R0] For unknown scalars there are two options in the BPF verifier where we could derive knowledge from in order to guarantee safe access to the memory: i) While </>/<=/>= variants won't allow to derive any lower or upper bounds from the unknown scalar where it would be safe to add it to the map value pointer, it is possible through ==/!= test however. ii) another option is to transform the unknown scalar into a known scalar, for example, through ALU ops combination such as R &= <imm> followed by R |= <imm> or any similar combination where the original information from the unknown scalar would be destroyed entirely leaving R with a constant. The initial slow load still precedes the latter ALU ops on that register, so the CPU executes speculatively from that point. Once we have the known scalar, any compare operation would work then. A third option only involving registers with known scalars could be crafted as described in [0] where a CPU port (e.g. Slow Int unit) would be filled with many dependent computations such that the subsequent condition depending on its outcome has to wait for evaluation on its execution port and thereby executing speculatively if the speculated code can be scheduled on a different execution port, or any other form of mistraining as described in [1], for example. Given this is not limited to only unknown scalars, not only map but also stack access is affected since both is accessible for unprivileged users and could potentially be used for out of bounds access under speculation. In order to prevent any of these cases, the verifier is now sanitizing pointer arithmetic on the offset such that any out of bounds speculation would be masked in a way where the pointer arithmetic result in the destination register will stay unchanged, meaning offset masked into zero similar as in array_index_nospec() case. With regards to implementation, there are three options that were considered: i) new insn for sanitation, ii) push/pop insn and sanitation as inlined BPF, iii) reuse of ax register and sanitation as inlined BPF. Option i) has the downside that we end up using from reserved bits in the opcode space, but also that we would require each JIT to emit masking as native arch opcodes meaning mitigation would have slow adoption till everyone implements it eventually which is counter-productive. Option ii) and iii) have both in common that a temporary register is needed in order to implement the sanitation as inlined BPF since we are not allowed to modify the source register. While a push / pop insn in ii) would be useful to have in any case, it requires once again that every JIT needs to implement it first. While possible, amount of changes needed would also be unsuitable for a -stable patch. Therefore, the path which has fewer changes, less BPF instructions for the mitigation and does not require anything to be changed in the JITs is option iii) which this work is pursuing. The ax register is already mapped to a register in all JITs (modulo arm32 where it's mapped to stack as various other BPF registers there) and used in constant blinding for JITs-only so far. It can be reused for verifier rewrites under certain constraints. The interpreter's tmp "register" has therefore been remapped into extending the register set with hidden ax register and reusing that for a number of instructions that needed the prior temporary variable internally (e.g. div, mod). This allows for zero increase in stack space usage in the interpreter, and enables (restricted) generic use in rewrites otherwise as long as such a patchlet does not make use of these instructions. The sanitation mask is dynamic and relative to the offset the map value or stack pointer currently holds. There are various cases that need to be taken under consideration for the masking, e.g. such operation could look as follows: ptr += val or val += ptr or ptr -= val. Thus, the value to be sanitized could reside either in source or in destination register, and the limit is different depending on whether the ALU op is addition or subtraction and depending on the current known and bounded offset. The limit is derived as follows: limit := max_value_size - (smin_value + off). For subtraction: limit := umax_value + off. This holds because we do not allow any pointer arithmetic that would temporarily go out of bounds or would have an unknown value with mixed signed bounds where it is unclear at verification time whether the actual runtime value would be either negative or positive. For example, we have a derived map pointer value with constant offset and bounded one, so limit based on smin_value works because the verifier requires that statically analyzed arithmetic on the pointer must be in bounds, and thus it checks if resulting smin_value + off and umax_value + off is still within map value bounds at time of arithmetic in addition to time of access. Similarly, for the case of stack access we derive the limit as follows: MAX_BPF_STACK + off for subtraction and -off for the case of addition where off := ptr_reg->off + ptr_reg->var_off.value. Subtraction is a special case for the masking which can be in form of ptr += -val, ptr -= -val, or ptr -= val. In the first two cases where we know that the value is negative, we need to temporarily negate the value in order to do the sanitation on a positive value where we later swap the ALU op, and restore original source register if the value was in source. The sanitation of pointer arithmetic alone is still not fully sufficient as is, since a scenario like the following could happen ... PTR += 0x1000 (e.g. K-based imm) PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON PTR += 0x1000 PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON [...] ... which under speculation could end up as ... PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] [...] ... and therefore still access out of bounds. To prevent such case, the verifier is also analyzing safety for potential out of bounds access under speculative execution. Meaning, it is also simulating pointer access under truncation. We therefore "branch off" and push the current verification state after the ALU operation with known 0 to the verification stack for later analysis. Given the current path analysis succeeded it is likely that the one under speculation can be pruned. In any case, it is also subject to existing complexity limits and therefore anything beyond this point will be rejected. In terms of pruning, it needs to be ensured that the verification state from speculative execution simulation must never prune a non-speculative execution path, therefore, we mark verifier state accordingly at the time of push_stack(). If verifier detects out of bounds access under speculative execution from one of the possible paths that includes a truncation, it will reject such program. Given we mask every reg-based pointer arithmetic for unprivileged programs, we've been looking into how it could affect real-world programs in terms of size increase. As the majority of programs are targeted for privileged-only use case, we've unconditionally enabled masking (with its alu restrictions on top of it) for privileged programs for the sake of testing in order to check i) whether they get rejected in its current form, and ii) by how much the number of instructions and size will increase. We've tested this by using Katran, Cilium and test_l4lb from the kernel selftests. For Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o and an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb we've used test_l4lb.o as well as test_l4lb_noinline.o. We found that none of the programs got rejected by the verifier with this change, and that impact is rather minimal to none. balancer_kern.o had 13,904 bytes (1,738 insns) xlated and 7,797 bytes JITed before and after the change. Most complex program in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated and 18,538 bytes JITed before and after and none of the other tail call programs in bpf_lxc.o had any changes either. For the older bpf_lxc_opt_-DUNKNOWN.o object we found a small increase from 20,616 bytes (2,576 insns) and 12,536 bytes JITed before to 20,664 bytes (2,582 insns) and 12,558 bytes JITed after the change. Other programs from that object file had similar small increase. Both test_l4lb.o had no change and remained at 6,544 bytes (817 insns) xlated and 3,401 bytes JITed and for test_l4lb_noinline.o constant at 5,080 bytes (634 insns) xlated and 3,313 bytes JITed. This can be explained in that LLVM typically optimizes stack based pointer arithmetic by using K-based operations and that use of dynamic map access is not overly frequent. However, in future we may decide to optimize the algorithm further under known guarantees from branch and value speculation. Latter seems also unclear in terms of prediction heuristics that today's CPUs apply as well as whether there could be collisions in e.g. the predictor's Value History/Pattern Table for triggering out of bounds access, thus masking is performed unconditionally at this point but could be subject to relaxation later on. We were generally also brainstorming various other approaches for mitigation, but the blocker was always lack of available registers at runtime and/or overhead for runtime tracking of limits belonging to a specific pointer. Thus, we found this to be minimally intrusive under given constraints. With that in place, a simple example with sanitized access on unprivileged load at post-verification time looks as follows: # bpftool prog dump xlated id 282 [...] 28: (79) r1 = *(u64 *)(r7 +0) 29: (79) r2 = *(u64 *)(r7 +8) 30: (57) r1 &= 15 31: (79) r3 = *(u64 *)(r0 +4608) 32: (57) r3 &= 1 33: (47) r3 |= 1 34: (2d) if r2 > r3 goto pc+19 35: (b4) (u32) r11 = (u32) 20479 | 36: (1f) r11 -= r2 | Dynamic sanitation for pointer 37: (4f) r11 |= r2 | arithmetic with registers 38: (87) r11 = -r11 | containing bounded or known 39: (c7) r11 s>>= 63 | scalars in order to prevent 40: (5f) r11 &= r2 | out of bounds speculation. 41: (0f) r4 += r11 | 42: (71) r4 = *(u8 *)(r4 +0) 43: (6f) r4 <<= r1 [...] For the case where the scalar sits in the destination register as opposed to the source register, the following code is emitted for the above example: [...] 16: (b4) (u32) r11 = (u32) 20479 17: (1f) r11 -= r2 18: (4f) r11 |= r2 19: (87) r11 = -r11 20: (c7) r11 s>>= 63 21: (5f) r2 &= r11 22: (0f) r2 += r0 23: (61) r0 = *(u32 *)(r2 +0) [...] JIT blinding example with non-conflicting use of r10: [...] d5: je 0x0000000000000106 _ d7: mov 0x0(%rax),%edi | da: mov $0xf153246,%r10d | Index load from map value and e0: xor $0xf153259,%r10 | (const blinded) mask with 0x1f. e7: and %r10,%rdi |_ ea: mov $0x2f,%r10d | f0: sub %rdi,%r10 | Sanitized addition. Both use r10 f3: or %rdi,%r10 | but do not interfere with each f6: neg %r10 | other. (Neither do these instructions f9: sar $0x3f,%r10 | interfere with the use of ax as temp fd: and %r10,%rdi | in interpreter.) 100: add %rax,%rdi |_ 103: mov 0x0(%rdi),%eax [...] Tested that it fixes Jann's reproducer, and also checked that test_verifier and test_progs suite with interpreter, JIT and JIT with hardening enabled on x86-64 and arm64 runs successfully. [0] Speculose: Analyzing the Security Implications of Speculative Execution in CPUs, Giorgi Maisuradze and Christian Rossow, https://arxiv.org/pdf/1801.04084.pdf [1] A Systematic Evaluation of Transient Execution Attacks and Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz, Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens, Dmitry Evtyushkin, Daniel Gruss, https://arxiv.org/pdf/1811.05441.pdf Fixes: b2157399cc98 ("bpf: prevent out-of-bounds speculation") Reported-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Alexei Starovoitov <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); bool src_known, dst_known; s64 smin_val, smax_val; u64 umin_val, umax_val; u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; if (insn_bitness == 32) { /* Relevant for 32-bit RSH: Information can propagate towards * LSB, so it isn't sufficient to only truncate the output to * 32 bits. */ coerce_reg_to_size(dst_reg, 4); coerce_reg_to_size(&src_reg, 4); } smin_val = src_reg.smin_value; smax_val = src_reg.smax_value; umin_val = src_reg.umin_value; umax_val = src_reg.umax_value; src_known = tnum_is_const(src_reg.var_off); dst_known = tnum_is_const(dst_reg->var_off); if ((src_known && (smin_val != smax_val || umin_val != umax_val)) || smin_val > smax_val || umin_val > umax_val) { /* Taint dst register if offset had invalid bounds derived from * e.g. dead branches. */ __mark_reg_unknown(dst_reg); return 0; } if (!src_known && opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { __mark_reg_unknown(dst_reg); return 0; } switch (opcode) { case BPF_ADD: if (signed_add_overflows(dst_reg->smin_value, smin_val) || signed_add_overflows(dst_reg->smax_value, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value += smin_val; dst_reg->smax_value += smax_val; } if (dst_reg->umin_value + umin_val < umin_val || dst_reg->umax_value + umax_val < umax_val) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value += umin_val; dst_reg->umax_value += umax_val; } dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); break; case BPF_SUB: if (signed_sub_overflows(dst_reg->smin_value, smax_val) || signed_sub_overflows(dst_reg->smax_value, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value -= smax_val; dst_reg->smax_value -= smin_val; } if (dst_reg->umin_value < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value -= umax_val; dst_reg->umax_value -= umin_val; } dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); break; case BPF_MUL: dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); if (smin_val < 0 || dst_reg->smin_value < 0) { /* Ain't nobody got time to multiply that sign */ __mark_reg_unbounded(dst_reg); __update_reg_bounds(dst_reg); break; } /* Both values are positive, so we can work with unsigned and * copy the result to signed (unless it exceeds S64_MAX). */ if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { /* Potential overflow, we know nothing */ __mark_reg_unbounded(dst_reg); /* (except what we can learn from the var_off) */ __update_reg_bounds(dst_reg); break; } dst_reg->umin_value *= umin_val; dst_reg->umax_value *= umax_val; if (dst_reg->umax_value > S64_MAX) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } break; case BPF_AND: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value & src_reg.var_off.value); break; } /* We get our minimum from the var_off, since that's inherently * bitwise. Our maximum is the minimum of the operands' maxima. */ dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = dst_reg->var_off.value; dst_reg->umax_value = min(dst_reg->umax_value, umax_val); if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ANDing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ANDing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_OR: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value | src_reg.var_off.value); break; } /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = max(dst_reg->umin_value, umin_val); dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_LSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* We lose all sign bit information (except what we can pick * up from var_off) */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; /* If we might shift our top bit out, then we know nothing */ if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value <<= umin_val; dst_reg->umax_value <<= umax_val; } dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_RSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* BPF_RSH is an unsigned shift. If the value in dst_reg might * be negative, then either: * 1) src_reg might be zero, so the sign bit of the result is * unknown, so we lose our signed bounds * 2) it's known negative, thus the unsigned bounds capture the * signed bounds * 3) the signed bounds cross zero, so they tell us nothing * about the result * If the value in dst_reg is known nonnegative, then again the * unsigned bounts capture the signed bounds. * Thus, in all cases it suffices to blow away our signed bounds * and rely on inferring new ones from the unsigned bounds and * var_off of the result. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); dst_reg->umin_value >>= umax_val; dst_reg->umax_value >>= umin_val; /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_ARSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* Upon reaching here, src_known is true and * umax_val is equal to umin_val. */ dst_reg->smin_value >>= umin_val; dst_reg->smax_value >>= umin_val; dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val); /* blow away the dst_reg umin_value/umax_value and rely on * dst_reg var_off to refine the result. */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; __update_reg_bounds(dst_reg); break; default: mark_reg_unknown(env, regs, insn->dst_reg); break; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops are (32,32)->32 */ coerce_reg_to_size(dst_reg, 4); } __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'bpf: fix sanitation of alu op with pointer / scalar type from different paths While 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer arithmetic") took care of rejecting alu op on pointer when e.g. pointer came from two different map values with different map properties such as value size, Jann reported that a case was not covered yet when a given alu op is used in both "ptr_reg += reg" and "numeric_reg += reg" from different branches where we would incorrectly try to sanitize based on the pointer's limit. Catch this corner case and reject the program instead. Fixes: 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer arithmetic") Reported-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Alexei Starovoitov <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct bpf_map *bpf_map_meta_alloc(int inner_map_ufd) { struct bpf_map *inner_map, *inner_map_meta; struct fd f; f = fdget(inner_map_ufd); inner_map = __bpf_map_get(f); if (IS_ERR(inner_map)) return inner_map; /* prog_array->owner_prog_type and owner_jited * is a runtime binding. Doing static check alone * in the verifier is not enough. */ if (inner_map->map_type == BPF_MAP_TYPE_PROG_ARRAY || inner_map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || inner_map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) { fdput(f); return ERR_PTR(-ENOTSUPP); } /* Does not support >1 level map-in-map */ if (inner_map->inner_map_meta) { fdput(f); return ERR_PTR(-EINVAL); } inner_map_meta = kzalloc(sizeof(*inner_map_meta), GFP_USER); if (!inner_map_meta) { fdput(f); return ERR_PTR(-ENOMEM); } inner_map_meta->map_type = inner_map->map_type; inner_map_meta->key_size = inner_map->key_size; inner_map_meta->value_size = inner_map->value_size; inner_map_meta->map_flags = inner_map->map_flags; inner_map_meta->ops = inner_map->ops; inner_map_meta->max_entries = inner_map->max_entries; fdput(f); return inner_map_meta; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'bpf: fix inner map masking to prevent oob under speculation During review I noticed that inner meta map setup for map in map is buggy in that it does not propagate all needed data from the reference map which the verifier is later accessing. In particular one such case is index masking to prevent out of bounds access under speculative execution due to missing the map's unpriv_array/index_mask field propagation. Fix this such that the verifier is generating the correct code for inlined lookups in case of unpriviledged use. Before patch (test_verifier's 'map in map access' dump): # bpftool prog dump xla id 3 0: (62) *(u32 *)(r10 -4) = 0 1: (bf) r2 = r10 2: (07) r2 += -4 3: (18) r1 = map[id:4] 5: (07) r1 += 272 | 6: (61) r0 = *(u32 *)(r2 +0) | 7: (35) if r0 >= 0x1 goto pc+6 | Inlined map in map lookup 8: (54) (u32) r0 &= (u32) 0 | with index masking for 9: (67) r0 <<= 3 | map->unpriv_array. 10: (0f) r0 += r1 | 11: (79) r0 = *(u64 *)(r0 +0) | 12: (15) if r0 == 0x0 goto pc+1 | 13: (05) goto pc+1 | 14: (b7) r0 = 0 | 15: (15) if r0 == 0x0 goto pc+11 16: (62) *(u32 *)(r10 -4) = 0 17: (bf) r2 = r10 18: (07) r2 += -4 19: (bf) r1 = r0 20: (07) r1 += 272 | 21: (61) r0 = *(u32 *)(r2 +0) | Index masking missing (!) 22: (35) if r0 >= 0x1 goto pc+3 | for inner map despite 23: (67) r0 <<= 3 | map->unpriv_array set. 24: (0f) r0 += r1 | 25: (05) goto pc+1 | 26: (b7) r0 = 0 | 27: (b7) r0 = 0 28: (95) exit After patch: # bpftool prog dump xla id 1 0: (62) *(u32 *)(r10 -4) = 0 1: (bf) r2 = r10 2: (07) r2 += -4 3: (18) r1 = map[id:2] 5: (07) r1 += 272 | 6: (61) r0 = *(u32 *)(r2 +0) | 7: (35) if r0 >= 0x1 goto pc+6 | Same inlined map in map lookup 8: (54) (u32) r0 &= (u32) 0 | with index masking due to 9: (67) r0 <<= 3 | map->unpriv_array. 10: (0f) r0 += r1 | 11: (79) r0 = *(u64 *)(r0 +0) | 12: (15) if r0 == 0x0 goto pc+1 | 13: (05) goto pc+1 | 14: (b7) r0 = 0 | 15: (15) if r0 == 0x0 goto pc+12 16: (62) *(u32 *)(r10 -4) = 0 17: (bf) r2 = r10 18: (07) r2 += -4 19: (bf) r1 = r0 20: (07) r1 += 272 | 21: (61) r0 = *(u32 *)(r2 +0) | 22: (35) if r0 >= 0x1 goto pc+4 | Now fixed inlined inner map 23: (54) (u32) r0 &= (u32) 0 | lookup with proper index masking 24: (67) r0 <<= 3 | for map->unpriv_array. 25: (0f) r0 += r1 | 26: (05) goto pc+1 | 27: (b7) r0 = 0 | 28: (b7) r0 = 0 29: (95) exit Fixes: b2157399cc98 ("bpf: prevent out-of-bounds speculation") Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Martin KaFai Lau <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image) { BMPInfo bmp_info; BMPSubtype bmp_subtype; const char *option; const StringInfo *profile; MagickBooleanType have_color_info, status; MemoryInfo *pixel_info; MagickOffsetType scene; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; register unsigned char *q; size_t bytes_per_line, imageListLength, type; ssize_t y; unsigned char *bmp_data, *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); type=4; if (LocaleCompare(image_info->magick,"BMP2") == 0) type=2; else if (LocaleCompare(image_info->magick,"BMP3") == 0) type=3; option=GetImageOption(image_info,"bmp:format"); if (option != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format=%s",option); if (LocaleCompare(option,"bmp2") == 0) type=2; if (LocaleCompare(option,"bmp3") == 0) type=3; if (LocaleCompare(option,"bmp4") == 0) type=4; } scene=0; imageListLength=GetImageListLength(image); do { /* Initialize BMP raster file header. */ if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.file_size=14+12; if (type > 2) bmp_info.file_size+=28; bmp_info.offset_bits=bmp_info.file_size; bmp_info.compression=BI_RGB; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; bmp_info.alpha_mask=0xff000000U; bmp_subtype=UndefinedSubtype; if ((image->storage_class == PseudoClass) && (image->colors > 256)) (void) SetImageStorageClass(image,DirectClass); if (image->storage_class != DirectClass) { /* Colormapped BMP raster. */ bmp_info.bits_per_pixel=8; if (image->colors <= 2) bmp_info.bits_per_pixel=1; else if (image->colors <= 16) bmp_info.bits_per_pixel=4; else if (image->colors <= 256) bmp_info.bits_per_pixel=8; if (image_info->compression == RLECompression) bmp_info.bits_per_pixel=8; bmp_info.number_colors=1U << bmp_info.bits_per_pixel; if (image->matte != MagickFalse) (void) SetImageStorageClass(image,DirectClass); else if ((size_t) bmp_info.number_colors < image->colors) (void) SetImageStorageClass(image,DirectClass); else { bmp_info.file_size+=3*(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=3*(1UL << bmp_info.bits_per_pixel); if (type > 2) { bmp_info.file_size+=(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=(1UL << bmp_info.bits_per_pixel); } } } if (image->storage_class == DirectClass) { /* Full color BMP raster. */ bmp_info.number_colors=0; option=GetImageOption(image_info,"bmp:subtype"); if (option != (const char *) NULL) { if (image->matte != MagickFalse) { if (LocaleNCompare(option,"ARGB4444",8) == 0) { bmp_subtype=ARGB4444; bmp_info.red_mask=0x00000f00U; bmp_info.green_mask=0x000000f0U; bmp_info.blue_mask=0x0000000fU; bmp_info.alpha_mask=0x0000f000U; } else if (LocaleNCompare(option,"ARGB1555",8) == 0) { bmp_subtype=ARGB1555; bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; bmp_info.alpha_mask=0x00008000U; } } else { if (LocaleNCompare(option,"RGB555",6) == 0) { bmp_subtype=RGB555; bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; bmp_info.alpha_mask=0U; } else if (LocaleNCompare(option,"RGB565",6) == 0) { bmp_subtype=RGB565; bmp_info.red_mask=0x0000f800U; bmp_info.green_mask=0x000007e0U; bmp_info.blue_mask=0x0000001fU; bmp_info.alpha_mask=0U; } } } if (bmp_subtype != UndefinedSubtype) { bmp_info.bits_per_pixel=16; bmp_info.compression=BI_BITFIELDS; } else { bmp_info.bits_per_pixel=(unsigned short) ((type > 3) && (image->matte != MagickFalse) ? 32 : 24); bmp_info.compression=(unsigned int) ((type > 3) && (image->matte != MagickFalse) ? BI_BITFIELDS : BI_RGB); if ((type == 3) && (image->matte != MagickFalse)) { option=GetImageOption(image_info,"bmp3:alpha"); if (IsStringTrue(option)) bmp_info.bits_per_pixel=32; } } } bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); bmp_info.ba_offset=0; profile=GetImageProfile(image,"icc"); have_color_info=(image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL) || (image->gamma != 0.0) ? MagickTrue : MagickFalse; if (type == 2) bmp_info.size=12; else if ((type == 3) || ((image->matte == MagickFalse) && (have_color_info == MagickFalse))) { type=3; bmp_info.size=40; } else { int extra_size; bmp_info.size=108; extra_size=68; if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { bmp_info.size=124; extra_size+=16; } bmp_info.file_size+=extra_size; bmp_info.offset_bits+=extra_size; } if (((ssize_t) image->columns != (ssize_t) ((signed int) image->columns)) || ((ssize_t) image->rows != (ssize_t) ((signed int) image->rows))) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); bmp_info.width=(ssize_t) image->columns; bmp_info.height=(ssize_t) image->rows; bmp_info.planes=1; bmp_info.image_size=(unsigned int) (bytes_per_line*image->rows); bmp_info.file_size+=bmp_info.image_size; bmp_info.x_pixels=75*39; bmp_info.y_pixels=75*39; switch (image->units) { case UndefinedResolution: case PixelsPerInchResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->x_resolution/2.54); bmp_info.y_pixels=(unsigned int) (100.0*image->y_resolution/2.54); break; } case PixelsPerCentimeterResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->x_resolution); bmp_info.y_pixels=(unsigned int) (100.0*image->y_resolution); break; } } bmp_info.colors_important=bmp_info.number_colors; /* Convert MIFF to BMP raster pixels. */ pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line, image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) memset(pixels,0,(size_t) bmp_info.image_size); switch (bmp_info.bits_per_pixel) { case 1: { size_t bit, byte; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels+(image->rows-y-1)*bytes_per_line; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; byte|=GetPixelIndex(indexes+x) != 0 ? 0x01 : 0x00; bit++; if (bit == 8) { *q++=(unsigned char) byte; bit=0; byte=0; } } if (bit != 0) { *q++=(unsigned char) (byte << (8-bit)); x++; } for (x=(ssize_t) (image->columns+7)/8; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 4: { size_t nibble, byte; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels+(image->rows-y-1)*bytes_per_line; nibble=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=4; byte|=((size_t) GetPixelIndex(indexes+x) & 0x0f); nibble++; if (nibble == 2) { *q++=(unsigned char) byte; nibble=0; byte=0; } } if (nibble != 0) { *q++=(unsigned char) (byte << 4); x++; } for (x=(ssize_t) (image->columns+1)/2; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoClass packet to BMP pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); for ( ; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 16: { /* Convert DirectClass packet to BMP BGR888. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=(pixels+(image->rows-y-1)*bytes_per_line); for (x=0; x < (ssize_t) image->columns; x++) { unsigned short pixel; pixel=0; if (bmp_subtype == ARGB4444) { pixel=(unsigned short) (ScaleQuantumToAny( GetPixelAlpha(p),15) << 12); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelRed(p),15) << 8); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelGreen(p),15) << 4); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelBlue(p),15)); } else if (bmp_subtype == RGB565) { pixel=(unsigned short) (ScaleQuantumToAny( GetPixelRed(p),31) << 11); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelGreen(p),63) << 5); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelBlue(p),31)); } else { if (bmp_subtype == ARGB1555) pixel=(unsigned short) (ScaleQuantumToAny( GetPixelAlpha(p),1) << 15); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelRed(p),31) << 10); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelGreen(p),31) << 5); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelBlue(p),31)); } *((unsigned short *) q)=pixel; q+=2; p++; } for (x=2L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectClass packet to BMP BGR888. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelRed(p)); p++; } for (x=3L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert DirectClass packet to ARGB8888 pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelAlpha(p)); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } if ((type > 2) && (bmp_info.bits_per_pixel == 8)) if (image_info->compression != NoCompression) { MemoryInfo *rle_info; /* Convert run-length encoded raster pixels. */ rle_info=AcquireVirtualMemory((size_t) (2*(bytes_per_line+2)+2), (image->rows+2)*sizeof(*pixels)); if (rle_info == (MemoryInfo *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } bmp_data=(unsigned char *) GetVirtualMemoryBlob(rle_info); bmp_info.file_size-=bmp_info.image_size; bmp_info.image_size=(unsigned int) EncodeImage(image,bytes_per_line, pixels,bmp_data); bmp_info.file_size+=bmp_info.image_size; pixel_info=RelinquishVirtualMemory(pixel_info); pixel_info=rle_info; pixels=bmp_data; bmp_info.compression=BI_RLE8; } /* Write BMP for Windows, all versions, 14-byte header. */ if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing BMP version %.20g datastream",(double) type); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class=DirectClass"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image depth=%.20g",(double) image->depth); if (image->matte != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte=True"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte=MagickFalse"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " BMP bits_per_pixel=%.20g",(double) bmp_info.bits_per_pixel); switch ((int) bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=BI_RGB"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=BI_BITFIELDS"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=UNKNOWN (%u)",bmp_info.compression); break; } } if (bmp_info.number_colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number_colors=unspecified"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number_colors=%u",bmp_info.number_colors); } (void) WriteBlob(image,2,(unsigned char *) "BM"); (void) WriteBlobLSBLong(image,bmp_info.file_size); (void) WriteBlobLSBLong(image,bmp_info.ba_offset); /* always 0 */ (void) WriteBlobLSBLong(image,bmp_info.offset_bits); if (type == 2) { /* Write 12-byte version 2 bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.width); (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); } else { /* Write 40-byte version 3+ bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBSignedLong(image,(signed long) bmp_info.width); (void) WriteBlobLSBSignedLong(image,(signed long) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); (void) WriteBlobLSBLong(image,bmp_info.compression); (void) WriteBlobLSBLong(image,bmp_info.image_size); (void) WriteBlobLSBLong(image,bmp_info.x_pixels); (void) WriteBlobLSBLong(image,bmp_info.y_pixels); (void) WriteBlobLSBLong(image,bmp_info.number_colors); (void) WriteBlobLSBLong(image,bmp_info.colors_important); } if ((type > 3) && ((image->matte != MagickFalse) || (have_color_info != MagickFalse))) { /* Write the rest of the 108-byte BMP Version 4 header. */ (void) WriteBlobLSBLong(image,bmp_info.red_mask); (void) WriteBlobLSBLong(image,bmp_info.green_mask); (void) WriteBlobLSBLong(image,bmp_info.blue_mask); (void) WriteBlobLSBLong(image,bmp_info.alpha_mask); (void) WriteBlobLSBLong(image,0x73524742U); /* sRGB */ (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.red_primary.x+ image->chromaticity.red_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.green_primary.x+ image->chromaticity.green_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.blue_primary.x+ image->chromaticity.blue_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.x*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.y*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.z*0x10000)); if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { ssize_t intent; switch ((int) image->rendering_intent) { case SaturationIntent: { intent=LCS_GM_BUSINESS; break; } case RelativeIntent: { intent=LCS_GM_GRAPHICS; break; } case PerceptualIntent: { intent=LCS_GM_IMAGES; break; } case AbsoluteIntent: { intent=LCS_GM_ABS_COLORIMETRIC; break; } default: { intent=0; break; } } (void) WriteBlobLSBLong(image,(unsigned int) intent); (void) WriteBlobLSBLong(image,0x00); /* dummy profile data */ (void) WriteBlobLSBLong(image,0x00); /* dummy profile length */ (void) WriteBlobLSBLong(image,0x00); /* reserved */ } } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; /* Dump colormap to file. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Colormap: %.20g entries",(double) image->colors); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL << bmp_info.bits_per_pixel),4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); q=bmp_colormap; for (i=0; i < (ssize_t) MagickMin((ssize_t) image->colors,(ssize_t) bmp_info.number_colors); i++) { *q++=ScaleQuantumToChar(image->colormap[i].blue); *q++=ScaleQuantumToChar(image->colormap[i].green); *q++=ScaleQuantumToChar(image->colormap[i].red); if (type > 2) *q++=(unsigned char) 0x0; } for ( ; i < (ssize_t) (1UL << bmp_info.bits_per_pixel); i++) { *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; if (type > 2) *q++=(unsigned char) 0x00; } if (type <= 2) (void) WriteBlob(image,(size_t) (3*(1L << bmp_info.bits_per_pixel)), bmp_colormap); else (void) WriteBlob(image,(size_t) (4*(1L << bmp_info.bits_per_pixel)), bmp_colormap); bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Pixels: %u bytes",bmp_info.image_size); (void) WriteBlob(image,(size_t) bmp_info.image_size,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " File_size: %u bytes",bmp_info.file_size); (void) CloseBlob(image); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1453'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image) { #define CFormat "/Filter [ /%s ]\n" #define ObjectsPerImage 14 #define ThrowPDFException(exception,message) \ { \ if (xref != (MagickOffsetType *) NULL) \ xref=(MagickOffsetType *) RelinquishMagickMemory(xref); \ ThrowWriterException((exception),(message)); \ } DisableMSCWarning(4310) static const char XMPProfile[]= { "<?xpacket begin=\"%s\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n" "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:08:23\">\n" " <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:xap=\"http://ns.adobe.com/xap/1.0/\">\n" " <xap:ModifyDate>%s</xap:ModifyDate>\n" " <xap:CreateDate>%s</xap:CreateDate>\n" " <xap:MetadataDate>%s</xap:MetadataDate>\n" " <xap:CreatorTool>%s</xap:CreatorTool>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n" " <dc:format>application/pdf</dc:format>\n" " <dc:title>\n" " <rdf:Alt>\n" " <rdf:li xml:lang=\"x-default\">%s</rdf:li>\n" " </rdf:Alt>\n" " </dc:title>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\">\n" " <xapMM:DocumentID>uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf</xapMM:DocumentID>\n" " <xapMM:InstanceID>uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb</xapMM:InstanceID>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\">\n" " <pdf:Producer>%s</pdf:Producer>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n" " <pdfaid:part>3</pdfaid:part>\n" " <pdfaid:conformance>B</pdfaid:conformance>\n" " </rdf:Description>\n" " </rdf:RDF>\n" "</x:xmpmeta>\n" "<?xpacket end=\"w\"?>\n" }, XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 }; RestoreMSCWarning char basename[MaxTextExtent], buffer[MaxTextExtent], date[MaxTextExtent], *escape, **labels, page_geometry[MaxTextExtent], *url; CompressionType compression; const char *device, *option, *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; Image *next, *tile_image; MagickBooleanType status; MagickOffsetType offset, scene, *xref; MagickSizeType number_pixels; MagickStatusType flags; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register const IndexPacket *indexes; register const PixelPacket *p; register unsigned char *q; register ssize_t i, x; size_t channels, imageListLength, info_id, length, object, pages_id, root_id, text_size, version; ssize_t count, page_count, y; struct tm local_time; time_t seconds; unsigned char *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Allocate X ref memory. */ xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(xref,0,2048UL*sizeof(*xref)); /* Write Info object. */ object=0; version=3; if (image_info->compression == JPEG2000Compression) version=(size_t) MagickMax(version,5); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) if (next->matte != MagickFalse) version=(size_t) MagickMax(version,4); if (LocaleCompare(image_info->magick,"PDFA") == 0) version=(size_t) MagickMax(version,6); profile=GetImageProfile(image,"icc"); if (profile != (StringInfo *) NULL) version=(size_t) MagickMax(version,7); (void) FormatLocaleString(buffer,MaxTextExtent,"%%PDF-1.%.20g \n",(double) version); (void) WriteBlobString(image,buffer); if (LocaleCompare(image_info->magick,"PDFA") == 0) { (void) WriteBlobByte(image,'%'); (void) WriteBlobByte(image,0xe2); (void) WriteBlobByte(image,0xe3); (void) WriteBlobByte(image,0xcf); (void) WriteBlobByte(image,0xd3); (void) WriteBlobByte(image,'\n'); } /* Write Catalog object. */ xref[object++]=TellBlob(image); root_id=object; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (LocaleCompare(image_info->magick,"PDFA") != 0) (void) FormatLocaleString(buffer,MaxTextExtent,"/Pages %.20g 0 R\n",(double) object+1); else { (void) FormatLocaleString(buffer,MaxTextExtent,"/Metadata %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Pages %.20g 0 R\n", (double) object+2); } (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Type /Catalog"); option=GetImageOption(image_info,"pdf:page-direction"); if ((option != (const char *) NULL) && (LocaleCompare(option,"right-to-left") == 0)) (void) WriteBlobString(image,"/ViewerPreferences<</PageDirection/R2L>>\n"); (void) WriteBlobString(image,"\n"); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); GetPathComponent(image->filename,BasePath,basename); if (LocaleCompare(image_info->magick,"PDFA") == 0) { char create_date[MaxTextExtent], modify_date[MaxTextExtent], timestamp[MaxTextExtent], xmp_profile[MaxTextExtent], *url; /* Write XMP object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Subtype /XML\n"); *modify_date='\0'; value=GetImageProperty(image,"date:modify"); if (value != (const char *) NULL) (void) CopyMagickString(modify_date,value,MaxTextExtent); *create_date='\0'; value=GetImageProperty(image,"date:create"); if (value != (const char *) NULL) (void) CopyMagickString(create_date,value,MaxTextExtent); (void) FormatMagickTime(time((time_t *) NULL),MaxTextExtent,timestamp); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(basename); i=FormatLocaleString(xmp_profile,MaxTextExtent,XMPProfile, XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url); escape=DestroyString(escape); (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g\n",(double) i); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Type /Metadata\n"); (void) WriteBlobString(image,">>\nstream\n"); (void) WriteBlobString(image,xmp_profile); (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); } /* Write Pages object. */ xref[object++]=TellBlob(image); pages_id=object; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /Pages\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Kids [ %.20g 0 R ",(double) object+1); (void) WriteBlobString(image,buffer); count=(ssize_t) (pages_id+ObjectsPerImage+1); page_count=1; if (image_info->adjoin != MagickFalse) { Image *kid_image; /* Predict page object id's. */ kid_image=image; for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage) { page_count++; profile=GetImageProfile(kid_image,"icc"); if (profile != (StringInfo *) NULL) count+=2; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 R ",(double) count); (void) WriteBlobString(image,buffer); kid_image=GetNextImageInList(kid_image); } xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL, sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) WriteBlobString(image,"]\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Count %.20g\n",(double) page_count); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); scene=0; imageListLength=GetImageListLength(image); do { MagickBooleanType has_icc_profile; profile=GetImageProfile(image,"icc"); has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse; compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { if ((SetImageMonochrome(image,&image->exception) == MagickFalse) || (image->matte != MagickFalse)) compression=RLECompression; break; } #if !defined(MAGICKCORE_JPEG_DELEGATE) case JPEGCompression: { compression=RLECompression; (void) ThrowMagickException(&image->exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)", image->filename); break; } #endif #if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE) case JPEG2000Compression: { compression=RLECompression; (void) ThrowMagickException(&image->exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JP2)", image->filename); break; } #endif #if !defined(MAGICKCORE_ZLIB_DELEGATE) case ZipCompression: { compression=RLECompression; (void) ThrowMagickException(&image->exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)", image->filename); break; } #endif case LZWCompression: { if (LocaleCompare(image_info->magick,"PDFA") == 0) compression=RLECompression; /* LZW compression is forbidden */ break; } case NoCompression: { if (LocaleCompare(image_info->magick,"PDFA") == 0) compression=RLECompression; /* ASCII 85 compression is forbidden */ break; } default: break; } if (compression == JPEG2000Compression) (void) TransformImageColorspace(image,sRGBColorspace); /* Scale relative to dots-per-inch. */ delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->x_resolution; resolution.y=image->y_resolution; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MaxTextExtent,"%.20gx%.20g",(double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MaxTextExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,"PDF") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry,MaxTextExtent); (void) ConcatenateMagickString(page_geometry,">",MaxTextExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info, &image->exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); (void) text_size; /* Write Page object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /Page\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Parent %.20g 0 R\n", (double) pages_id); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Resources <<\n"); labels=(char **) NULL; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent, "/Font << /F%.20g %.20g 0 R >>\n",(double) image->scene,(double) object+4); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MaxTextExtent, "/XObject << /Im%.20g %.20g 0 R >>\n",(double) image->scene,(double) object+5); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/ProcSet %.20g 0 R >>\n", (double) object+3); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "/MediaBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x, 72.0*media_info.height/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "/CropBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x, 72.0*media_info.height/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Contents %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Thumb %.20g 0 R\n", (double) object+(has_icc_profile != MagickFalse ? 10 : 8)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Contents object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); (void) WriteBlobString(image,"q\n"); if (labels != (char **) NULL) for (i=0; labels[i] != (char *) NULL; i++) { (void) WriteBlobString(image,"BT\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/F%.20g %g Tf\n", (double) image->scene,pointsize); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g Td\n", (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+ 12)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"(%s) Tj\n",labels[i]); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"ET\n"); labels[i]=DestroyString(labels[i]); } (void) FormatLocaleString(buffer,MaxTextExtent,"%g 0 0 %g %.20g %.20g cm\n", scale.x,scale.y,(double) geometry.x,(double) geometry.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Im%.20g Do\n",(double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"Q\n"); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write Procset object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) CopyMagickString(buffer,"[ /PDF /Text /ImageC",MaxTextExtent); else if ((compression == FaxCompression) || (compression == Group4Compression)) (void) CopyMagickString(buffer,"[ /PDF /Text /ImageB",MaxTextExtent); else (void) CopyMagickString(buffer,"[ /PDF /Text /ImageI",MaxTextExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image," ]\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Font object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (labels != (char **) NULL) { (void) WriteBlobString(image,"/Type /Font\n"); (void) WriteBlobString(image,"/Subtype /Type1\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Name /F%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/BaseFont /Helvetica\n"); (void) WriteBlobString(image,"/Encoding /MacRomanEncoding\n"); labels=(char **) RelinquishMagickMemory(labels); } (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write XObject object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /XObject\n"); (void) WriteBlobString(image,"/Subtype /Image\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Name /Im%.20g\n",(double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"ASCII85Decode"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"DCTDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MaxTextExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"JPXDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MaxTextExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"FlateDecode"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n", MaxTextExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/DecodeParms [ << " "/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam, (double) image->columns,(double) image->rows); break; } default: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",(double) image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/ColorSpace %.20g 0 R\n", (double) object+2); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); if (image->matte != MagickFalse) { (void) FormatLocaleString(buffer,MaxTextExtent,"/SMask %.20g 0 R\n", (double) object+(has_icc_profile != MagickFalse ? 9 : 7)); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels))) ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,"0") == 0) { (void) HuffmanEncodeImage(image_info,image,image); break; } (void) Huffman2DEncodeImage(image_info,image,image); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg", &image->exception); if (status == MagickFalse) ThrowPDFException(CoderError,image->exception.reason); break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,"jp2", &image->exception); if (status == MagickFalse) ThrowPDFException(CoderError,image->exception.reason); break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p))); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p)))); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg", &image->exception); if (status == MagickFalse) ThrowPDFException(CoderError,image->exception.reason); break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,"jp2", &image->exception); if (status == MagickFalse) ThrowPDFException(CoderError,image->exception.reason); break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; length*=image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelBlue(p)); if (image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelIndex(indexes+x)); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelIndex(indexes+x))); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } else { /* Dump number of colors and colormap. */ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); ThrowPDFException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) Ascii85Encode(image,(unsigned char) GetPixelIndex(indexes+x)); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write Colorspace object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); device="DeviceRGB"; channels=0; if (image->colorspace == CMYKColorspace) { device="DeviceCMYK"; channels=4; } else if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse))) { device="DeviceGray"; channels=1; } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) { device="DeviceRGB"; channels=3; } profile=GetImageProfile(image,"icc"); if ((profile == (StringInfo *) NULL) || (channels == 0)) { if (channels != 0) (void) FormatLocaleString(buffer,MaxTextExtent,"/%s\n",device); else (void) FormatLocaleString(buffer,MaxTextExtent, "[ /Indexed /%s %.20g %.20g 0 R ]\n",device,(double) image->colors- 1,(double) object+3); (void) WriteBlobString(image,buffer); } else { const unsigned char *p; /* Write ICC profile. */ (void) FormatLocaleString(buffer,MaxTextExtent, "[/ICCBased %.20g 0 R]\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"<<\n/N %.20g\n" "/Filter /ASCII85Decode\n/Length %.20g 0 R\n/Alternate /%s\n>>\n" "stream\n",(double) channels,(double) object+1,device); (void) WriteBlobString(image,buffer); offset=TellBlob(image); Ascii85Initialize(image); p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) Ascii85Encode(image,(unsigned char) *p++); Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"endstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"endobj\n"); /* Write Thumb object. */ SetGeometry(image,&geometry); (void) ParseMetaGeometry("106x106+0+0>",&geometry.x,&geometry.y, &geometry.width,&geometry.height); tile_image=ThumbnailImage(image,geometry.width,geometry.height, &image->exception); if (tile_image == (Image *) NULL) ThrowPDFException(ResourceLimitError,image->exception.reason); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"ASCII85Decode"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"DCTDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MaxTextExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"JPXDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MaxTextExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"FlateDecode"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n", MaxTextExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/DecodeParms [ << " "/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam, (double) tile_image->columns,(double) tile_image->rows); break; } default: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double) tile_image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",(double) tile_image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/ColorSpace %.20g 0 R\n", (double) object-(has_icc_profile != MagickFalse ? 3 : 1)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows; if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(tile_image,&image->exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,"0") == 0) { (void) HuffmanEncodeImage(image_info,image,tile_image); break; } (void) Huffman2DEncodeImage(image_info,image,tile_image); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,"jpeg", &image->exception); if (status == MagickFalse) ThrowPDFException(CoderError,tile_image->exception.reason); break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,"jp2", &image->exception); if (status == MagickFalse) ThrowPDFException(CoderError,tile_image->exception.reason); break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p))); p++; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p)))); p++; } } Ascii85Flush(image); break; } } } else if ((tile_image->storage_class == DirectClass) || (tile_image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,"jpeg", &image->exception); if (status == MagickFalse) ThrowPDFException(CoderError,tile_image->exception.reason); break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,"jp2", &image->exception); if (status == MagickFalse) ThrowPDFException(CoderError,tile_image->exception.reason); break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runoffset encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelBlue(p)); if (tile_image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelIndex(indexes+x)); p++; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelIndex(indexes+x))); p++; } } Ascii85Flush(image); break; } } else { /* Dump number of colors and colormap. */ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) Ascii85Encode(image,(unsigned char) GetPixelIndex(indexes+x)); } Ascii85Flush(image); break; } } } tile_image=DestroyImage(tile_image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == FaxCompression) || (compression == Group4Compression)) (void) WriteBlobString(image,">>\n"); else { /* Write Colormap object. */ if (compression == NoCompression) (void) WriteBlobString(image,"/Filter [ /ASCII85Decode ]\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); if (compression == NoCompression) Ascii85Initialize(image); for (i=0; i < (ssize_t) image->colors; i++) { if (compression == NoCompression) { Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].red)); Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].green)); Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].blue)); continue; } (void) WriteBlobByte(image, ScaleQuantumToChar(image->colormap[i].red)); (void) WriteBlobByte(image, ScaleQuantumToChar(image->colormap[i].green)); (void) WriteBlobByte(image, ScaleQuantumToChar(image->colormap[i].blue)); } if (compression == NoCompression) Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); } (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write softmask object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (image->matte == MagickFalse) (void) WriteBlobString(image,">>\n"); else { (void) WriteBlobString(image,"/Type /XObject\n"); (void) WriteBlobString(image,"/Subtype /Image\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Name /Ma%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "ASCII85Decode"); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "FlateDecode"); break; } default: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n", (double) image->rows); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/ColorSpace /DeviceGray\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { image=DestroyImage(image); ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(p))); p++; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar((Quantum) (QuantumRange- GetPixelOpacity(p)))); p++; } } Ascii85Flush(image); break; } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); } (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); /* Write Metadata object. */ xref[object++]=TellBlob(image); info_id=object; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (LocaleCompare(image_info->magick,"PDFA") == 0) (void) FormatLocaleString(buffer,MagickPathExtent,"/Title (%s)\n", EscapeParenthesis(basename)); else { wchar_t *utf16; utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length); if (utf16 != (wchar_t *) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent,"/Title (\xfe\xff"); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) length; i++) (void) WriteBlobMSBShort(image,(unsigned short) utf16[i]); (void) FormatLocaleString(buffer,MagickPathExtent,")\n"); utf16=(wchar_t *) RelinquishMagickMemory(utf16); } } (void) WriteBlobString(image,buffer); seconds=time((time_t *) NULL); #if defined(MAGICKCORE_HAVE_LOCALTIME_R) (void) localtime_r(&seconds,&local_time); #else (void) memcpy(&local_time,localtime(&seconds),sizeof(local_time)); #endif (void) FormatLocaleString(date,MaxTextExtent,"D:%04d%02d%02d%02d%02d%02d", local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday, local_time.tm_hour,local_time.tm_min,local_time.tm_sec); (void) FormatLocaleString(buffer,MaxTextExtent,"/CreationDate (%s)\n",date); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/ModDate (%s)\n",date); (void) WriteBlobString(image,buffer); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(url); (void) FormatLocaleString(buffer,MaxTextExtent,"/Producer (%s)\n",escape); escape=DestroyString(escape); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Xref object. */ offset=TellBlob(image)-xref[0]+ (LocaleCompare(image_info->magick,"PDFA") == 0 ? 6 : 0)+10; (void) WriteBlobString(image,"xref\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"0 %.20g\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"0000000000 65535 f \n"); for (i=0; i < (ssize_t) object; i++) { (void) FormatLocaleString(buffer,MaxTextExtent,"%010lu 00000 n \n", (unsigned long) xref[i]); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"trailer\n"); (void) WriteBlobString(image,"<<\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Size %.20g\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Info %.20g 0 R\n",(double) info_id); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Root %.20g 0 R\n",(double) root_id); (void) WriteBlobString(image,buffer); (void) SignatureImage(image); (void) FormatLocaleString(buffer,MaxTextExtent,"/ID [<%s> <%s>]\n", GetImageProperty(image,"signature"),GetImageProperty(image,"signature")); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"startxref\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"%%EOF\n"); xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1454'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate, const CompressionType compression,ExceptionInfo *exception) { MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t count, length; ssize_t y; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,compression,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } memset(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1451'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: apply_extra_data (FlatpakDir *self, GFile *checkoutdir, GCancellable *cancellable, GError **error) { g_autoptr(GFile) metadata = NULL; g_autofree char *metadata_contents = NULL; gsize metadata_size; g_autoptr(GKeyFile) metakey = NULL; g_autofree char *id = NULL; g_autofree char *runtime = NULL; g_autofree char *runtime_ref = NULL; g_autoptr(FlatpakDeploy) runtime_deploy = NULL; g_autoptr(FlatpakBwrap) bwrap = NULL; g_autoptr(GFile) app_files = NULL; g_autoptr(GFile) apply_extra_file = NULL; g_autoptr(GFile) app_export_file = NULL; g_autoptr(GFile) extra_export_file = NULL; g_autoptr(GFile) extra_files = NULL; g_autoptr(GFile) runtime_files = NULL; g_auto(GStrv) runtime_ref_parts = NULL; g_autoptr(FlatpakContext) app_context = NULL; g_auto(GStrv) minimal_envp = NULL; int exit_status; const char *group = FLATPAK_METADATA_GROUP_APPLICATION; g_autoptr(GError) local_error = NULL; apply_extra_file = g_file_resolve_relative_path (checkoutdir, "files/bin/apply_extra"); if (!g_file_query_exists (apply_extra_file, cancellable)) return TRUE; metadata = g_file_get_child (checkoutdir, "metadata"); if (!g_file_load_contents (metadata, cancellable, &metadata_contents, &metadata_size, NULL, error)) return FALSE; metakey = g_key_file_new (); if (!g_key_file_load_from_data (metakey, metadata_contents, metadata_size, 0, error)) return FALSE; id = g_key_file_get_string (metakey, group, FLATPAK_METADATA_KEY_NAME, &local_error); if (id == NULL) { group = FLATPAK_METADATA_GROUP_RUNTIME; id = g_key_file_get_string (metakey, group, FLATPAK_METADATA_KEY_NAME, NULL); if (id == NULL) { g_propagate_error (error, g_steal_pointer (&local_error)); return FALSE; } g_clear_error (&local_error); } runtime = g_key_file_get_string (metakey, group, FLATPAK_METADATA_KEY_RUNTIME, error); if (runtime == NULL) return FALSE; runtime_ref = g_build_filename ("runtime", runtime, NULL); runtime_ref_parts = flatpak_decompose_ref (runtime_ref, error); if (runtime_ref_parts == NULL) return FALSE; if (!g_key_file_get_boolean (metakey, FLATPAK_METADATA_GROUP_EXTRA_DATA, FLATPAK_METADATA_KEY_NO_RUNTIME, NULL)) { runtime_deploy = flatpak_find_deploy_for_ref (runtime_ref, NULL, cancellable, error); if (runtime_deploy == NULL) return FALSE; runtime_files = flatpak_deploy_get_files (runtime_deploy); } app_files = g_file_get_child (checkoutdir, "files"); app_export_file = g_file_get_child (checkoutdir, "export"); extra_files = g_file_get_child (app_files, "extra"); extra_export_file = g_file_get_child (extra_files, "export"); minimal_envp = flatpak_run_get_minimal_env (FALSE, FALSE); bwrap = flatpak_bwrap_new (minimal_envp); flatpak_bwrap_add_args (bwrap, flatpak_get_bwrap (), NULL); if (runtime_files) flatpak_bwrap_add_args (bwrap, "--ro-bind", flatpak_file_get_path_cached (runtime_files), "/usr", "--lock-file", "/usr/.ref", NULL); flatpak_bwrap_add_args (bwrap, "--ro-bind", flatpak_file_get_path_cached (app_files), "/app", "--bind", flatpak_file_get_path_cached (extra_files), "/app/extra", "--chdir", "/app/extra", /* We run as root in the system-helper case, so drop all caps */ "--cap-drop", "ALL", NULL); if (!flatpak_run_setup_base_argv (bwrap, runtime_files, NULL, runtime_ref_parts[2], FLATPAK_RUN_FLAG_NO_SESSION_HELPER, error)) return FALSE; app_context = flatpak_context_new (); if (!flatpak_run_add_environment_args (bwrap, NULL, FLATPAK_RUN_FLAG_NO_SESSION_BUS_PROXY | FLATPAK_RUN_FLAG_NO_SYSTEM_BUS_PROXY | FLATPAK_RUN_FLAG_NO_A11Y_BUS_PROXY, id, app_context, NULL, NULL, cancellable, error)) return FALSE; flatpak_bwrap_add_arg (bwrap, "/app/bin/apply_extra"); flatpak_bwrap_finish (bwrap); g_debug ("Running /app/bin/apply_extra "); /* We run the sandbox without caps, but it can still create files owned by itself with * arbitrary permissions, including setuid myself. This is extra risky in the case where * this runs as root in the system helper case. We canonicalize the permissions at the * end, but do avoid non-canonical permissions leaking out before then we make the * toplevel dir only accessible to the user */ if (chmod (flatpak_file_get_path_cached (extra_files), 0700) != 0) { glnx_set_error_from_errno (error); return FALSE; } if (!g_spawn_sync (NULL, (char **) bwrap->argv->pdata, bwrap->envp, G_SPAWN_SEARCH_PATH, child_setup, bwrap->fds, NULL, NULL, &exit_status, error)) return FALSE; if (!flatpak_canonicalize_permissions (AT_FDCWD, flatpak_file_get_path_cached (extra_files), getuid() == 0 ? 0 : -1, getuid() == 0 ? 0 : -1, error)) return FALSE; if (exit_status != 0) { g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, _("apply_extra script failed, exit status %d"), exit_status); return FALSE; } if (g_file_query_exists (extra_export_file, cancellable)) { if (!flatpak_mkdir_p (app_export_file, cancellable, error)) return FALSE; if (!flatpak_cp_a (extra_export_file, app_export_file, FLATPAK_CP_FLAGS_MERGE, cancellable, error)) return FALSE; } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-668'], 'message': 'Don't expose /proc when running apply_extra As shown by CVE-2019-5736, it is sometimes possible for the sandbox app to access outside files using /proc/self/exe. This is not typically an issue for flatpak as the sandbox runs as the user which has no permissions to e.g. modify the host files. However, when installing apps using extra-data into the system repo we *do* actually run a sandbox as root. So, in this case we disable mounting /proc in the sandbox, which will neuter attacks like this.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: wav_write_header (SF_PRIVATE *psf, int calc_length) { sf_count_t current ; int error, has_data = SF_FALSE ; current = psf_ftell (psf) ; if (current > psf->dataoffset) has_data = SF_TRUE ; if (calc_length) { psf->filelength = psf_get_filelen (psf) ; psf->datalength = psf->filelength - psf->dataoffset ; if (psf->dataend) psf->datalength -= psf->filelength - psf->dataend ; else if (psf->bytewidth > 0 && psf->sf.seekable == SF_TRUE) psf->datalength = psf->sf.frames * psf->bytewidth * psf->sf.channels ; } ; /* Reset the current header length to zero. */ psf->header.ptr [0] = 0 ; psf->header.indx = 0 ; psf_fseek (psf, 0, SEEK_SET) ; /* ** RIFX signifies big-endian format for all header and data. ** To prevent lots of code copying here, we'll set the psf->rwf_endian flag ** once here, and never specify endian-ness for all other header operations. */ /* RIFF/RIFX marker, length, WAVE and 'fmt ' markers. */ if (psf->endian == SF_ENDIAN_LITTLE) psf_binheader_writef (psf, "etm8", BHWm (RIFF_MARKER), BHW8 ((psf->filelength < 8) ? 8 : psf->filelength - 8)) ; else psf_binheader_writef (psf, "Etm8", BHWm (RIFX_MARKER), BHW8 ((psf->filelength < 8) ? 8 : psf->filelength - 8)) ; /* WAVE and 'fmt ' markers. */ psf_binheader_writef (psf, "mm", BHWm (WAVE_MARKER), BHWm (fmt_MARKER)) ; /* Write the 'fmt ' chunk. */ switch (SF_CONTAINER (psf->sf.format)) { case SF_FORMAT_WAV : if ((error = wav_write_fmt_chunk (psf)) != 0) return error ; break ; case SF_FORMAT_WAVEX : if ((error = wavex_write_fmt_chunk (psf)) != 0) return error ; break ; default : return SFE_UNIMPLEMENTED ; } ; /* The LIST/INFO chunk. */ if (psf->strings.flags & SF_STR_LOCATE_START) wavlike_write_strings (psf, SF_STR_LOCATE_START) ; if (psf->peak_info != NULL && psf->peak_info->peak_loc == SF_PEAK_START) wavlike_write_peak_chunk (psf) ; if (psf->broadcast_16k != NULL) wavlike_write_bext_chunk (psf) ; if (psf->cart_16k != NULL) wavlike_write_cart_chunk (psf) ; if (psf->cues != NULL) { uint32_t k ; psf_binheader_writef (psf, "em44", BHWm (cue_MARKER), BHW4 (4 + psf->cues->cue_count * 6 * 4), BHW4 (psf->cues->cue_count)) ; for (k = 0 ; k < psf->cues->cue_count ; k++) psf_binheader_writef (psf, "e44m444", BHW4 (psf->cues->cue_points [k].indx), BHW4 (psf->cues->cue_points [k].position), BHWm (psf->cues->cue_points [k].fcc_chunk), BHW4 (psf->cues->cue_points [k].chunk_start), BHW4 (psf->cues->cue_points [k].block_start), BHW4 (psf->cues->cue_points [k].sample_offset)) ; } ; if (psf->instrument != NULL) { int tmp ; double dtune = (double) (0x40000000) / 25.0 ; psf_binheader_writef (psf, "m4", BHWm (smpl_MARKER), BHW4 (9 * 4 + psf->instrument->loop_count * 6 * 4)) ; psf_binheader_writef (psf, "44", BHW4 (0), BHW4 (0)) ; /* Manufacturer zero is everyone */ tmp = (int) (1.0e9 / psf->sf.samplerate) ; /* Sample period in nano seconds */ psf_binheader_writef (psf, "44", BHW4 (tmp), BHW4 (psf->instrument->basenote)) ; tmp = (uint32_t) (psf->instrument->detune * dtune + 0.5) ; psf_binheader_writef (psf, "4", BHW4 (tmp)) ; psf_binheader_writef (psf, "44", BHW4 (0), BHW4 (0)) ; /* SMTPE format */ psf_binheader_writef (psf, "44", BHW4 (psf->instrument->loop_count), BHW4 (0)) ; /* Loop count is signed 16 bit number so we limit it range to something sensible. */ psf->instrument->loop_count &= 0x7fff ; for (tmp = 0 ; tmp < psf->instrument->loop_count ; tmp++) { int type ; type = psf->instrument->loops [tmp].mode ; type = (type == SF_LOOP_FORWARD ? 0 : type == SF_LOOP_BACKWARD ? 2 : type == SF_LOOP_ALTERNATING ? 1 : 32) ; psf_binheader_writef (psf, "44", BHW4 (tmp), BHW4 (type)) ; psf_binheader_writef (psf, "44", BHW4 (psf->instrument->loops [tmp].start), BHW4 (psf->instrument->loops [tmp].end - 1)) ; psf_binheader_writef (psf, "44", BHW4 (0), BHW4 (psf->instrument->loops [tmp].count)) ; } ; } ; /* Write custom headers. */ if (psf->wchunks.used > 0) wavlike_write_custom_chunks (psf) ; if (psf->header.indx + 16 < psf->dataoffset) { /* Add PAD data if necessary. */ size_t k = psf->dataoffset - (psf->header.indx + 16) ; psf_binheader_writef (psf, "m4z", BHWm (PAD_MARKER), BHW4 (k), BHWz (k)) ; } ; psf_binheader_writef (psf, "tm8", BHWm (data_MARKER), BHW8 (psf->datalength)) ; psf_fwrite (psf->header.ptr, psf->header.indx, 1, psf) ; if (psf->error) return psf->error ; if (has_data && psf->dataoffset != psf->header.indx) { psf_log_printf (psf, "Oooops : has_data && psf->dataoffset != psf->header.indx\n") ; return psf->error = SFE_INTERNAL ; } ; psf->dataoffset = psf->header.indx ; if (! has_data) psf_fseek (psf, psf->dataoffset, SEEK_SET) ; else if (current > 0) psf_fseek (psf, current, SEEK_SET) ; return psf->error ; } /* wav_write_header */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'wav_write_header: don't read past the array end If loop_count is bigger than the array, truncate it to the array length (and not to 32k). CVE-2019-3832'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: empe_inlinepgp_signed_parse (EMailParserExtension *extension, EMailParser *parser, CamelMimePart *part, GString *part_id, GCancellable *cancellable, GQueue *out_mail_parts) { CamelStream *filtered_stream; CamelMimeFilterPgp *pgp_filter; CamelContentType *content_type; CamelCipherContext *cipher; CamelCipherValidity *valid; CamelDataWrapper *dw; CamelMimePart *opart; CamelStream *ostream; GQueue work_queue = G_QUEUE_INIT; GList *head, *link; gchar *type; gint len; GError *local_error = NULL; GByteArray *ba; if (g_cancellable_is_cancelled (cancellable)) return FALSE; cipher = camel_gpg_context_new (e_mail_parser_get_session (parser)); /* Verify the signature of the message */ valid = camel_cipher_context_verify_sync ( cipher, part, cancellable, &local_error); if (local_error != NULL) { e_mail_parser_error ( parser, out_mail_parts, _("Error verifying signature: %s"), local_error->message); g_error_free (local_error); e_mail_parser_parse_part_as ( parser, part, part_id, "application/vnd.evolution.source", cancellable, out_mail_parts); g_object_unref (cipher); return TRUE; } /* Setup output stream */ ostream = camel_stream_mem_new (); filtered_stream = camel_stream_filter_new (ostream); /* Add PGP header / footer filter */ pgp_filter = (CamelMimeFilterPgp *) camel_mime_filter_pgp_new (); camel_stream_filter_add ( CAMEL_STREAM_FILTER (filtered_stream), CAMEL_MIME_FILTER (pgp_filter)); g_object_unref (pgp_filter); /* Pass through the filters that have been setup */ dw = camel_medium_get_content ((CamelMedium *) part); camel_data_wrapper_decode_to_stream_sync ( dw, (CamelStream *) filtered_stream, cancellable, NULL); camel_stream_flush ((CamelStream *) filtered_stream, cancellable, NULL); g_object_unref (filtered_stream); /* Create a new text/plain MIME part containing the signed * content preserving the original part's Content-Type params. */ content_type = camel_mime_part_get_content_type (part); type = camel_content_type_format (content_type); content_type = camel_content_type_decode (type); g_free (type); g_free (content_type->type); content_type->type = g_strdup ("text"); g_free (content_type->subtype); content_type->subtype = g_strdup ("plain"); type = camel_content_type_format (content_type); camel_content_type_unref (content_type); ba = camel_stream_mem_get_byte_array ((CamelStreamMem *) ostream); opart = camel_mime_part_new (); camel_mime_part_set_content (opart, (gchar *) ba->data, ba->len, type); g_free (type); len = part_id->len; g_string_append (part_id, ".inlinepgp_signed"); g_warn_if_fail (e_mail_parser_parse_part ( parser, opart, part_id, cancellable, &work_queue)); head = g_queue_peek_head_link (&work_queue); for (link = head; link != NULL; link = g_list_next (link)) { EMailPart *mail_part = link->data; e_mail_part_update_validity ( mail_part, valid, E_MAIL_PART_VALIDITY_SIGNED | E_MAIL_PART_VALIDITY_PGP); } e_queue_transfer (&work_queue, out_mail_parts); g_string_truncate (part_id, len); /* Add a widget with details about the encryption, but only when * the encrypted isn't itself secured, in that case it has created * the button itself */ if (!e_mail_part_is_secured (opart)) { EMailPart *mail_part; g_string_append (part_id, ".inlinepgp_signed.button"); e_mail_parser_parse_part_as ( parser, part, part_id, "application/vnd.evolution.secure-button", cancellable, &work_queue); mail_part = g_queue_peek_head (&work_queue); if (mail_part != NULL) e_mail_part_update_validity ( mail_part, valid, E_MAIL_PART_VALIDITY_SIGNED | E_MAIL_PART_VALIDITY_PGP); e_queue_transfer (&work_queue, out_mail_parts); g_string_truncate (part_id, len); } /* Clean Up */ camel_cipher_validity_free (valid); g_object_unref (opart); g_object_unref (ostream); g_object_unref (cipher); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-347'], 'message': 'eds-I#3 - [GPG] Mails that are not encrypted look encrypted Related to https://gitlab.gnome.org/GNOME/evolution-data-server/issues/3'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: e_mail_formatter_format_security_header (EMailFormatter *formatter, EMailFormatterContext *context, GString *buffer, EMailPart *part, guint32 flags) { const gchar* part_id; gchar* part_id_prefix; GString* tmp; GQueue queue = G_QUEUE_INIT; GList *head, *link; g_return_if_fail (E_IS_MAIL_PART_HEADERS (part)); /* Get prefix of this PURI */ part_id = e_mail_part_get_id (part); part_id_prefix = g_strndup (part_id, g_strrstr (part_id, ".") - part_id); /* Add encryption/signature header */ tmp = g_string_new (""); e_mail_part_list_queue_parts (context->part_list, NULL, &queue); head = g_queue_peek_head_link (&queue); /* Find first secured part. */ for (link = head; link != NULL; link = g_list_next(link)) { EMailPart *mail_part = link->data; if (!e_mail_part_has_validity (mail_part)) continue; if (!e_mail_part_id_has_prefix (mail_part, part_id_prefix)) continue; if (e_mail_part_get_validity (mail_part, E_MAIL_PART_VALIDITY_PGP | E_MAIL_PART_VALIDITY_SIGNED)) { g_string_append (tmp, _("GPG signed")); } if (e_mail_part_get_validity (mail_part, E_MAIL_PART_VALIDITY_PGP | E_MAIL_PART_VALIDITY_ENCRYPTED)) { if (tmp->len > 0) g_string_append (tmp, ", "); g_string_append (tmp, _("GPG encrypted")); } if (e_mail_part_get_validity (mail_part, E_MAIL_PART_VALIDITY_SMIME | E_MAIL_PART_VALIDITY_SIGNED)) { if (tmp->len > 0) g_string_append (tmp, ", "); g_string_append (tmp, _("S/MIME signed")); } if (e_mail_part_get_validity (mail_part, E_MAIL_PART_VALIDITY_SMIME | E_MAIL_PART_VALIDITY_ENCRYPTED)) { if (tmp->len > 0) g_string_append (tmp, ", "); g_string_append (tmp, _("S/MIME encrypted")); } break; } if (tmp->len > 0) { e_mail_formatter_format_header ( formatter, buffer, _("Security"), tmp->str, flags, "UTF-8"); } while (!g_queue_is_empty (&queue)) g_object_unref (g_queue_pop_head (&queue)); g_string_free (tmp, TRUE); g_free (part_id_prefix); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-347'], 'message': 'eds-I#3 - [GPG] Mails that are not encrypted look encrypted Related to https://gitlab.gnome.org/GNOME/evolution-data-server/issues/3'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: empe_mp_signed_parse (EMailParserExtension *extension, EMailParser *parser, CamelMimePart *part, GString *part_id, GCancellable *cancellable, GQueue *out_mail_parts) { CamelMimePart *cpart = NULL; CamelMultipart *multipart; CamelCipherContext *cipher = NULL; CamelContentType *content_type; CamelSession *session; guint32 validity_type; CamelCipherValidity *valid; const gchar *protocol = NULL; GError *local_error = NULL; gint i, nparts, len; gboolean secured; /* If the part is application/pgp-signature sub-part then skip it. */ if (!CAMEL_IS_MULTIPART (part)) { content_type = camel_mime_part_get_content_type (part); if (camel_content_type_is ( content_type, "application", "pgp-signature")) { return TRUE; } } multipart = (CamelMultipart *) camel_medium_get_content ((CamelMedium *) part); if (CAMEL_IS_MULTIPART_SIGNED (multipart)) { cpart = camel_multipart_get_part ( multipart, CAMEL_MULTIPART_SIGNED_CONTENT); } if (cpart == NULL) { e_mail_parser_error ( parser, out_mail_parts, _("Could not parse MIME message. " "Displaying as source.")); e_mail_parser_parse_part_as ( parser, part, part_id, "application/vnd.evolution.source", cancellable, out_mail_parts); return TRUE; } content_type = camel_data_wrapper_get_mime_type_field ( CAMEL_DATA_WRAPPER (multipart)); if (content_type != NULL) protocol = camel_content_type_param (content_type, "protocol"); session = e_mail_parser_get_session (parser); /* FIXME: Should be done via a plugin interface */ /* FIXME: duplicated in em-format-html-display.c */ if (protocol != NULL) { #ifdef ENABLE_SMIME if (g_ascii_strcasecmp ("application/x-pkcs7-signature", protocol) == 0 || g_ascii_strcasecmp ("application/pkcs7-signature", protocol) == 0) { cipher = camel_smime_context_new (session); validity_type = E_MAIL_PART_VALIDITY_SMIME; } else { #endif if (g_ascii_strcasecmp ("application/pgp-signature", protocol) == 0) { cipher = camel_gpg_context_new (session); validity_type = E_MAIL_PART_VALIDITY_PGP; } #ifdef ENABLE_SMIME } #endif } if (cipher == NULL) { e_mail_parser_error ( parser, out_mail_parts, _("Unsupported signature format")); e_mail_parser_parse_part_as ( parser, part, part_id, "multipart/mixed", cancellable, out_mail_parts); return TRUE; } valid = camel_cipher_context_verify_sync ( cipher, part, cancellable, &local_error); if (local_error != NULL) { e_mail_parser_error ( parser, out_mail_parts, _("Error verifying signature: %s"), local_error->message); e_mail_parser_parse_part_as ( parser, part, part_id, "multipart/mixed", cancellable, out_mail_parts); g_object_unref (cipher); g_error_free (local_error); return TRUE; } nparts = camel_multipart_get_number (multipart); secured = FALSE; len = part_id->len; for (i = 0; i < nparts; i++) { GQueue work_queue = G_QUEUE_INIT; GList *head, *link; CamelMimePart *subpart; subpart = camel_multipart_get_part (multipart, i); g_string_append_printf (part_id, ".signed.%d", i); g_warn_if_fail (e_mail_parser_parse_part ( parser, subpart, part_id, cancellable, &work_queue)); g_string_truncate (part_id, len); if (!secured) secured = e_mail_part_is_secured (subpart); head = g_queue_peek_head_link (&work_queue); for (link = head; link != NULL; link = g_list_next (link)) { EMailPart *mail_part = link->data; e_mail_part_update_validity ( mail_part, valid, validity_type | E_MAIL_PART_VALIDITY_SIGNED); } e_queue_transfer (&work_queue, out_mail_parts); } /* Add a widget with details about the encryption, but only when * the encrypted isn't itself secured, in that case it has created * the button itself. */ if (!secured) { GQueue work_queue = G_QUEUE_INIT; EMailPart *mail_part; g_string_append (part_id, ".signed.button"); e_mail_parser_parse_part_as ( parser, part, part_id, "application/vnd.evolution.secure-button", cancellable, &work_queue); mail_part = g_queue_peek_head (&work_queue); if (mail_part != NULL) e_mail_part_update_validity ( mail_part, valid, validity_type | E_MAIL_PART_VALIDITY_SIGNED); e_queue_transfer (&work_queue, out_mail_parts); g_string_truncate (part_id, len); } camel_cipher_validity_free (valid); g_object_unref (cipher); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-347'], 'message': 'eds-I#3 - [GPG] Mails that are not encrypted look encrypted Related to https://gitlab.gnome.org/GNOME/evolution-data-server/issues/3'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mail_parser_run (EMailParser *parser, EMailPartList *part_list, GCancellable *cancellable) { EMailExtensionRegistry *reg; CamelMimeMessage *message; EMailPart *mail_part; GQueue *parsers; GQueue mail_part_queue = G_QUEUE_INIT; GList *iter; GString *part_id; if (cancellable) g_object_ref (cancellable); else cancellable = g_cancellable_new (); g_mutex_lock (&parser->priv->mutex); g_hash_table_insert (parser->priv->ongoing_part_lists, cancellable, part_list); g_mutex_unlock (&parser->priv->mutex); message = e_mail_part_list_get_message (part_list); reg = e_mail_parser_get_extension_registry (parser); parsers = e_mail_extension_registry_get_for_mime_type ( reg, "application/vnd.evolution.message"); if (parsers == NULL) parsers = e_mail_extension_registry_get_for_mime_type ( reg, "message/*"); /* No parsers means the internal Evolution parser * extensions were not loaded. Something is terribly wrong! */ g_return_if_fail (parsers != NULL); part_id = g_string_new (".message"); mail_part = e_mail_part_new (CAMEL_MIME_PART (message), ".message"); e_mail_part_list_add_part (part_list, mail_part); g_object_unref (mail_part); for (iter = parsers->head; iter; iter = iter->next) { EMailParserExtension *extension; gboolean message_handled; if (g_cancellable_is_cancelled (cancellable)) break; extension = iter->data; if (!extension) continue; message_handled = e_mail_parser_extension_parse ( extension, parser, CAMEL_MIME_PART (message), part_id, cancellable, &mail_part_queue); if (message_handled) break; } while (!g_queue_is_empty (&mail_part_queue)) { mail_part = g_queue_pop_head (&mail_part_queue); e_mail_part_list_add_part (part_list, mail_part); g_object_unref (mail_part); } g_mutex_lock (&parser->priv->mutex); g_hash_table_remove (parser->priv->ongoing_part_lists, cancellable); g_mutex_unlock (&parser->priv->mutex); g_clear_object (&cancellable); g_string_free (part_id, TRUE); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-347'], 'message': 'I#120 - Show security bar above message headers Closes https://gitlab.gnome.org/GNOME/evolution/issues/120'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: e_ews_autodiscover_ws_url_sync (ESource *source, CamelEwsSettings *settings, const gchar *email_address, const gchar *password, GCancellable *cancellable, GError **error) { EAsyncClosure *closure; GAsyncResult *result; gboolean success; g_return_val_if_fail (CAMEL_IS_EWS_SETTINGS (settings), FALSE); g_return_val_if_fail (email_address != NULL, FALSE); g_return_val_if_fail (password != NULL, FALSE); closure = e_async_closure_new (); e_ews_autodiscover_ws_url (source, settings, email_address, password, cancellable, e_async_closure_callback, closure); result = e_async_closure_wait (closure); success = e_ews_autodiscover_ws_url_finish (settings, result, error); e_async_closure_free (closure); return success; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too. Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mail_config_ews_autodiscover_run_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) { AsyncContext *async_context = task_data; GError *local_error = NULL; gboolean success = FALSE; if (!g_cancellable_set_error_if_cancelled (cancellable, &local_error) && !local_error) { gboolean without_password; without_password = e_ews_connection_utils_get_without_password (async_context->ews_settings); if (without_password) { success = e_ews_autodiscover_ws_url_sync (async_context->source, async_context->ews_settings, async_context->email_address, "", cancellable, &local_error); } if (!without_password || g_error_matches (local_error, SOUP_HTTP_ERROR, SOUP_STATUS_UNAUTHORIZED)) { EShell *shell; e_ews_connection_utils_force_off_ntlm_auth_check (); g_clear_error (&local_error); shell = e_shell_get_default (); success = e_credentials_prompter_loop_prompt_sync (e_shell_get_credentials_prompter (shell), async_context->source, E_CREDENTIALS_PROMPTER_PROMPT_FLAG_ALLOW_SOURCE_SAVE, mail_config_ews_autodiscover_sync, async_context, cancellable, &local_error); } } if (local_error != NULL) { g_task_return_error (task, local_error); } else { g_task_return_boolean (task, success); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too. Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ews_backend_constructed (GObject *object) { EBackend *backend; ESource *source; ESourceAuthentication *auth_extension; const gchar *extension_name; gchar *host = NULL; guint16 port = 0; /* Chain up to parent's constructed() method. */ G_OBJECT_CLASS (e_ews_backend_parent_class)->constructed (object); backend = E_BACKEND (object); source = e_backend_get_source (backend); /* XXX Wondering if we ought to delay this until after folders * are initially populated, just to remove the possibility * of weird races with clients trying to create folders. */ e_server_side_source_set_remote_creatable ( E_SERVER_SIDE_SOURCE (source), TRUE); /* Setup the Authentication extension so * Camel can determine host reachability. */ extension_name = E_SOURCE_EXTENSION_AUTHENTICATION; auth_extension = e_source_get_extension (source, extension_name); if (e_backend_get_destination_address (backend, &host, &port)) { e_source_authentication_set_host (auth_extension, host); e_source_authentication_set_port (auth_extension, port); } g_free (host); /* Reset the connectable, it steals data from Authentication extension, where is written incorrect address */ e_backend_set_connectable (backend, NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too. Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ews_backend_authenticate_sync (EBackend *backend, const ENamedParameters *credentials, gchar **out_certificate_pem, GTlsCertificateFlags *out_certificate_errors, GCancellable *cancellable, GError **error) { EEwsBackend *ews_backend; EEwsConnection *connection; CamelEwsSettings *ews_settings; ESourceAuthenticationResult result = E_SOURCE_AUTHENTICATION_ERROR; g_return_val_if_fail (E_IS_EWS_BACKEND (backend), E_SOURCE_AUTHENTICATION_ERROR); ews_backend = E_EWS_BACKEND (backend); ews_settings = ews_backend_get_settings (ews_backend); g_return_val_if_fail (ews_settings != NULL, E_SOURCE_AUTHENTICATION_ERROR); g_mutex_lock (&ews_backend->priv->connection_lock); g_clear_object (&ews_backend->priv->connection); e_named_parameters_free (ews_backend->priv->credentials); ews_backend->priv->credentials = e_named_parameters_new_clone (credentials); g_mutex_unlock (&ews_backend->priv->connection_lock); connection = e_ews_backend_ref_connection_sync (ews_backend, &result, cancellable, error); g_clear_object (&connection); if (result == E_SOURCE_AUTHENTICATION_ACCEPTED) { e_collection_backend_authenticate_children (E_COLLECTION_BACKEND (backend), credentials); e_ews_backend_sync_folders (ews_backend, NULL, ews_backend_folders_synced_cb, NULL); } else if (e_ews_connection_utils_get_without_password (ews_settings) && result == E_SOURCE_AUTHENTICATION_REJECTED && !e_named_parameters_exists (credentials, E_SOURCE_CREDENTIAL_PASSWORD)) { e_ews_connection_utils_force_off_ntlm_auth_check (); result = E_SOURCE_AUTHENTICATION_REQUIRED; } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too. Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: e_ews_backend_ref_connection_sync (EEwsBackend *backend, ESourceAuthenticationResult *result, GCancellable *cancellable, GError **error) { EEwsConnection *connection = NULL; ESourceAuthenticationResult local_result; CamelEwsSettings *settings; gchar *hosturl; gboolean success; g_return_val_if_fail (E_IS_EWS_BACKEND (backend), NULL); g_mutex_lock (&backend->priv->connection_lock); if (backend->priv->connection != NULL) connection = g_object_ref (backend->priv->connection); g_mutex_unlock (&backend->priv->connection_lock); /* If we already have an authenticated * connection object, just return that. */ if (connection != NULL || !backend->priv->credentials) return connection; settings = ews_backend_get_settings (backend); hosturl = camel_ews_settings_dup_hosturl (settings); connection = e_ews_connection_new_full (e_backend_get_source (E_BACKEND (backend)), hosturl, settings, FALSE); g_free (hosturl); e_binding_bind_property ( backend, "proxy-resolver", connection, "proxy-resolver", G_BINDING_SYNC_CREATE); local_result = e_ews_connection_try_credentials_sync (connection, backend->priv->credentials, cancellable, error); if (result) *result = local_result; success = local_result == E_SOURCE_AUTHENTICATION_ACCEPTED; if (success) { g_mutex_lock (&backend->priv->connection_lock); if (backend->priv->connection != NULL) g_object_unref (backend->priv->connection); backend->priv->connection = g_object_ref (connection); g_mutex_unlock (&backend->priv->connection_lock); } else { g_object_unref (connection); connection = NULL; } return connection; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too. Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: e_ews_backend_sync_folders_sync (EEwsBackend *backend, GCancellable *cancellable, GError **error) { EEwsConnection *connection; GSList *folders_created = NULL; GSList *folders_updated = NULL; GSList *folders_deleted = NULL; gboolean includes_last_folder = FALSE; gchar *old_sync_state, *new_sync_state = NULL; gboolean success; GError *local_error = NULL; g_return_val_if_fail (E_IS_EWS_BACKEND (backend), FALSE); if (!e_backend_get_online (E_BACKEND (backend))) { SyncFoldersClosure *closure; /* This takes ownership of the folder lists. */ closure = g_slice_new0 (SyncFoldersClosure); closure->backend = g_object_ref (backend); /* Process the results from an idle callback. */ g_idle_add_full ( G_PRIORITY_DEFAULT_IDLE, ews_backend_sync_folders_idle_cb, closure, (GDestroyNotify) sync_folders_closure_free); return TRUE; } connection = e_ews_backend_ref_connection_sync (backend, NULL, cancellable, error); if (connection == NULL) { backend->priv->need_update_folders = TRUE; return FALSE; } backend->priv->need_update_folders = FALSE; g_mutex_lock (&backend->priv->sync_state_lock); old_sync_state = g_strdup (backend->priv->sync_state); g_mutex_unlock (&backend->priv->sync_state_lock); success = e_ews_connection_sync_folder_hierarchy_sync (connection, EWS_PRIORITY_MEDIUM, old_sync_state, &new_sync_state, &includes_last_folder, &folders_created, &folders_updated, &folders_deleted, cancellable, &local_error); if (old_sync_state && g_error_matches (local_error, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_INVALIDSYNCSTATEDATA)) { g_clear_error (&local_error); g_mutex_lock (&backend->priv->sync_state_lock); g_free (backend->priv->sync_state); backend->priv->sync_state = NULL; g_mutex_unlock (&backend->priv->sync_state_lock); ews_backend_forget_all_sources (backend); success = e_ews_connection_sync_folder_hierarchy_sync (connection, EWS_PRIORITY_MEDIUM, NULL, &new_sync_state, &includes_last_folder, &folders_created, &folders_updated, &folders_deleted, cancellable, &local_error); } else if (local_error) { g_propagate_error (error, local_error); local_error = NULL; } g_free (old_sync_state); old_sync_state = NULL; if (success) { SyncFoldersClosure *closure; /* This takes ownership of the folder lists. */ closure = g_slice_new0 (SyncFoldersClosure); closure->backend = g_object_ref (backend); closure->folders_created = folders_created; closure->folders_deleted = folders_deleted; closure->folders_updated = folders_updated; /* Process the results from an idle callback. */ g_idle_add_full ( G_PRIORITY_DEFAULT_IDLE, ews_backend_sync_folders_idle_cb, closure, (GDestroyNotify) sync_folders_closure_free); g_mutex_lock (&backend->priv->sync_state_lock); g_free (backend->priv->sync_state); backend->priv->sync_state = g_strdup (new_sync_state); g_mutex_unlock (&backend->priv->sync_state_lock); } else { /* Make sure we're not leaking anything. */ g_warn_if_fail (folders_created == NULL); g_warn_if_fail (folders_updated == NULL); g_warn_if_fail (folders_deleted == NULL); backend->priv->need_update_folders = TRUE; } g_free (new_sync_state); g_object_unref (connection); return success; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too. Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s>