instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static __inline__ int scm_check_creds(struct ucred *creds) { const struct cred *cred = current_cred(); kuid_t uid = make_kuid(cred->user_ns, creds->uid); kgid_t gid = make_kgid(cred->user_ns, creds->gid); if (!uid_valid(uid) || !gid_valid(gid)) return -EINVAL; if ((creds->pid == task_tgid_vnr(current) || ns_capable(current->nsproxy->pid_ns->user_ns, CAP_SYS_ADMIN)) && ((uid_eq(uid, cred->uid) || uid_eq(uid, cred->euid) || uid_eq(uid, cred->suid)) || nsown_capable(CAP_SETUID)) && ((gid_eq(gid, cred->gid) || gid_eq(gid, cred->egid) || gid_eq(gid, cred->sgid)) || nsown_capable(CAP_SETGID))) { return 0; } return -EPERM; } Commit Message: net: Check the correct namespace when spoofing pid over SCM_RIGHTS This is a security bug. The follow-up will fix nsproxy to discourage this type of issue from happening again. Cc: [email protected] Signed-off-by: Andy Lutomirski <[email protected]> Reviewed-by: "Eric W. Biederman" <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264
static __inline__ int scm_check_creds(struct ucred *creds) { const struct cred *cred = current_cred(); kuid_t uid = make_kuid(cred->user_ns, creds->uid); kgid_t gid = make_kgid(cred->user_ns, creds->gid); if (!uid_valid(uid) || !gid_valid(gid)) return -EINVAL; if ((creds->pid == task_tgid_vnr(current) || ns_capable(task_active_pid_ns(current)->user_ns, CAP_SYS_ADMIN)) && ((uid_eq(uid, cred->uid) || uid_eq(uid, cred->euid) || uid_eq(uid, cred->suid)) || nsown_capable(CAP_SETUID)) && ((gid_eq(gid, cred->gid) || gid_eq(gid, cred->egid) || gid_eq(gid, cred->sgid)) || nsown_capable(CAP_SETGID))) { return 0; } return -EPERM; }
165,991
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long Segment::CreateInstance( IMkvReader* pReader, long long pos, Segment*& pSegment) { assert(pReader); assert(pos >= 0); pSegment = NULL; long long total, available; const long status = pReader->Length(&total, &available); if (status < 0) //error return status; if (available < 0) return -1; if ((total >= 0) && (available > total)) return -1; for (;;) { if ((total >= 0) && (pos >= total)) return E_FILE_FORMAT_INVALID; long len; long long result = GetUIntLength(pReader, pos, len); if (result) //error, or too few available bytes return result; if ((total >= 0) && ((pos + len) > total)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; const long long idpos = pos; const long long id = ReadUInt(pReader, pos, len); if (id < 0) //error return id; pos += len; //consume ID result = GetUIntLength(pReader, pos, len); if (result) //error, or too few available bytes return result; if ((total >= 0) && ((pos + len) > total)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; long long size = ReadUInt(pReader, pos, len); if (size < 0) //error return size; pos += len; //consume length of size of element const long long unknown_size = (1LL << (7 * len)) - 1; if (id == 0x08538067) //Segment ID { if (size == unknown_size) size = -1; else if (total < 0) size = -1; else if ((pos + size) > total) size = -1; pSegment = new (std::nothrow) Segment( pReader, idpos, pos, size); if (pSegment == 0) return -1; //generic error return 0; //success } if (size == unknown_size) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + size) > total)) return E_FILE_FORMAT_INVALID; if ((pos + size) > available) return pos + size; pos += size; //consume payload } } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long Segment::CreateInstance( if (result < 0) // error return result; if (result > 0) // underflow (weird) return (pos + 1); if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; const long long idpos = pos; const long long id = ReadUInt(m_pReader, idpos, len); if (id < 0) // error return id; if (id == 0x0F43B675) // Cluster ID break; pos += len; // consume ID if ((pos + 1) > available) return (pos + 1); // Read Size result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return result; if (result > 0) // underflow (weird) return (pos + 1); if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) // error return size; pos += len; // consume length of size of element const long long element_size = size + pos - element_start; // Pos now points to start of payload if ((segment_stop >= 0) && ((pos + size) > segment_stop)) return E_FILE_FORMAT_INVALID; // We read EBML elements either in total or nothing at all. if ((pos + size) > available) return pos + size; if (id == 0x0549A966) { // Segment Info ID if (m_pInfo) return E_FILE_FORMAT_INVALID; m_pInfo = new (std::nothrow) SegmentInfo(this, pos, size, element_start, element_size); if (m_pInfo == NULL) return -1; const long status = m_pInfo->Parse(); if (status) return status; } else if (id == 0x0654AE6B) { // Tracks ID if (m_pTracks) return E_FILE_FORMAT_INVALID; m_pTracks = new (std::nothrow) Tracks(this, pos, size, element_start, element_size); if (m_pTracks == NULL) return -1; const long status = m_pTracks->Parse();
174,259
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ExtensionUninstaller::Run() { const extensions::Extension* extension = extensions::ExtensionSystem::Get(profile_)->extension_service()-> GetInstalledExtension(app_id_); if (!extension) { CleanUp(); return; } controller_->OnShowChildDialog(); dialog_.reset(extensions::ExtensionUninstallDialog::Create( profile_, controller_->GetAppListWindow(), this)); dialog_->ConfirmUninstall(extension, extensions::UNINSTALL_REASON_USER_INITIATED); } Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry This CL adds GetInstalledExtension() method to ExtensionRegistry and uses it instead of deprecated ExtensionService::GetInstalledExtension() in chrome/browser/ui/app_list/. Part of removing the deprecated GetInstalledExtension() call from the ExtensionService. BUG=489687 Review URL: https://codereview.chromium.org/1130353010 Cr-Commit-Position: refs/heads/master@{#333036} CWE ID:
void ExtensionUninstaller::Run() { const extensions::Extension* extension = extensions::ExtensionRegistry::Get(profile_)->GetInstalledExtension( app_id_); if (!extension) { CleanUp(); return; } controller_->OnShowChildDialog(); dialog_.reset(extensions::ExtensionUninstallDialog::Create( profile_, controller_->GetAppListWindow(), this)); dialog_->ConfirmUninstall(extension, extensions::UNINSTALL_REASON_USER_INITIATED); }
171,724
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: cib_remote_dispatch(gpointer user_data) { cib_t *cib = user_data; cib_remote_opaque_t *private = cib->variant_opaque; xmlNode *msg = NULL; const char *type = NULL; crm_info("Message on callback channel"); msg = crm_recv_remote_msg(private->callback.session, private->callback.encrypted); type = crm_element_value(msg, F_TYPE); crm_trace("Activating %s callbacks...", type); if (safe_str_eq(type, T_CIB)) { cib_native_callback(cib, msg, 0, 0); } else if (safe_str_eq(type, T_CIB_NOTIFY)) { g_list_foreach(cib->notify_list, cib_native_notify, msg); } else { crm_err("Unknown message type: %s", type); } if (msg != NULL) { free_xml(msg); return 0; } return -1; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
cib_remote_dispatch(gpointer user_data) cib_remote_command_dispatch(gpointer user_data) { int disconnected = 0; cib_t *cib = user_data; cib_remote_opaque_t *private = cib->variant_opaque; crm_recv_remote_msg(private->command.session, &private->command.recv_buf, private->command.encrypted, -1, &disconnected); free(private->command.recv_buf); private->command.recv_buf = NULL; crm_err("received late reply for remote cib connection, discarding"); if (disconnected) { return -1; } return 0; } int cib_remote_callback_dispatch(gpointer user_data) { cib_t *cib = user_data; cib_remote_opaque_t *private = cib->variant_opaque; xmlNode *msg = NULL; int disconnected = 0; crm_info("Message on callback channel"); crm_recv_remote_msg(private->callback.session, &private->callback.recv_buf, private->callback.encrypted, -1, &disconnected); msg = crm_parse_remote_buffer(&private->callback.recv_buf); while (msg) { const char *type = crm_element_value(msg, F_TYPE); crm_trace("Activating %s callbacks...", type); if (safe_str_eq(type, T_CIB)) { cib_native_callback(cib, msg, 0, 0); } else if (safe_str_eq(type, T_CIB_NOTIFY)) { g_list_foreach(cib->notify_list, cib_native_notify, msg); } else { crm_err("Unknown message type: %s", type); } free_xml(msg); msg = crm_parse_remote_buffer(&private->callback.recv_buf); } if (disconnected) { return -1; } return 0; }
166,151
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport size_t GetQuantumExtent(const Image *image, const QuantumInfo *quantum_info,const QuantumType quantum_type) { size_t extent, packet_size; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); packet_size=1; switch (quantum_type) { case GrayAlphaQuantum: packet_size=2; break; case IndexAlphaQuantum: packet_size=2; break; case RGBQuantum: packet_size=3; break; case BGRQuantum: packet_size=3; break; case RGBAQuantum: packet_size=4; break; case RGBOQuantum: packet_size=4; break; case BGRAQuantum: packet_size=4; break; case CMYKQuantum: packet_size=4; break; case CMYKAQuantum: packet_size=5; break; default: break; } extent=MagickMax(image->columns,image->rows); if (quantum_info->pack == MagickFalse) return((size_t) (packet_size*extent*((quantum_info->depth+7)/8))); return((size_t) ((packet_size*extent*quantum_info->depth+7)/8)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/126 CWE ID: CWE-125
MagickExport size_t GetQuantumExtent(const Image *image, const QuantumInfo *quantum_info,const QuantumType quantum_type) { size_t extent, packet_size; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); packet_size=1; switch (quantum_type) { case GrayAlphaQuantum: packet_size=2; break; case IndexAlphaQuantum: packet_size=2; break; case RGBQuantum: packet_size=3; break; case BGRQuantum: packet_size=3; break; case RGBAQuantum: packet_size=4; break; case RGBOQuantum: packet_size=4; break; case BGRAQuantum: packet_size=4; break; case CMYKQuantum: packet_size=4; break; case CMYKAQuantum: packet_size=5; break; case CbYCrAQuantum: packet_size=4; break; case CbYCrQuantum: packet_size=3; break; case CbYCrYQuantum: packet_size=4; break; default: break; } extent=MagickMax(image->columns,image->rows); if (quantum_info->pack == MagickFalse) return((size_t) (packet_size*extent*((quantum_info->depth+7)/8))); return((size_t) ((packet_size*extent*quantum_info->depth+7)/8)); }
168,794
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static unsigned short get_ushort(const unsigned char *data) { unsigned short val = *(const unsigned short *)data; #ifdef OPJ_BIG_ENDIAN val = ((val & 0xffU) << 8) | (val >> 8); #endif return val; } Commit Message: tgatoimage(): avoid excessive memory allocation attempt, and fixes unaligned load (#995) CWE ID: CWE-787
static unsigned short get_ushort(const unsigned char *data) /* Returns a ushort from a little-endian serialized value */ static unsigned short get_tga_ushort(const unsigned char *data) { return data[0] | (data[1] << 8); }
167,780
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeClientImpl::Focus() { if (web_view_->Client()) web_view_->Client()->DidFocus(); } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID:
void ChromeClientImpl::Focus() { void ChromeClientImpl::Focus(LocalFrame* calling_frame) { if (web_view_->Client()) { web_view_->Client()->DidFocus( calling_frame ? WebLocalFrameImpl::FromFrame(calling_frame) : nullptr); } }
172,724
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ftp_loop_internal (struct url *u, struct fileinfo *f, ccon *con, char **local_file, bool force_full_retrieve) { int count, orig_lp; wgint restval, len = 0, qtyread = 0; const char *tmrate = NULL; uerr_t err; struct_stat st; /* Declare WARC variables. */ bool warc_enabled = (opt.warc_filename != NULL); FILE *warc_tmp = NULL; ip_address *warc_ip = NULL; wgint last_expected_bytes = 0; /* Get the target, and set the name for the message accordingly. */ if ((f == NULL) && (con->target)) { /* Explicit file (like ".listing"). */ locf = con->target; } else { { /* URL-derived file. Consider "-O file" name. */ xfree (con->target); con->target = url_file_name (u, NULL); if (!opt.output_document) locf = con->target; else } /* If the output_document was given, then this check was already done and the file didn't exist. Hence the !opt.output_document */ /* If we receive .listing file it is necessary to determine system type of the ftp server even if opn.noclobber is given. Thus we must ignore opt.noclobber in order to establish connection with the server and get system type. */ if (opt.noclobber && !opt.output_document && file_exists_p (con->target) && !((con->cmd & DO_LIST) && !(con->cmd & DO_RETR))) { logprintf (LOG_VERBOSE, _("File %s already there; not retrieving.\n"), quote (con->target)); /* If the file is there, we suppose it's retrieved OK. */ return RETROK; } /* Remove it if it's a link. */ remove_link (con->target); count = 0; if (con->st & ON_YOUR_OWN) con->st = ON_YOUR_OWN; orig_lp = con->cmd & LEAVE_PENDING ? 1 : 0; /* THE loop. */ do { /* Increment the pass counter. */ ++count; sleep_between_retrievals (count); if (con->st & ON_YOUR_OWN) { con->cmd = 0; con->cmd |= (DO_RETR | LEAVE_PENDING); if (con->csock != -1) con->cmd &= ~ (DO_LOGIN | DO_CWD); else con->cmd |= (DO_LOGIN | DO_CWD); } else /* not on your own */ { if (con->csock != -1) con->cmd &= ~DO_LOGIN; else con->cmd |= DO_LOGIN; if (con->st & DONE_CWD) con->cmd &= ~DO_CWD; else con->cmd |= DO_CWD; } /* For file RETR requests, we can write a WARC record. We record the file contents to a temporary file. */ if (warc_enabled && (con->cmd & DO_RETR) && warc_tmp == NULL) { warc_tmp = warc_tempfile (); if (warc_tmp == NULL) return WARC_TMP_FOPENERR; if (!con->proxy && con->csock != -1) { warc_ip = (ip_address *) alloca (sizeof (ip_address)); socket_ip_address (con->csock, warc_ip, ENDPOINT_PEER); } } /* Decide whether or not to restart. */ if (con->cmd & DO_LIST) restval = 0; else if (force_full_retrieve) restval = 0; else if (opt.start_pos >= 0) restval = opt.start_pos; else if (opt.always_rest && stat (locf, &st) == 0 && S_ISREG (st.st_mode)) /* When -c is used, continue from on-disk size. (Can't use hstat.len even if count>1 because we don't want a failed first attempt to clobber existing data.) */ restval = st.st_size; else if (count > 1) restval = qtyread; /* start where the previous run left off */ else restval = 0; /* Get the current time string. */ tms = datetime_str (time (NULL)); /* Print fetch message, if opt.verbose. */ if (opt.verbose) { char *hurl = url_string (u, URL_AUTH_HIDE_PASSWD); char tmp[256]; strcpy (tmp, " "); if (count > 1) sprintf (tmp, _("(try:%2d)"), count); logprintf (LOG_VERBOSE, "--%s-- %s\n %s => %s\n", tms, hurl, tmp, quote (locf)); #ifdef WINDOWS ws_changetitle (hurl); #endif xfree (hurl); } /* Send getftp the proper length, if fileinfo was provided. */ if (f && f->type != FT_SYMLINK) len = f->size; else len = 0; /* If we are working on a WARC record, getftp should also write to the warc_tmp file. */ err = getftp (u, len, &qtyread, restval, con, count, &last_expected_bytes, warc_tmp); if (con->csock == -1) con->st &= ~DONE_CWD; con->st |= DONE_CWD; switch (err) { case HOSTERR: case CONIMPOSSIBLE: case FWRITEERR: case FOPENERR: case FTPNSFOD: case FTPLOGINC: case FTPNOPASV: case FTPNOAUTH: case FTPNOPBSZ: case FTPNOPROT: case UNLINKERR: case WARC_TMP_FWRITEERR: case CONSSLERR: case CONTNOTSUPPORTED: #ifdef HAVE_SSL if (err == FTPNOAUTH) logputs (LOG_NOTQUIET, "Server does not support AUTH TLS.\n"); if (opt.ftps_implicit) logputs (LOG_NOTQUIET, "Server does not like implicit FTPS connections.\n"); #endif /* Fatal errors, give up. */ if (warc_tmp != NULL) fclose (warc_tmp); return err; case CONSOCKERR: case CONERROR: case FTPSRVERR: case FTPRERR: case WRITEFAILED: case FTPUNKNOWNTYPE: case FTPSYSERR: case FTPPORTERR: case FTPLOGREFUSED: case FTPINVPASV: case FOPEN_EXCL_ERR: printwhat (count, opt.ntry); /* non-fatal errors */ if (err == FOPEN_EXCL_ERR) { /* Re-determine the file name. */ xfree (con->target); con->target = url_file_name (u, NULL); locf = con->target; } continue; case FTPRETRINT: /* If the control connection was closed, the retrieval will be considered OK if f->size == len. */ if (!f || qtyread != f->size) { printwhat (count, opt.ntry); continue; } break; case RETRFINISHED: /* Great! */ break; default: /* Not as great. */ abort (); } tms = datetime_str (time (NULL)); if (!opt.spider) tmrate = retr_rate (qtyread - restval, con->dltime); /* If we get out of the switch above without continue'ing, we've successfully downloaded a file. Remember this fact. */ downloaded_file (FILE_DOWNLOADED_NORMALLY, locf); if (con->st & ON_YOUR_OWN) { fd_close (con->csock); con->csock = -1; } if (!opt.spider) { bool write_to_stdout = (opt.output_document && HYPHENP (opt.output_document)); logprintf (LOG_VERBOSE, write_to_stdout ? _("%s (%s) - written to stdout %s[%s]\n\n") : _("%s (%s) - %s saved [%s]\n\n"), tms, tmrate, write_to_stdout ? "" : quote (locf), number_to_static_string (qtyread)); } if (!opt.verbose && !opt.quiet) { /* Need to hide the password from the URL. The `if' is here so that we don't do the needless allocation every time. */ char *hurl = url_string (u, URL_AUTH_HIDE_PASSWD); logprintf (LOG_NONVERBOSE, "%s URL: %s [%s] -> \"%s\" [%d]\n", tms, hurl, number_to_static_string (qtyread), locf, count); xfree (hurl); } if (warc_enabled && (con->cmd & DO_RETR)) { /* Create and store a WARC resource record for the retrieved file. */ bool warc_res; warc_res = warc_write_resource_record (NULL, u->url, NULL, NULL, warc_ip, NULL, warc_tmp, -1); if (! warc_res) return WARC_ERR; /* warc_write_resource_record has also closed warc_tmp. */ warc_tmp = NULL; } if (con->cmd & DO_LIST) /* This is a directory listing file. */ { if (!opt.remove_listing) /* --dont-remove-listing was specified, so do count this towards the number of bytes and files downloaded. */ { total_downloaded_bytes += qtyread; numurls++; } /* Deletion of listing files is not controlled by --delete-after, but by the more specific option --dont-remove-listing, and the code to do this deletion is in another function. */ } else if (!opt.spider) /* This is not a directory listing file. */ { /* Unlike directory listing files, don't pretend normal files weren't downloaded if they're going to be deleted. People seeding proxies, for instance, may want to know how many bytes and files they've downloaded through it. */ total_downloaded_bytes += qtyread; numurls++; if (opt.delete_after && !input_file_url (opt.input_filename)) { DEBUGP (("\ Removing file due to --delete-after in ftp_loop_internal():\n")); logprintf (LOG_VERBOSE, _("Removing %s.\n"), locf); if (unlink (locf)) logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno)); } } /* Restore the original leave-pendingness. */ if (orig_lp) con->cmd |= LEAVE_PENDING; else con->cmd &= ~LEAVE_PENDING; if (local_file) *local_file = xstrdup (locf); if (warc_tmp != NULL) fclose (warc_tmp); return RETROK; } while (!opt.ntry || (count < opt.ntry)); if (con->csock != -1 && (con->st & ON_YOUR_OWN)) { fd_close (con->csock); con->csock = -1; } if (warc_tmp != NULL) fclose (warc_tmp); return TRYLIMEXC; } /* Return the directory listing in a reusable format. The directory /* Return the directory listing in a reusable format. The directory is specifed in u->dir. */ static uerr_t ftp_get_listing (struct url *u, ccon *con, struct fileinfo **f) { uerr_t err; char *uf; /* url file name */ con->st &= ~ON_YOUR_OWN; con->cmd |= (DO_LIST | LEAVE_PENDING); con->cmd &= ~DO_RETR; /* Find the listing file name. We do it by taking the file name of the URL and replacing the last component with the listing file name. */ uf = url_file_name (u, NULL); lf = file_merge (uf, LIST_FILENAME); xfree (uf); DEBUGP ((_("Using %s as listing tmp file.\n"), quote (lf))); con->target = xstrdup (lf); con->target = xstrdup (lf); xfree (lf); err = ftp_loop_internal (u, NULL, con, NULL, false); lf = xstrdup (con->target); xfree (con->target); con->target = old_target; { *f = ftp_parse_ls (lf, con->rs); if (opt.remove_listing) { if (unlink (lf)) logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno)); else logprintf (LOG_VERBOSE, _("Removed %s.\n"), quote (lf)); } } else *f = NULL; xfree (lf); con->cmd &= ~DO_LIST; return err; } return err; } Commit Message: CWE ID: CWE-254
ftp_loop_internal (struct url *u, struct fileinfo *f, ccon *con, char **local_file, ftp_loop_internal (struct url *u, struct url *original_url, struct fileinfo *f, ccon *con, char **local_file, bool force_full_retrieve) { int count, orig_lp; wgint restval, len = 0, qtyread = 0; const char *tmrate = NULL; uerr_t err; struct_stat st; /* Declare WARC variables. */ bool warc_enabled = (opt.warc_filename != NULL); FILE *warc_tmp = NULL; ip_address *warc_ip = NULL; wgint last_expected_bytes = 0; /* Get the target, and set the name for the message accordingly. */ if ((f == NULL) && (con->target)) { /* Explicit file (like ".listing"). */ locf = con->target; } else { { /* URL-derived file. Consider "-O file" name. */ xfree (con->target); con->target = url_file_name (opt.trustservernames || !original_url ? u : original_url, NULL); if (!opt.output_document) locf = con->target; else } /* If the output_document was given, then this check was already done and the file didn't exist. Hence the !opt.output_document */ /* If we receive .listing file it is necessary to determine system type of the ftp server even if opn.noclobber is given. Thus we must ignore opt.noclobber in order to establish connection with the server and get system type. */ if (opt.noclobber && !opt.output_document && file_exists_p (con->target) && !((con->cmd & DO_LIST) && !(con->cmd & DO_RETR))) { logprintf (LOG_VERBOSE, _("File %s already there; not retrieving.\n"), quote (con->target)); /* If the file is there, we suppose it's retrieved OK. */ return RETROK; } /* Remove it if it's a link. */ remove_link (con->target); count = 0; if (con->st & ON_YOUR_OWN) con->st = ON_YOUR_OWN; orig_lp = con->cmd & LEAVE_PENDING ? 1 : 0; /* THE loop. */ do { /* Increment the pass counter. */ ++count; sleep_between_retrievals (count); if (con->st & ON_YOUR_OWN) { con->cmd = 0; con->cmd |= (DO_RETR | LEAVE_PENDING); if (con->csock != -1) con->cmd &= ~ (DO_LOGIN | DO_CWD); else con->cmd |= (DO_LOGIN | DO_CWD); } else /* not on your own */ { if (con->csock != -1) con->cmd &= ~DO_LOGIN; else con->cmd |= DO_LOGIN; if (con->st & DONE_CWD) con->cmd &= ~DO_CWD; else con->cmd |= DO_CWD; } /* For file RETR requests, we can write a WARC record. We record the file contents to a temporary file. */ if (warc_enabled && (con->cmd & DO_RETR) && warc_tmp == NULL) { warc_tmp = warc_tempfile (); if (warc_tmp == NULL) return WARC_TMP_FOPENERR; if (!con->proxy && con->csock != -1) { warc_ip = (ip_address *) alloca (sizeof (ip_address)); socket_ip_address (con->csock, warc_ip, ENDPOINT_PEER); } } /* Decide whether or not to restart. */ if (con->cmd & DO_LIST) restval = 0; else if (force_full_retrieve) restval = 0; else if (opt.start_pos >= 0) restval = opt.start_pos; else if (opt.always_rest && stat (locf, &st) == 0 && S_ISREG (st.st_mode)) /* When -c is used, continue from on-disk size. (Can't use hstat.len even if count>1 because we don't want a failed first attempt to clobber existing data.) */ restval = st.st_size; else if (count > 1) restval = qtyread; /* start where the previous run left off */ else restval = 0; /* Get the current time string. */ tms = datetime_str (time (NULL)); /* Print fetch message, if opt.verbose. */ if (opt.verbose) { char *hurl = url_string (u, URL_AUTH_HIDE_PASSWD); char tmp[256]; strcpy (tmp, " "); if (count > 1) sprintf (tmp, _("(try:%2d)"), count); logprintf (LOG_VERBOSE, "--%s-- %s\n %s => %s\n", tms, hurl, tmp, quote (locf)); #ifdef WINDOWS ws_changetitle (hurl); #endif xfree (hurl); } /* Send getftp the proper length, if fileinfo was provided. */ if (f && f->type != FT_SYMLINK) len = f->size; else len = 0; /* If we are working on a WARC record, getftp should also write to the warc_tmp file. */ err = getftp (u, original_url, len, &qtyread, restval, con, count, &last_expected_bytes, warc_tmp); if (con->csock == -1) con->st &= ~DONE_CWD; con->st |= DONE_CWD; switch (err) { case HOSTERR: case CONIMPOSSIBLE: case FWRITEERR: case FOPENERR: case FTPNSFOD: case FTPLOGINC: case FTPNOPASV: case FTPNOAUTH: case FTPNOPBSZ: case FTPNOPROT: case UNLINKERR: case WARC_TMP_FWRITEERR: case CONSSLERR: case CONTNOTSUPPORTED: #ifdef HAVE_SSL if (err == FTPNOAUTH) logputs (LOG_NOTQUIET, "Server does not support AUTH TLS.\n"); if (opt.ftps_implicit) logputs (LOG_NOTQUIET, "Server does not like implicit FTPS connections.\n"); #endif /* Fatal errors, give up. */ if (warc_tmp != NULL) fclose (warc_tmp); return err; case CONSOCKERR: case CONERROR: case FTPSRVERR: case FTPRERR: case WRITEFAILED: case FTPUNKNOWNTYPE: case FTPSYSERR: case FTPPORTERR: case FTPLOGREFUSED: case FTPINVPASV: case FOPEN_EXCL_ERR: printwhat (count, opt.ntry); /* non-fatal errors */ if (err == FOPEN_EXCL_ERR) { /* Re-determine the file name. */ xfree (con->target); con->target = url_file_name (u, NULL); locf = con->target; } continue; case FTPRETRINT: /* If the control connection was closed, the retrieval will be considered OK if f->size == len. */ if (!f || qtyread != f->size) { printwhat (count, opt.ntry); continue; } break; case RETRFINISHED: /* Great! */ break; default: /* Not as great. */ abort (); } tms = datetime_str (time (NULL)); if (!opt.spider) tmrate = retr_rate (qtyread - restval, con->dltime); /* If we get out of the switch above without continue'ing, we've successfully downloaded a file. Remember this fact. */ downloaded_file (FILE_DOWNLOADED_NORMALLY, locf); if (con->st & ON_YOUR_OWN) { fd_close (con->csock); con->csock = -1; } if (!opt.spider) { bool write_to_stdout = (opt.output_document && HYPHENP (opt.output_document)); logprintf (LOG_VERBOSE, write_to_stdout ? _("%s (%s) - written to stdout %s[%s]\n\n") : _("%s (%s) - %s saved [%s]\n\n"), tms, tmrate, write_to_stdout ? "" : quote (locf), number_to_static_string (qtyread)); } if (!opt.verbose && !opt.quiet) { /* Need to hide the password from the URL. The `if' is here so that we don't do the needless allocation every time. */ char *hurl = url_string (u, URL_AUTH_HIDE_PASSWD); logprintf (LOG_NONVERBOSE, "%s URL: %s [%s] -> \"%s\" [%d]\n", tms, hurl, number_to_static_string (qtyread), locf, count); xfree (hurl); } if (warc_enabled && (con->cmd & DO_RETR)) { /* Create and store a WARC resource record for the retrieved file. */ bool warc_res; warc_res = warc_write_resource_record (NULL, u->url, NULL, NULL, warc_ip, NULL, warc_tmp, -1); if (! warc_res) return WARC_ERR; /* warc_write_resource_record has also closed warc_tmp. */ warc_tmp = NULL; } if (con->cmd & DO_LIST) /* This is a directory listing file. */ { if (!opt.remove_listing) /* --dont-remove-listing was specified, so do count this towards the number of bytes and files downloaded. */ { total_downloaded_bytes += qtyread; numurls++; } /* Deletion of listing files is not controlled by --delete-after, but by the more specific option --dont-remove-listing, and the code to do this deletion is in another function. */ } else if (!opt.spider) /* This is not a directory listing file. */ { /* Unlike directory listing files, don't pretend normal files weren't downloaded if they're going to be deleted. People seeding proxies, for instance, may want to know how many bytes and files they've downloaded through it. */ total_downloaded_bytes += qtyread; numurls++; if (opt.delete_after && !input_file_url (opt.input_filename)) { DEBUGP (("\ Removing file due to --delete-after in ftp_loop_internal():\n")); logprintf (LOG_VERBOSE, _("Removing %s.\n"), locf); if (unlink (locf)) logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno)); } } /* Restore the original leave-pendingness. */ if (orig_lp) con->cmd |= LEAVE_PENDING; else con->cmd &= ~LEAVE_PENDING; if (local_file) *local_file = xstrdup (locf); if (warc_tmp != NULL) fclose (warc_tmp); return RETROK; } while (!opt.ntry || (count < opt.ntry)); if (con->csock != -1 && (con->st & ON_YOUR_OWN)) { fd_close (con->csock); con->csock = -1; } if (warc_tmp != NULL) fclose (warc_tmp); return TRYLIMEXC; } /* Return the directory listing in a reusable format. The directory /* Return the directory listing in a reusable format. The directory is specifed in u->dir. */ static uerr_t ftp_get_listing (struct url *u, struct url *original_url, ccon *con, struct fileinfo **f) { uerr_t err; char *uf; /* url file name */ con->st &= ~ON_YOUR_OWN; con->cmd |= (DO_LIST | LEAVE_PENDING); con->cmd &= ~DO_RETR; /* Find the listing file name. We do it by taking the file name of the URL and replacing the last component with the listing file name. */ uf = url_file_name (u, NULL); lf = file_merge (uf, LIST_FILENAME); xfree (uf); DEBUGP ((_("Using %s as listing tmp file.\n"), quote (lf))); con->target = xstrdup (lf); con->target = xstrdup (lf); xfree (lf); err = ftp_loop_internal (u, original_url, NULL, con, NULL, false); lf = xstrdup (con->target); xfree (con->target); con->target = old_target; { *f = ftp_parse_ls (lf, con->rs); if (opt.remove_listing) { if (unlink (lf)) logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno)); else logprintf (LOG_VERBOSE, _("Removed %s.\n"), quote (lf)); } } else *f = NULL; xfree (lf); con->cmd &= ~DO_LIST; return err; } return err; }
165,015
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int udf_pc_to_char(struct super_block *sb, unsigned char *from, int fromlen, unsigned char *to, int tolen) { struct pathComponent *pc; int elen = 0; int comp_len; unsigned char *p = to; /* Reserve one byte for terminating \0 */ tolen--; while (elen < fromlen) { pc = (struct pathComponent *)(from + elen); switch (pc->componentType) { case 1: /* * Symlink points to some place which should be agreed * upon between originator and receiver of the media. Ignore. */ if (pc->lengthComponentIdent > 0) break; /* Fall through */ case 2: if (tolen == 0) return -ENAMETOOLONG; p = to; *p++ = '/'; tolen--; break; case 3: if (tolen < 3) return -ENAMETOOLONG; memcpy(p, "../", 3); p += 3; tolen -= 3; break; case 4: if (tolen < 2) return -ENAMETOOLONG; memcpy(p, "./", 2); p += 2; tolen -= 2; /* that would be . - just ignore */ break; case 5: comp_len = udf_get_filename(sb, pc->componentIdent, pc->lengthComponentIdent, p, tolen); p += comp_len; tolen -= comp_len; if (tolen == 0) return -ENAMETOOLONG; *p++ = '/'; tolen--; break; } elen += sizeof(struct pathComponent) + pc->lengthComponentIdent; } if (p > to + 1) p[-1] = '\0'; else p[0] = '\0'; return 0; } Commit Message: udf: Check component length before reading it Check that length specified in a component of a symlink fits in the input buffer we are reading. Also properly ignore component length for component types that do not use it. Otherwise we read memory after end of buffer for corrupted udf image. Reported-by: Carl Henrik Lunde <[email protected]> CC: [email protected] Signed-off-by: Jan Kara <[email protected]> CWE ID:
static int udf_pc_to_char(struct super_block *sb, unsigned char *from, int fromlen, unsigned char *to, int tolen) { struct pathComponent *pc; int elen = 0; int comp_len; unsigned char *p = to; /* Reserve one byte for terminating \0 */ tolen--; while (elen < fromlen) { pc = (struct pathComponent *)(from + elen); elen += sizeof(struct pathComponent); switch (pc->componentType) { case 1: /* * Symlink points to some place which should be agreed * upon between originator and receiver of the media. Ignore. */ if (pc->lengthComponentIdent > 0) { elen += pc->lengthComponentIdent; break; } /* Fall through */ case 2: if (tolen == 0) return -ENAMETOOLONG; p = to; *p++ = '/'; tolen--; break; case 3: if (tolen < 3) return -ENAMETOOLONG; memcpy(p, "../", 3); p += 3; tolen -= 3; break; case 4: if (tolen < 2) return -ENAMETOOLONG; memcpy(p, "./", 2); p += 2; tolen -= 2; /* that would be . - just ignore */ break; case 5: elen += pc->lengthComponentIdent; if (elen > fromlen) return -EIO; comp_len = udf_get_filename(sb, pc->componentIdent, pc->lengthComponentIdent, p, tolen); p += comp_len; tolen -= comp_len; if (tolen == 0) return -ENAMETOOLONG; *p++ = '/'; tolen--; break; } } if (p > to + 1) p[-1] = '\0'; else p[0] = '\0'; return 0; }
166,761
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void cipso_v4_req_delattr(struct request_sock *req) { struct ip_options *opt; struct inet_request_sock *req_inet; req_inet = inet_rsk(req); opt = req_inet->opt; if (opt == NULL || opt->cipso == 0) return; cipso_v4_delopt(&req_inet->opt); } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
void cipso_v4_req_delattr(struct request_sock *req) { struct ip_options_rcu *opt; struct inet_request_sock *req_inet; req_inet = inet_rsk(req); opt = req_inet->opt; if (opt == NULL || opt->opt.cipso == 0) return; cipso_v4_delopt(&req_inet->opt); }
165,547
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: uint64_t esp_reg_read(ESPState *s, uint32_t saddr) { uint32_t old_val; trace_esp_mem_readb(saddr, s->rregs[saddr]); switch (saddr) { case ESP_FIFO: if (s->ti_size > 0) { s->ti_size--; if ((s->rregs[ESP_RSTAT] & STAT_PIO_MASK) == 0) { /* Data out. */ qemu_log_mask(LOG_UNIMP, "esp: PIO data read not implemented\n"); s->rregs[ESP_FIFO] = 0; } else { s->rregs[ESP_FIFO] = s->ti_buf[s->ti_rptr++]; } esp_raise_irq(s); } if (s->ti_size == 0) { s->ti_rptr = 0; s->ti_wptr = 0; } s->ti_wptr = 0; } break; case ESP_RINTR: /* Clear sequence step, interrupt register and all status bits except TC */ old_val = s->rregs[ESP_RINTR]; s->rregs[ESP_RINTR] = 0; s->rregs[ESP_RSTAT] &= ~STAT_TC; s->rregs[ESP_RSEQ] = SEQ_CD; esp_lower_irq(s); return old_val; case ESP_TCHI: /* Return the unique id if the value has never been written */ if (!s->tchi_written) { return s->chip_id; } default: break; } Commit Message: CWE ID: CWE-20
uint64_t esp_reg_read(ESPState *s, uint32_t saddr) { uint32_t old_val; trace_esp_mem_readb(saddr, s->rregs[saddr]); switch (saddr) { case ESP_FIFO: if ((s->rregs[ESP_RSTAT] & STAT_PIO_MASK) == 0) { /* Data out. */ qemu_log_mask(LOG_UNIMP, "esp: PIO data read not implemented\n"); s->rregs[ESP_FIFO] = 0; esp_raise_irq(s); } else if (s->ti_rptr < s->ti_wptr) { s->ti_size--; s->rregs[ESP_FIFO] = s->ti_buf[s->ti_rptr++]; esp_raise_irq(s); } if (s->ti_rptr == s->ti_wptr) { s->ti_rptr = 0; s->ti_wptr = 0; } s->ti_wptr = 0; } break; case ESP_RINTR: /* Clear sequence step, interrupt register and all status bits except TC */ old_val = s->rregs[ESP_RINTR]; s->rregs[ESP_RINTR] = 0; s->rregs[ESP_RSTAT] &= ~STAT_TC; s->rregs[ESP_RSEQ] = SEQ_CD; esp_lower_irq(s); return old_val; case ESP_TCHI: /* Return the unique id if the value has never been written */ if (!s->tchi_written) { return s->chip_id; } default: break; }
165,012
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: AutoFillQueryXmlParser::AutoFillQueryXmlParser( std::vector<AutoFillFieldType>* field_types, UploadRequired* upload_required) : field_types_(field_types), upload_required_(upload_required) { DCHECK(upload_required_); } Commit Message: Add support for autofill server experiments BUG=none TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId Review URL: http://codereview.chromium.org/6260027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
AutoFillQueryXmlParser::AutoFillQueryXmlParser( std::vector<AutoFillFieldType>* field_types, UploadRequired* upload_required, std::string* experiment_id) : field_types_(field_types), upload_required_(upload_required), experiment_id_(experiment_id) { DCHECK(upload_required_); DCHECK(experiment_id_); }
170,653
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ehci_advance_state(EHCIState *ehci, int async) { EHCIQueue *q = NULL; int again; do { case EST_WAITLISTHEAD: again = ehci_state_waitlisthead(ehci, async); break; case EST_FETCHENTRY: again = ehci_state_fetchentry(ehci, async); break; case EST_FETCHQH: q = ehci_state_fetchqh(ehci, async); if (q != NULL) { assert(q->async == async); again = 1; } else { again = 0; } break; case EST_FETCHITD: again = ehci_state_fetchitd(ehci, async); break; case EST_FETCHSITD: again = ehci_state_fetchsitd(ehci, async); break; case EST_ADVANCEQUEUE: case EST_FETCHQTD: assert(q != NULL); again = ehci_state_fetchqtd(q); break; case EST_HORIZONTALQH: assert(q != NULL); again = ehci_state_horizqh(q); break; case EST_EXECUTE: assert(q != NULL); again = ehci_state_execute(q); if (async) { ehci->async_stepdown = 0; } break; case EST_EXECUTING: assert(q != NULL); if (async) { ehci->async_stepdown = 0; } again = ehci_state_executing(q); break; case EST_WRITEBACK: assert(q != NULL); again = ehci_state_writeback(q); if (!async) { ehci->periodic_sched_active = PERIODIC_ACTIVE; } break; default: fprintf(stderr, "Bad state!\n"); again = -1; g_assert_not_reached(); break; } break; } Commit Message: CWE ID: CWE-20
static void ehci_advance_state(EHCIState *ehci, int async) { EHCIQueue *q = NULL; int itd_count = 0; int again; do { case EST_WAITLISTHEAD: again = ehci_state_waitlisthead(ehci, async); break; case EST_FETCHENTRY: again = ehci_state_fetchentry(ehci, async); break; case EST_FETCHQH: q = ehci_state_fetchqh(ehci, async); if (q != NULL) { assert(q->async == async); again = 1; } else { again = 0; } break; case EST_FETCHITD: again = ehci_state_fetchitd(ehci, async); itd_count++; break; case EST_FETCHSITD: again = ehci_state_fetchsitd(ehci, async); itd_count++; break; case EST_ADVANCEQUEUE: case EST_FETCHQTD: assert(q != NULL); again = ehci_state_fetchqtd(q); break; case EST_HORIZONTALQH: assert(q != NULL); again = ehci_state_horizqh(q); break; case EST_EXECUTE: assert(q != NULL); again = ehci_state_execute(q); if (async) { ehci->async_stepdown = 0; } break; case EST_EXECUTING: assert(q != NULL); if (async) { ehci->async_stepdown = 0; } again = ehci_state_executing(q); break; case EST_WRITEBACK: assert(q != NULL); again = ehci_state_writeback(q); if (!async) { ehci->periodic_sched_active = PERIODIC_ACTIVE; } break; default: fprintf(stderr, "Bad state!\n"); again = -1; g_assert_not_reached(); break; } break; }
165,075
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void IndexedDBCursor::RemoveCursorFromTransaction() { if (transaction_) transaction_->UnregisterOpenCursor(this); } Commit Message: [IndexedDB] Fix Cursor UAF If the connection is closed before we return a cursor, it dies in IndexedDBCallbacks::IOThreadHelper::SendSuccessCursor. It's deleted on the correct thread, but we also need to makes sure to remove it from its transaction. To make things simpler, we have the cursor remove itself from its transaction on destruction. R: [email protected] Bug: 728887 Change-Id: I8c76e6195c2490137a05213e47c635d12f4d3dd2 Reviewed-on: https://chromium-review.googlesource.com/526284 Commit-Queue: Daniel Murphy <[email protected]> Reviewed-by: Victor Costan <[email protected]> Cr-Commit-Position: refs/heads/master@{#477504} CWE ID: CWE-416
void IndexedDBCursor::RemoveCursorFromTransaction() {
172,307
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps) { int start = 0; u32 prev_legacy, cur_legacy; mutex_lock(&kvm->arch.vpit->pit_state.lock); prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY; cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY; if (!prev_legacy && cur_legacy) start = 1; memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels, sizeof(kvm->arch.vpit->pit_state.channels)); kvm->arch.vpit->pit_state.flags = ps->flags; kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start); mutex_unlock(&kvm->arch.vpit->pit_state.lock); return 0; } Commit Message: KVM: x86: Reload pit counters for all channels when restoring state Currently if userspace restores the pit counters with a count of 0 on channels 1 or 2 and the guest attempts to read the count on those channels, then KVM will perform a mod of 0 and crash. This will ensure that 0 values are converted to 65536 as per the spec. This is CVE-2015-7513. Signed-off-by: Andy Honig <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID:
static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps) { int start = 0; int i; u32 prev_legacy, cur_legacy; mutex_lock(&kvm->arch.vpit->pit_state.lock); prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY; cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY; if (!prev_legacy && cur_legacy) start = 1; memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels, sizeof(kvm->arch.vpit->pit_state.channels)); kvm->arch.vpit->pit_state.flags = ps->flags; for (i = 0; i < 3; i++) kvm_pit_load_count(kvm, i, kvm->arch.vpit->pit_state.channels[i].count, start); mutex_unlock(&kvm->arch.vpit->pit_state.lock); return 0; }
167,561
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cypress_open(struct tty_struct *tty, struct usb_serial_port *port) { struct cypress_private *priv = usb_get_serial_port_data(port); struct usb_serial *serial = port->serial; unsigned long flags; int result = 0; if (!priv->comm_is_ok) return -EIO; /* clear halts before open */ usb_clear_halt(serial->dev, 0x81); usb_clear_halt(serial->dev, 0x02); spin_lock_irqsave(&priv->lock, flags); /* reset read/write statistics */ priv->bytes_in = 0; priv->bytes_out = 0; priv->cmd_count = 0; priv->rx_flags = 0; spin_unlock_irqrestore(&priv->lock, flags); /* Set termios */ cypress_send(port); if (tty) cypress_set_termios(tty, port, &priv->tmp_termios); /* setup the port and start reading from the device */ if (!port->interrupt_in_urb) { dev_err(&port->dev, "%s - interrupt_in_urb is empty!\n", __func__); return -1; } usb_fill_int_urb(port->interrupt_in_urb, serial->dev, usb_rcvintpipe(serial->dev, port->interrupt_in_endpointAddress), port->interrupt_in_urb->transfer_buffer, port->interrupt_in_urb->transfer_buffer_length, cypress_read_int_callback, port, priv->read_urb_interval); result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL); if (result) { dev_err(&port->dev, "%s - failed submitting read urb, error %d\n", __func__, result); cypress_set_dead(port); } return result; } /* cypress_open */ Commit Message: USB: cypress_m8: add endpoint sanity check An attack using missing endpoints exists. CVE-2016-3137 Signed-off-by: Oliver Neukum <[email protected]> CC: [email protected] Signed-off-by: Johan Hovold <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID:
static int cypress_open(struct tty_struct *tty, struct usb_serial_port *port) { struct cypress_private *priv = usb_get_serial_port_data(port); struct usb_serial *serial = port->serial; unsigned long flags; int result = 0; if (!priv->comm_is_ok) return -EIO; /* clear halts before open */ usb_clear_halt(serial->dev, 0x81); usb_clear_halt(serial->dev, 0x02); spin_lock_irqsave(&priv->lock, flags); /* reset read/write statistics */ priv->bytes_in = 0; priv->bytes_out = 0; priv->cmd_count = 0; priv->rx_flags = 0; spin_unlock_irqrestore(&priv->lock, flags); /* Set termios */ cypress_send(port); if (tty) cypress_set_termios(tty, port, &priv->tmp_termios); /* setup the port and start reading from the device */ usb_fill_int_urb(port->interrupt_in_urb, serial->dev, usb_rcvintpipe(serial->dev, port->interrupt_in_endpointAddress), port->interrupt_in_urb->transfer_buffer, port->interrupt_in_urb->transfer_buffer_length, cypress_read_int_callback, port, priv->read_urb_interval); result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL); if (result) { dev_err(&port->dev, "%s - failed submitting read urb, error %d\n", __func__, result); cypress_set_dead(port); } return result; } /* cypress_open */
167,360
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool SerializeNotificationDatabaseData(const NotificationDatabaseData& input, std::string* output) { DCHECK(output); scoped_ptr<NotificationDatabaseDataProto::NotificationData> payload( new NotificationDatabaseDataProto::NotificationData()); const PlatformNotificationData& notification_data = input.notification_data; payload->set_title(base::UTF16ToUTF8(notification_data.title)); switch (notification_data.direction) { case PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT: payload->set_direction( NotificationDatabaseDataProto::NotificationData::LEFT_TO_RIGHT); break; case PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT: payload->set_direction( NotificationDatabaseDataProto::NotificationData::RIGHT_TO_LEFT); break; case PlatformNotificationData::DIRECTION_AUTO: payload->set_direction( NotificationDatabaseDataProto::NotificationData::AUTO); break; } payload->set_lang(notification_data.lang); payload->set_body(base::UTF16ToUTF8(notification_data.body)); payload->set_tag(notification_data.tag); payload->set_icon(notification_data.icon.spec()); for (size_t i = 0; i < notification_data.vibration_pattern.size(); ++i) payload->add_vibration_pattern(notification_data.vibration_pattern[i]); payload->set_timestamp(notification_data.timestamp.ToInternalValue()); payload->set_silent(notification_data.silent); payload->set_require_interaction(notification_data.require_interaction); if (notification_data.data.size()) { payload->set_data(&notification_data.data.front(), notification_data.data.size()); } for (const PlatformNotificationAction& action : notification_data.actions) { NotificationDatabaseDataProto::NotificationAction* payload_action = payload->add_actions(); payload_action->set_action(action.action); payload_action->set_title(base::UTF16ToUTF8(action.title)); } NotificationDatabaseDataProto message; message.set_notification_id(input.notification_id); message.set_origin(input.origin.spec()); message.set_service_worker_registration_id( input.service_worker_registration_id); message.set_allocated_notification_data(payload.release()); return message.SerializeToString(output); } Commit Message: Notification actions may have an icon url. This is behind a runtime flag for two reasons: * The implementation is incomplete. * We're still evaluating the API design. Intent to Implement and Ship: Notification Action Icons https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ BUG=581336 Review URL: https://codereview.chromium.org/1644573002 Cr-Commit-Position: refs/heads/master@{#374649} CWE ID:
bool SerializeNotificationDatabaseData(const NotificationDatabaseData& input, std::string* output) { DCHECK(output); scoped_ptr<NotificationDatabaseDataProto::NotificationData> payload( new NotificationDatabaseDataProto::NotificationData()); const PlatformNotificationData& notification_data = input.notification_data; payload->set_title(base::UTF16ToUTF8(notification_data.title)); switch (notification_data.direction) { case PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT: payload->set_direction( NotificationDatabaseDataProto::NotificationData::LEFT_TO_RIGHT); break; case PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT: payload->set_direction( NotificationDatabaseDataProto::NotificationData::RIGHT_TO_LEFT); break; case PlatformNotificationData::DIRECTION_AUTO: payload->set_direction( NotificationDatabaseDataProto::NotificationData::AUTO); break; } payload->set_lang(notification_data.lang); payload->set_body(base::UTF16ToUTF8(notification_data.body)); payload->set_tag(notification_data.tag); payload->set_icon(notification_data.icon.spec()); for (size_t i = 0; i < notification_data.vibration_pattern.size(); ++i) payload->add_vibration_pattern(notification_data.vibration_pattern[i]); payload->set_timestamp(notification_data.timestamp.ToInternalValue()); payload->set_silent(notification_data.silent); payload->set_require_interaction(notification_data.require_interaction); if (notification_data.data.size()) { payload->set_data(&notification_data.data.front(), notification_data.data.size()); } for (const PlatformNotificationAction& action : notification_data.actions) { NotificationDatabaseDataProto::NotificationAction* payload_action = payload->add_actions(); payload_action->set_action(action.action); payload_action->set_title(base::UTF16ToUTF8(action.title)); payload_action->set_icon(action.icon.spec()); } NotificationDatabaseDataProto message; message.set_notification_id(input.notification_id); message.set_origin(input.origin.spec()); message.set_service_worker_registration_id( input.service_worker_registration_id); message.set_allocated_notification_data(payload.release()); return message.SerializeToString(output); }
171,630
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadLABELImage(const ImageInfo *image_info, ExceptionInfo *exception) { char geometry[MaxTextExtent], *property; const char *label; DrawInfo *draw_info; Image *image; MagickBooleanType status; TypeMetric metrics; size_t height, width; /* Initialize Image structure. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); (void) ResetImagePage(image,"0x0+0+0"); property=InterpretImageProperties(image_info,image,image_info->filename); (void) SetImageProperty(image,"label",property); property=DestroyString(property); label=GetImageProperty(image,"label"); draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); draw_info->text=ConstantString(label); metrics.width=0; metrics.ascent=0.0; status=GetMultilineTypeMetrics(image,draw_info,&metrics); if ((image->columns == 0) && (image->rows == 0)) { image->columns=(size_t) (metrics.width+draw_info->stroke_width+0.5); image->rows=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); } else if (((image->columns == 0) || (image->rows == 0)) || (fabs(image_info->pointsize) < MagickEpsilon)) { double high, low; /* Auto fit text into bounding box. */ for ( ; ; draw_info->pointsize*=2.0) { (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); (void) status; width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); if ((image->columns != 0) && (image->rows != 0)) { if ((width >= image->columns) && (height >= image->rows)) break; } else if (((image->columns != 0) && (width >= image->columns)) || ((image->rows != 0) && (height >= image->rows))) break; } high=draw_info->pointsize; for (low=1.0; (high-low) > 0.5; ) { draw_info->pointsize=(low+high)/2.0; (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); if ((image->columns != 0) && (image->rows != 0)) { if ((width < image->columns) && (height < image->rows)) low=draw_info->pointsize+0.5; else high=draw_info->pointsize-0.5; } else if (((image->columns != 0) && (width < image->columns)) || ((image->rows != 0) && (height < image->rows))) low=draw_info->pointsize+0.5; else high=draw_info->pointsize-0.5; } draw_info->pointsize=(low+high)/2.0-0.5; } status=GetMultilineTypeMetrics(image,draw_info,&metrics); if (status == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if (image->columns == 0) image->columns=(size_t) (metrics.width+draw_info->stroke_width+0.5); if (image->columns == 0) image->columns=(size_t) (draw_info->pointsize+draw_info->stroke_width+0.5); if (image->rows == 0) image->rows=(size_t) (metrics.ascent-metrics.descent+ draw_info->stroke_width+0.5); if (image->rows == 0) image->rows=(size_t) (draw_info->pointsize+draw_info->stroke_width+0.5); if (draw_info->gravity == UndefinedGravity) { (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1+draw_info->stroke_width/2.0,metrics.ascent+ draw_info->stroke_width/2.0); (void) CloneString(&draw_info->geometry,geometry); } if (draw_info->direction == RightToLeftDirection) { if (draw_info->direction == RightToLeftDirection) (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", image->columns-(metrics.bounds.x2+draw_info->stroke_width/2.0), metrics.ascent+draw_info->stroke_width/2.0); (void) CloneString(&draw_info->geometry,geometry); } if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } (void) AnnotateImage(image,draw_info); if (image_info->pointsize == 0.0) { char pointsize[MaxTextExtent]; (void) FormatLocaleString(pointsize,MaxTextExtent,"%.20g", draw_info->pointsize); (void) SetImageProperty(image,"label:pointsize",pointsize); } draw_info=DestroyDrawInfo(draw_info); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadLABELImage(const ImageInfo *image_info, ExceptionInfo *exception) { char geometry[MaxTextExtent], *property; const char *label; DrawInfo *draw_info; Image *image; MagickBooleanType status; TypeMetric metrics; size_t height, width; /* Initialize Image structure. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); (void) ResetImagePage(image,"0x0+0+0"); property=InterpretImageProperties(image_info,image,image_info->filename); (void) SetImageProperty(image,"label",property); property=DestroyString(property); label=GetImageProperty(image,"label"); draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); draw_info->text=ConstantString(label); metrics.width=0; metrics.ascent=0.0; status=GetMultilineTypeMetrics(image,draw_info,&metrics); if ((image->columns == 0) && (image->rows == 0)) { image->columns=(size_t) (metrics.width+draw_info->stroke_width+0.5); image->rows=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); } else if (((image->columns == 0) || (image->rows == 0)) || (fabs(image_info->pointsize) < MagickEpsilon)) { double high, low; /* Auto fit text into bounding box. */ for ( ; ; draw_info->pointsize*=2.0) { (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); (void) status; width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); if ((image->columns != 0) && (image->rows != 0)) { if ((width >= image->columns) && (height >= image->rows)) break; } else if (((image->columns != 0) && (width >= image->columns)) || ((image->rows != 0) && (height >= image->rows))) break; } high=draw_info->pointsize; for (low=1.0; (high-low) > 0.5; ) { draw_info->pointsize=(low+high)/2.0; (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); if ((image->columns != 0) && (image->rows != 0)) { if ((width < image->columns) && (height < image->rows)) low=draw_info->pointsize+0.5; else high=draw_info->pointsize-0.5; } else if (((image->columns != 0) && (width < image->columns)) || ((image->rows != 0) && (height < image->rows))) low=draw_info->pointsize+0.5; else high=draw_info->pointsize-0.5; } draw_info->pointsize=(low+high)/2.0-0.5; } status=GetMultilineTypeMetrics(image,draw_info,&metrics); if (status == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if (image->columns == 0) image->columns=(size_t) (metrics.width+draw_info->stroke_width+0.5); if (image->columns == 0) image->columns=(size_t) (draw_info->pointsize+draw_info->stroke_width+0.5); if (image->rows == 0) image->rows=(size_t) (metrics.ascent-metrics.descent+ draw_info->stroke_width+0.5); if (image->rows == 0) image->rows=(size_t) (draw_info->pointsize+draw_info->stroke_width+0.5); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (draw_info->gravity == UndefinedGravity) { (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1+draw_info->stroke_width/2.0,metrics.ascent+ draw_info->stroke_width/2.0); (void) CloneString(&draw_info->geometry,geometry); } if (draw_info->direction == RightToLeftDirection) { if (draw_info->direction == RightToLeftDirection) (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", image->columns-(metrics.bounds.x2+draw_info->stroke_width/2.0), metrics.ascent+draw_info->stroke_width/2.0); (void) CloneString(&draw_info->geometry,geometry); } if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } (void) AnnotateImage(image,draw_info); if (image_info->pointsize == 0.0) { char pointsize[MaxTextExtent]; (void) FormatLocaleString(pointsize,MaxTextExtent,"%.20g", draw_info->pointsize); (void) SetImageProperty(image,"label:pointsize",pointsize); } draw_info=DestroyDrawInfo(draw_info); return(GetFirstImageInList(image)); }
168,577
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PaymentRequest::Complete(mojom::PaymentComplete result) { if (!client_.is_bound()) return; if (result == mojom::PaymentComplete::FAIL) { delegate_->ShowErrorMessage(); } else { DCHECK(!has_recorded_completion_); journey_logger_.SetCompleted(); has_recorded_completion_ = true; delegate_->GetPrefService()->SetBoolean(kPaymentsFirstTransactionCompleted, true); client_->OnComplete(); state_->RecordUseStats(); } } Commit Message: [Payment Request][Desktop] Prevent use after free. Before this patch, a compromised renderer on desktop could make IPC methods into Payment Request in an unexpected ordering and cause use after free in the browser. This patch will disconnect the IPC pipes if: - Init() is called more than once. - Any other method is called before Init(). - Show() is called more than once. - Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or Complete() are called before Show(). This patch re-orders the IPC methods in payment_request.cc to match the order in payment_request.h, which eases verifying correctness of their error handling. This patch prints more errors to the developer console, if available, to improve debuggability by web developers, who rarely check where LOG prints. After this patch, unexpected ordering of calls into the Payment Request IPC from the renderer to the browser on desktop will print an error in the developer console and disconnect the IPC pipes. The binary might increase slightly in size because more logs are included in the release version instead of being stripped at compile time. Bug: 912947 Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a Reviewed-on: https://chromium-review.googlesource.com/c/1370198 Reviewed-by: anthonyvd <[email protected]> Commit-Queue: Rouslan Solomakhin <[email protected]> Cr-Commit-Position: refs/heads/master@{#616822} CWE ID: CWE-189
void PaymentRequest::Complete(mojom::PaymentComplete result) { if (!IsInitialized()) { log_.Error("Attempted complete without initialization"); OnConnectionTerminated(); return; } if (!IsThisPaymentRequestShowing()) { log_.Error("Attempted complete without show"); OnConnectionTerminated(); return; } if (result == mojom::PaymentComplete::FAIL) { delegate_->ShowErrorMessage(); } else { DCHECK(!has_recorded_completion_); journey_logger_.SetCompleted(); has_recorded_completion_ = true; delegate_->GetPrefService()->SetBoolean(kPaymentsFirstTransactionCompleted, true); client_->OnComplete(); state_->RecordUseStats(); } }
173,081
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn, xkb_mod_mask_t *mods_rtrn, CompatInfo *info) { if (expr == NULL) { *pred_rtrn = MATCH_ANY_OR_NONE; *mods_rtrn = MOD_REAL_MASK_ALL; return true; } *pred_rtrn = MATCH_EXACTLY; if (expr->expr.op == EXPR_ACTION_DECL) { const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name); if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn)) { log_err(info->ctx, "Illegal modifier predicate \"%s\"; Ignored\n", pred_txt); return false; } expr = expr->action.args; } else if (expr->expr.op == EXPR_IDENT) { const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident); if (pred_txt && istreq(pred_txt, "any")) { *pred_rtrn = MATCH_ANY; *mods_rtrn = MOD_REAL_MASK_ALL; return true; } } return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods, mods_rtrn); } Commit Message: xkbcomp: Don't crash on no-op modmask expressions If we have an expression of the form 'l1' in an interp section, we unconditionally try to dereference its args, even if it has none. Signed-off-by: Daniel Stone <[email protected]> CWE ID: CWE-476
ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn, xkb_mod_mask_t *mods_rtrn, CompatInfo *info) { if (expr == NULL) { *pred_rtrn = MATCH_ANY_OR_NONE; *mods_rtrn = MOD_REAL_MASK_ALL; return true; } *pred_rtrn = MATCH_EXACTLY; if (expr->expr.op == EXPR_ACTION_DECL) { const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name); if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn) || !expr->action.args) { log_err(info->ctx, "Illegal modifier predicate \"%s\"; Ignored\n", pred_txt); return false; } expr = expr->action.args; } else if (expr->expr.op == EXPR_IDENT) { const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident); if (pred_txt && istreq(pred_txt, "any")) { *pred_rtrn = MATCH_ANY; *mods_rtrn = MOD_REAL_MASK_ALL; return true; } } return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods, mods_rtrn); }
169,088
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int res_inverse(vorbis_dsp_state *vd,vorbis_info_residue *info, ogg_int32_t **in,int *nonzero,int ch){ int i,j,k,s,used=0; codec_setup_info *ci=(codec_setup_info *)vd->vi->codec_setup; codebook *phrasebook=ci->book_param+info->groupbook; int samples_per_partition=info->grouping; int partitions_per_word=phrasebook->dim; int pcmend=ci->blocksizes[vd->W]; if(info->type<2){ int max=pcmend>>1; int end=(info->end<max?info->end:max); int n=end-info->begin; if(n>0){ int partvals=n/samples_per_partition; int partwords=(partvals+partitions_per_word-1)/partitions_per_word; for(i=0;i<ch;i++) if(nonzero[i]) in[used++]=in[i]; ch=used; if(used){ char **partword=(char **)alloca(ch*sizeof(*partword)); for(j=0;j<ch;j++) partword[j]=(char *)alloca(partwords*partitions_per_word* sizeof(*partword[j])); for(s=0;s<info->stages;s++){ for(i=0;i<partvals;){ if(s==0){ /* fetch the partition word for each channel */ partword[0][i+partitions_per_word-1]=1; for(k=partitions_per_word-2;k>=0;k--) partword[0][i+k]=partword[0][i+k+1]*info->partitions; for(j=1;j<ch;j++) for(k=partitions_per_word-1;k>=0;k--) partword[j][i+k]=partword[j-1][i+k]; for(j=0;j<ch;j++){ int temp=vorbis_book_decode(phrasebook,&vd->opb); if(temp==-1)goto eopbreak; /* this can be done quickly in assembly due to the quotient always being at most six bits */ for(k=0;k<partitions_per_word;k++){ ogg_uint32_t div=partword[j][i+k]; partword[j][i+k]=temp/div; temp-=partword[j][i+k]*div; } } } /* now we decode residual values for the partitions */ for(k=0;k<partitions_per_word && i<partvals;k++,i++) for(j=0;j<ch;j++){ long offset=info->begin+i*samples_per_partition; if(info->stagemasks[(int)partword[j][i]]&(1<<s)){ codebook *stagebook=ci->book_param+ info->stagebooks[(partword[j][i]<<3)+s]; if(info->type){ if(vorbis_book_decodev_add(stagebook,in[j]+offset,&vd->opb, samples_per_partition,-8)==-1) goto eopbreak; }else{ if(vorbis_book_decodevs_add(stagebook,in[j]+offset,&vd->opb, samples_per_partition,-8)==-1) goto eopbreak; } } } } } } } }else{ int max=(pcmend*ch)>>1; int end=(info->end<max?info->end:max); int n=end-info->begin; if(n>0){ int partvals=n/samples_per_partition; int partwords=(partvals+partitions_per_word-1)/partitions_per_word; char *partword= (char *)alloca(partwords*partitions_per_word*sizeof(*partword)); int beginoff=info->begin/ch; for(i=0;i<ch;i++)if(nonzero[i])break; if(i==ch)return(0); /* no nonzero vectors */ samples_per_partition/=ch; for(s=0;s<info->stages;s++){ for(i=0;i<partvals;){ if(s==0){ int temp; partword[i+partitions_per_word-1]=1; for(k=partitions_per_word-2;k>=0;k--) partword[i+k]=partword[i+k+1]*info->partitions; /* fetch the partition word */ temp=vorbis_book_decode(phrasebook,&vd->opb); if(temp==-1)goto eopbreak; /* this can be done quickly in assembly due to the quotient always being at most six bits */ for(k=0;k<partitions_per_word;k++){ ogg_uint32_t div=partword[i+k]; partword[i+k]=temp/div; temp-=partword[i+k]*div; } } /* now we decode residual values for the partitions */ for(k=0;k<partitions_per_word && i<partvals;k++,i++) if(info->stagemasks[(int)partword[i]]&(1<<s)){ codebook *stagebook=ci->book_param+ info->stagebooks[(partword[i]<<3)+s]; if(vorbis_book_decodevv_add(stagebook,in, i*samples_per_partition+beginoff,ch, &vd->opb, samples_per_partition,-8)==-1) goto eopbreak; } } } } } eopbreak: return 0; } Commit Message: Check partword is in range for # of partitions and reformat tabs->spaces for readability. Bug: 28556125 Change-Id: Id02819a6a5bcc24ba4f8a502081e5cb45272681c CWE ID: CWE-20
int res_inverse(vorbis_dsp_state *vd,vorbis_info_residue *info, ogg_int32_t **in,int *nonzero,int ch){ int i,j,k,s,used=0; codec_setup_info *ci=(codec_setup_info *)vd->vi->codec_setup; codebook *phrasebook=ci->book_param+info->groupbook; int samples_per_partition=info->grouping; int partitions_per_word=phrasebook->dim; int pcmend=ci->blocksizes[vd->W]; if(info->type<2){ int max=pcmend>>1; int end=(info->end<max?info->end:max); int n=end-info->begin; if(n>0){ int partvals=n/samples_per_partition; int partwords=(partvals+partitions_per_word-1)/partitions_per_word; for(i=0;i<ch;i++) if(nonzero[i]) in[used++]=in[i]; ch=used; if(used){ char **partword=(char **)alloca(ch*sizeof(*partword)); for(j=0;j<ch;j++) partword[j]=(char *)alloca(partwords*partitions_per_word* sizeof(*partword[j])); for(s=0;s<info->stages;s++){ for(i=0;i<partvals;){ if(s==0){ /* fetch the partition word for each channel */ partword[0][i+partitions_per_word-1]=1; for(k=partitions_per_word-2;k>=0;k--) partword[0][i+k]=partword[0][i+k+1]*info->partitions; for(j=1;j<ch;j++) for(k=partitions_per_word-1;k>=0;k--) partword[j][i+k]=partword[j-1][i+k]; for(j=0;j<ch;j++){ int temp=vorbis_book_decode(phrasebook,&vd->opb); if(temp==-1)goto eopbreak; /* this can be done quickly in assembly due to the quotient always being at most six bits */ for(k=0;k<partitions_per_word;k++){ ogg_uint32_t div=partword[j][i+k]; partword[j][i+k]=temp/div; temp-=partword[j][i+k]*div; } } } /* now we decode residual values for the partitions */ for(k=0;k<partitions_per_word && i<partvals;k++,i++) for(j=0;j<ch;j++){ long offset=info->begin+i*samples_per_partition; int idx = (int)partword[j][i]; if(idx < info->partitions && info->stagemasks[idx]&(1<<s)){ codebook *stagebook=ci->book_param+ info->stagebooks[(partword[j][i]<<3)+s]; if(info->type){ if(vorbis_book_decodev_add(stagebook,in[j]+offset,&vd->opb, samples_per_partition,-8)==-1) goto eopbreak; }else{ if(vorbis_book_decodevs_add(stagebook,in[j]+offset,&vd->opb, samples_per_partition,-8)==-1) goto eopbreak; } } } } } } } }else{ int max=(pcmend*ch)>>1; int end=(info->end<max?info->end:max); int n=end-info->begin; if(n>0){ int partvals=n/samples_per_partition; int partwords=(partvals+partitions_per_word-1)/partitions_per_word; char *partword= (char *)alloca(partwords*partitions_per_word*sizeof(*partword)); int beginoff=info->begin/ch; for(i=0;i<ch;i++)if(nonzero[i])break; if(i==ch)return(0); /* no nonzero vectors */ samples_per_partition/=ch; for(s=0;s<info->stages;s++){ for(i=0;i<partvals;){ if(s==0){ int temp; partword[i+partitions_per_word-1]=1; for(k=partitions_per_word-2;k>=0;k--) partword[i+k]=partword[i+k+1]*info->partitions; /* fetch the partition word */ temp=vorbis_book_decode(phrasebook,&vd->opb); if(temp==-1)goto eopbreak; /* this can be done quickly in assembly due to the quotient always being at most six bits */ for(k=0;k<partitions_per_word;k++){ ogg_uint32_t div=partword[i+k]; partword[i+k]=temp/div; temp-=partword[i+k]*div; } } /* now we decode residual values for the partitions */ for(k=0;k<partitions_per_word && i<partvals;k++,i++) if(info->stagemasks[(int)partword[i]]&(1<<s)){ codebook *stagebook=ci->book_param+ info->stagebooks[(partword[i]<<3)+s]; if(vorbis_book_decodevv_add(stagebook,in, i*samples_per_partition+beginoff,ch, &vd->opb, samples_per_partition,-8)==-1) goto eopbreak; } } } } } eopbreak: return 0; }
173,561
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileObject, fread) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long length = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) { return; } if (length <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(length + 1); Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, fread) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long length = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) { return; } if (length <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } if (length > INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be no more than %d", INT_MAX); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(length + 1); Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; }
167,067
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MaxTextExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False when converting or mogrifying */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length+ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; /* Skip nominal layer count, frame count, and play time */ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); if (length > 1) { object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream", "`%s'", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, "object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (*p && ((p-chunk) < (ssize_t) length)) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay && (p-chunk) < (ssize_t) (length-4)) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout && (p-chunk) < (ssize_t) (length-4)) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping && (p-chunk) < (ssize_t) (length-17)) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters ", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 15) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 17) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 19) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { /* Interpolate */ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelComponent() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } /* To do: Rewrite using Get/Set***PixelComponent() */ else { /* Interpolate */ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { /* Interpolate */ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage();"); return(image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/549 CWE ID: CWE-770
static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MaxTextExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False when converting or mogrifying */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); chunk=(unsigned char *) AcquireQuantumMemory(length+ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; /* Skip nominal layer count, frame count, and play time */ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); if (length > 1) { object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream", "`%s'", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, "object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (*p && ((p-chunk) < (ssize_t) length)) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay && (p-chunk) < (ssize_t) (length-4)) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout && (p-chunk) < (ssize_t) (length-4)) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping && (p-chunk) < (ssize_t) (length-17)) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters ", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 15) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 17) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 19) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { /* Interpolate */ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelComponent() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } /* To do: Rewrite using Get/Set***PixelComponent() */ else { /* Interpolate */ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { /* Interpolate */ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage();"); return(image); }
167,980
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void qemu_spice_create_host_primary(SimpleSpiceDisplay *ssd) { QXLDevSurfaceCreate surface; memset(&surface, 0, sizeof(surface)); dprint(1, "%s/%d: %dx%d\n", __func__, ssd->qxl.id, surface_width(ssd->ds), surface_height(ssd->ds)); surface.format = SPICE_SURFACE_FMT_32_xRGB; surface.width = surface_width(ssd->ds); { dprint(1, "%s/%d:\n", __func__, ssd->qxl.id); qemu_spice_destroy_primary_surface(ssd, 0, QXL_SYNC); } void qemu_spice_display_init_common(SimpleSpiceDisplay *ssd) { qemu_mutex_init(&ssd->lock); QTAILQ_INIT(&ssd->updates); ssd->mouse_x = -1; ssd->mouse_y = -1; if (ssd->num_surfaces == 0) { ssd->num_surfaces = 1024; } ssd->bufsize = (16 * 1024 * 1024); ssd->buf = g_malloc(ssd->bufsize); } /* display listener callbacks */ void qemu_spice_display_update(SimpleSpiceDisplay *ssd, int x, int y, int w, int h) { if (ssd->num_surfaces == 0) { ssd->num_surfaces = 1024; } ssd->bufsize = (16 * 1024 * 1024); ssd->buf = g_malloc(ssd->bufsize); } /* display listener callbacks */ update_area.top = y; update_area.bottom = y + h; if (qemu_spice_rect_is_empty(&ssd->dirty)) { ssd->notify++; } qemu_spice_rect_union(&ssd->dirty, &update_area); } Commit Message: CWE ID: CWE-200
void qemu_spice_create_host_primary(SimpleSpiceDisplay *ssd) { QXLDevSurfaceCreate surface; uint64_t surface_size; memset(&surface, 0, sizeof(surface)); surface_size = (uint64_t) surface_width(ssd->ds) * surface_height(ssd->ds) * 4; assert(surface_size > 0); assert(surface_size < INT_MAX); if (ssd->bufsize < surface_size) { ssd->bufsize = surface_size; g_free(ssd->buf); ssd->buf = g_malloc(ssd->bufsize); } dprint(1, "%s/%d: %ux%u (size %" PRIu64 "/%d)\n", __func__, ssd->qxl.id, surface_width(ssd->ds), surface_height(ssd->ds), surface_size, ssd->bufsize); surface.format = SPICE_SURFACE_FMT_32_xRGB; surface.width = surface_width(ssd->ds); { dprint(1, "%s/%d:\n", __func__, ssd->qxl.id); qemu_spice_destroy_primary_surface(ssd, 0, QXL_SYNC); } void qemu_spice_display_init_common(SimpleSpiceDisplay *ssd) { qemu_mutex_init(&ssd->lock); QTAILQ_INIT(&ssd->updates); ssd->mouse_x = -1; ssd->mouse_y = -1; if (ssd->num_surfaces == 0) { ssd->num_surfaces = 1024; } ssd->bufsize = (16 * 1024 * 1024); ssd->buf = g_malloc(ssd->bufsize); } /* display listener callbacks */ void qemu_spice_display_update(SimpleSpiceDisplay *ssd, int x, int y, int w, int h) { if (ssd->num_surfaces == 0) { ssd->num_surfaces = 1024; } } /* display listener callbacks */ update_area.top = y; update_area.bottom = y + h; if (qemu_spice_rect_is_empty(&ssd->dirty)) { ssd->notify++; } qemu_spice_rect_union(&ssd->dirty, &update_area); }
165,151
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_pic_ext_data(dec_state_t *ps_dec) { stream_t *ps_stream; UWORD32 u4_start_code; IMPEG2D_ERROR_CODES_T e_error; e_error = (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; ps_stream = &ps_dec->s_bit_stream; u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); while ( (u4_start_code == EXTENSION_START_CODE || u4_start_code == USER_DATA_START_CODE) && (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE == e_error) { if(u4_start_code == USER_DATA_START_CODE) { impeg2d_dec_user_data(ps_dec); } else { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u4_start_code = impeg2d_bit_stream_nxt(ps_stream,EXT_ID_LEN); switch(u4_start_code) { case QUANT_MATRIX_EXT_ID: impeg2d_dec_quant_matrix_ext(ps_dec); break; case COPYRIGHT_EXT_ID: impeg2d_dec_copyright_ext(ps_dec); break; case PIC_DISPLAY_EXT_ID: impeg2d_dec_pic_disp_ext(ps_dec); break; case CAMERA_PARAM_EXT_ID: impeg2d_dec_cam_param_ext(ps_dec); break; case ITU_T_EXT_ID: impeg2d_dec_itu_t_ext(ps_dec); break; case PIC_SPATIAL_SCALABLE_EXT_ID: case PIC_TEMPORAL_SCALABLE_EXT_ID: e_error = IMPEG2D_SCALABLITY_NOT_SUP; break; default: /* In case its a reserved extension code */ impeg2d_bit_stream_flush(ps_stream,EXT_ID_LEN); impeg2d_next_start_code(ps_dec); break; } } u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); } return e_error; } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254
IMPEG2D_ERROR_CODES_T impeg2d_dec_pic_ext_data(dec_state_t *ps_dec) { stream_t *ps_stream; UWORD32 u4_start_code; IMPEG2D_ERROR_CODES_T e_error; e_error = (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; ps_stream = &ps_dec->s_bit_stream; u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); while ( (u4_start_code == EXTENSION_START_CODE || u4_start_code == USER_DATA_START_CODE) && (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE == e_error && (ps_stream->u4_offset < ps_stream->u4_max_offset)) { if(u4_start_code == USER_DATA_START_CODE) { impeg2d_dec_user_data(ps_dec); } else { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u4_start_code = impeg2d_bit_stream_nxt(ps_stream,EXT_ID_LEN); switch(u4_start_code) { case QUANT_MATRIX_EXT_ID: impeg2d_dec_quant_matrix_ext(ps_dec); break; case COPYRIGHT_EXT_ID: impeg2d_dec_copyright_ext(ps_dec); break; case PIC_DISPLAY_EXT_ID: impeg2d_dec_pic_disp_ext(ps_dec); break; case CAMERA_PARAM_EXT_ID: impeg2d_dec_cam_param_ext(ps_dec); break; case ITU_T_EXT_ID: impeg2d_dec_itu_t_ext(ps_dec); break; case PIC_SPATIAL_SCALABLE_EXT_ID: case PIC_TEMPORAL_SCALABLE_EXT_ID: e_error = IMPEG2D_SCALABLITY_NOT_SUP; break; default: /* In case its a reserved extension code */ impeg2d_bit_stream_flush(ps_stream,EXT_ID_LEN); impeg2d_next_start_code(ps_dec); break; } } u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); } return e_error; }
173,944
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: tt_cmap14_validate( FT_Byte* table, FT_Validator valid ) { FT_Byte* p; FT_ULong length; FT_ULong num_selectors; if ( table + 2 + 4 + 4 > valid->limit ) FT_INVALID_TOO_SHORT; p = table + 2; length = TT_NEXT_ULONG( p ); num_selectors = TT_NEXT_ULONG( p ); if ( length > (FT_ULong)( valid->limit - table ) || /* length < 10 + 11 * num_selectors ? */ length < 10 || ( length - 10 ) / 11 < num_selectors ) FT_INVALID_TOO_SHORT; /* check selectors, they must be in increasing order */ { /* we start lastVarSel at 1 because a variant selector value of 0 * isn't valid. */ FT_ULong n, lastVarSel = 1; for ( n = 0; n < num_selectors; n++ ) { FT_ULong varSel = TT_NEXT_UINT24( p ); FT_ULong defOff = TT_NEXT_ULONG( p ); FT_ULong nondefOff = TT_NEXT_ULONG( p ); if ( defOff >= length || nondefOff >= length ) FT_INVALID_TOO_SHORT; if ( varSel < lastVarSel ) FT_INVALID_DATA; lastVarSel = varSel + 1; /* check the default table (these glyphs should be reached */ /* through the normal Unicode cmap, no GIDs, just check order) */ if ( defOff != 0 ) { FT_Byte* defp = table + defOff; FT_ULong numRanges = TT_NEXT_ULONG( defp ); FT_ULong i; FT_ULong lastBase = 0; /* defp + numRanges * 4 > valid->limit ? */ if ( numRanges > (FT_ULong)( valid->limit - defp ) / 4 ) FT_INVALID_TOO_SHORT; if ( base + cnt >= 0x110000UL ) /* end of Unicode */ FT_INVALID_DATA; if ( base < lastBase ) FT_INVALID_DATA; lastBase = base + cnt + 1U; } } /* and the non-default table (these glyphs are specified here) */ if ( nondefOff != 0 ) { FT_Byte* ndp = table + nondefOff; FT_ULong numMappings = TT_NEXT_ULONG( ndp ); /* and the non-default table (these glyphs are specified here) */ if ( nondefOff != 0 ) { FT_Byte* ndp = table + nondefOff; FT_ULong numMappings = TT_NEXT_ULONG( ndp ); FT_ULong i, lastUni = 0; /* numMappings * 4 > (FT_ULong)( valid->limit - ndp ) ? */ if ( numMappings > ( (FT_ULong)( valid->limit - ndp ) ) / 4 ) FT_INVALID_TOO_SHORT; for ( i = 0; i < numMappings; ++i ) lastUni = uni + 1U; if ( valid->level >= FT_VALIDATE_TIGHT && gid >= TT_VALID_GLYPH_COUNT( valid ) ) FT_INVALID_GLYPH_ID; } } } } Commit Message: CWE ID: CWE-125
tt_cmap14_validate( FT_Byte* table, FT_Validator valid ) { FT_Byte* p; FT_ULong length; FT_ULong num_selectors; if ( table + 2 + 4 + 4 > valid->limit ) FT_INVALID_TOO_SHORT; p = table + 2; length = TT_NEXT_ULONG( p ); num_selectors = TT_NEXT_ULONG( p ); if ( length > (FT_ULong)( valid->limit - table ) || /* length < 10 + 11 * num_selectors ? */ length < 10 || ( length - 10 ) / 11 < num_selectors ) FT_INVALID_TOO_SHORT; /* check selectors, they must be in increasing order */ { /* we start lastVarSel at 1 because a variant selector value of 0 * isn't valid. */ FT_ULong n, lastVarSel = 1; for ( n = 0; n < num_selectors; n++ ) { FT_ULong varSel = TT_NEXT_UINT24( p ); FT_ULong defOff = TT_NEXT_ULONG( p ); FT_ULong nondefOff = TT_NEXT_ULONG( p ); if ( defOff >= length || nondefOff >= length ) FT_INVALID_TOO_SHORT; if ( varSel < lastVarSel ) FT_INVALID_DATA; lastVarSel = varSel + 1; /* check the default table (these glyphs should be reached */ /* through the normal Unicode cmap, no GIDs, just check order) */ if ( defOff != 0 ) { FT_Byte* defp = table + defOff; FT_ULong numRanges; FT_ULong i; FT_ULong lastBase = 0; if ( defp + 4 > valid->limit ) FT_INVALID_TOO_SHORT; numRanges = TT_NEXT_ULONG( defp ); /* defp + numRanges * 4 > valid->limit ? */ if ( numRanges > (FT_ULong)( valid->limit - defp ) / 4 ) FT_INVALID_TOO_SHORT; if ( base + cnt >= 0x110000UL ) /* end of Unicode */ FT_INVALID_DATA; if ( base < lastBase ) FT_INVALID_DATA; lastBase = base + cnt + 1U; } } /* and the non-default table (these glyphs are specified here) */ if ( nondefOff != 0 ) { FT_Byte* ndp = table + nondefOff; FT_ULong numMappings = TT_NEXT_ULONG( ndp ); /* and the non-default table (these glyphs are specified here) */ if ( nondefOff != 0 ) { FT_Byte* ndp = table + nondefOff; FT_ULong numMappings; FT_ULong i, lastUni = 0; if ( ndp + 4 > valid->limit ) FT_INVALID_TOO_SHORT; numMappings = TT_NEXT_ULONG( ndp ); /* numMappings * 5 > (FT_ULong)( valid->limit - ndp ) ? */ if ( numMappings > ( (FT_ULong)( valid->limit - ndp ) ) / 5 ) FT_INVALID_TOO_SHORT; for ( i = 0; i < numMappings; ++i ) lastUni = uni + 1U; if ( valid->level >= FT_VALIDATE_TIGHT && gid >= TT_VALID_GLYPH_COUNT( valid ) ) FT_INVALID_GLYPH_ID; } } } }
165,426
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static EncodedJSValue JSC_HOST_CALL jsTestObjConstructorFunctionOverloadedMethod12(ExecState* exec) { if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); const String& type(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); TestObj::overloadedMethod1(type); return JSValue::encode(jsUndefined()); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
static EncodedJSValue JSC_HOST_CALL jsTestObjConstructorFunctionOverloadedMethod12(ExecState* exec) { if (exec->argumentCount() < 1) return throwVMError(exec, createNotEnoughArgumentsError(exec)); const String& type(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); TestObj::overloadedMethod1(type); return JSValue::encode(jsUndefined()); }
170,581
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long mkvparser::ReadUInt(IMkvReader* pReader, long long pos, long& len) { assert(pReader); assert(pos >= 0); int status; len = 1; unsigned char b; status = pReader->Read(pos, 1, &b); if (status < 0) // error or underflow return status; if (status > 0) // interpreted as "underflow" return E_BUFFER_NOT_FULL; if (b == 0) // we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } long long result = b & (~m); ++pos; for (int i = 1; i < len; ++i) { status = pReader->Read(pos, 1, &b); if (status < 0) { len = 1; return status; } if (status > 0) { len = 1; return E_BUFFER_NOT_FULL; } result <<= 8; result |= b; ++pos; } return result; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long long mkvparser::ReadUInt(IMkvReader* pReader, long long pos, long& len) { long long ReadUInt(IMkvReader* pReader, long long pos, long& len) { if (!pReader || pos < 0) return E_FILE_FORMAT_INVALID; len = 1; unsigned char b; int status = pReader->Read(pos, 1, &b); if (status < 0) // error or underflow return status; if (status > 0) // interpreted as "underflow" return E_BUFFER_NOT_FULL; if (b == 0) // we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } long long result = b & (~m); ++pos; for (int i = 1; i < len; ++i) { status = pReader->Read(pos, 1, &b); if (status < 0) { len = 1; return status; } if (status > 0) { len = 1; return E_BUFFER_NOT_FULL; } result <<= 8; result |= b; ++pos; } return result; }
173,862
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e) : saml2md::DynamicMetadataProvider(e), m_verifyHost(XMLHelper::getAttrBool(e, true, verifyHost)), m_ignoreTransport(XMLHelper::getAttrBool(e, false, ignoreTransport)), m_encoded(true), m_trust(nullptr) { const DOMElement* child = XMLHelper::getFirstChildElement(e, Subst); if (child && child->hasChildNodes()) { auto_ptr_char s(child->getFirstChild()->getNodeValue()); if (s.get() && *s.get()) { m_subst = s.get(); m_encoded = XMLHelper::getAttrBool(child, true, encoded); m_hashed = XMLHelper::getAttrString(child, nullptr, hashed); } } if (m_subst.empty()) { child = XMLHelper::getFirstChildElement(e, Regex); if (child && child->hasChildNodes() && child->hasAttributeNS(nullptr, match)) { m_match = XMLHelper::getAttrString(child, nullptr, match); auto_ptr_char repl(child->getFirstChild()->getNodeValue()); if (repl.get() && *repl.get()) m_regex = repl.get(); } } if (!m_ignoreTransport) { child = XMLHelper::getFirstChildElement(e, _TrustEngine); string t = XMLHelper::getAttrString(child, nullptr, _type); if (!t.empty()) { TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child); if (!dynamic_cast<X509TrustEngine*>(trust)) { delete trust; throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin."); } m_trust.reset(dynamic_cast<X509TrustEngine*>(trust)); m_dummyCR.reset(XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(DUMMY_CREDENTIAL_RESOLVER, nullptr)); } if (!m_trust.get() || !m_dummyCR.get()) throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin unless ignoreTransport is true."); } } Commit Message: CWE ID: CWE-347
DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e) : saml2md::DynamicMetadataProvider(e), MetadataProvider(e), m_verifyHost(XMLHelper::getAttrBool(e, true, verifyHost)), m_ignoreTransport(XMLHelper::getAttrBool(e, false, ignoreTransport)), m_encoded(true), m_trust(nullptr) { const DOMElement* child = XMLHelper::getFirstChildElement(e, Subst); if (child && child->hasChildNodes()) { auto_ptr_char s(child->getFirstChild()->getNodeValue()); if (s.get() && *s.get()) { m_subst = s.get(); m_encoded = XMLHelper::getAttrBool(child, true, encoded); m_hashed = XMLHelper::getAttrString(child, nullptr, hashed); } } if (m_subst.empty()) { child = XMLHelper::getFirstChildElement(e, Regex); if (child && child->hasChildNodes() && child->hasAttributeNS(nullptr, match)) { m_match = XMLHelper::getAttrString(child, nullptr, match); auto_ptr_char repl(child->getFirstChild()->getNodeValue()); if (repl.get() && *repl.get()) m_regex = repl.get(); } } if (!m_ignoreTransport) { child = XMLHelper::getFirstChildElement(e, _TrustEngine); string t = XMLHelper::getAttrString(child, nullptr, _type); if (!t.empty()) { TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child); if (!dynamic_cast<X509TrustEngine*>(trust)) { delete trust; throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin."); } m_trust.reset(dynamic_cast<X509TrustEngine*>(trust)); m_dummyCR.reset(XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(DUMMY_CREDENTIAL_RESOLVER, nullptr)); } if (!m_trust.get() || !m_dummyCR.get()) throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin unless ignoreTransport is true."); } }
164,623
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void unix_notinflight(struct file *fp) { struct sock *s = unix_get_socket(fp); if (s) { struct unix_sock *u = unix_sk(s); spin_lock(&unix_gc_lock); BUG_ON(list_empty(&u->link)); if (atomic_long_dec_and_test(&u->inflight)) list_del_init(&u->link); unix_tot_inflight--; spin_unlock(&unix_gc_lock); } } Commit Message: unix: properly account for FDs passed over unix sockets It is possible for a process to allocate and accumulate far more FDs than the process' limit by sending them over a unix socket then closing them to keep the process' fd count low. This change addresses this problem by keeping track of the number of FDs in flight per user and preventing non-privileged processes from having more FDs in flight than their configured FD limit. Reported-by: [email protected] Reported-by: Tetsuo Handa <[email protected]> Mitigates: CVE-2013-4312 (Linux 2.0+) Suggested-by: Linus Torvalds <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: Willy Tarreau <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119
void unix_notinflight(struct file *fp) { struct sock *s = unix_get_socket(fp); spin_lock(&unix_gc_lock); if (s) { struct unix_sock *u = unix_sk(s); BUG_ON(list_empty(&u->link)); if (atomic_long_dec_and_test(&u->inflight)) list_del_init(&u->link); unix_tot_inflight--; } fp->f_cred->user->unix_inflight--; spin_unlock(&unix_gc_lock); }
167,598
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HTMLScriptRunner::runScript(Element* script, const TextPosition& scriptStartPosition) { ASSERT(m_document); ASSERT(!hasParserBlockingScript()); { ScriptLoader* scriptLoader = toScriptLoaderIfPossible(script); ASSERT(scriptLoader); if (!scriptLoader) return; ASSERT(scriptLoader->isParserInserted()); if (!isExecutingScript()) Microtask::performCheckpoint(); InsertionPointRecord insertionPointRecord(m_host->inputStream()); NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel); scriptLoader->prepareScript(scriptStartPosition); if (!scriptLoader->willBeParserExecuted()) return; if (scriptLoader->willExecuteWhenDocumentFinishedParsing()) { requestDeferredScript(script); } else if (scriptLoader->readyToBeParserExecuted()) { if (m_scriptNestingLevel == 1) { m_parserBlockingScript.setElement(script); m_parserBlockingScript.setStartingPosition(scriptStartPosition); } else { ScriptSourceCode sourceCode(script->textContent(), documentURLForScriptExecution(m_document), scriptStartPosition); scriptLoader->executeScript(sourceCode); } } else { requestParsingBlockingScript(script); } } } Commit Message: Correctly keep track of isolates for microtask execution BUG=487155 [email protected] Review URL: https://codereview.chromium.org/1161823002 git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-254
void HTMLScriptRunner::runScript(Element* script, const TextPosition& scriptStartPosition) { ASSERT(m_document); ASSERT(!hasParserBlockingScript()); { ScriptLoader* scriptLoader = toScriptLoaderIfPossible(script); ASSERT(scriptLoader); if (!scriptLoader) return; ASSERT(scriptLoader->isParserInserted()); if (!isExecutingScript()) Microtask::performCheckpoint(V8PerIsolateData::mainThreadIsolate()); InsertionPointRecord insertionPointRecord(m_host->inputStream()); NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel); scriptLoader->prepareScript(scriptStartPosition); if (!scriptLoader->willBeParserExecuted()) return; if (scriptLoader->willExecuteWhenDocumentFinishedParsing()) { requestDeferredScript(script); } else if (scriptLoader->readyToBeParserExecuted()) { if (m_scriptNestingLevel == 1) { m_parserBlockingScript.setElement(script); m_parserBlockingScript.setStartingPosition(scriptStartPosition); } else { ScriptSourceCode sourceCode(script->textContent(), documentURLForScriptExecution(m_document), scriptStartPosition); scriptLoader->executeScript(sourceCode); } } else { requestParsingBlockingScript(script); } } }
171,947
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int phar_parse_zipfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, char **error) /* {{{ */ { phar_zip_dir_end locator; char buf[sizeof(locator) + 65536]; zend_long size; php_uint16 i; phar_archive_data *mydata = NULL; phar_entry_info entry = {0}; char *p = buf, *ext, *actual_alias = NULL; char *metadata = NULL; size = php_stream_tell(fp); if (size > sizeof(locator) + 65536) { /* seek to max comment length + end of central directory record */ size = sizeof(locator) + 65536; if (FAILURE == php_stream_seek(fp, -size, SEEK_END)) { php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: unable to search for end of central directory in zip-based phar \"%s\"", fname); } return FAILURE; } } else { php_stream_seek(fp, 0, SEEK_SET); } if (!php_stream_read(fp, buf, size)) { php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: unable to read in data to search for end of central directory in zip-based phar \"%s\"", fname); } return FAILURE; } while ((p=(char *) memchr(p + 1, 'P', (size_t) (size - (p + 1 - buf)))) != NULL) { if ((p - buf) + sizeof(locator) <= size && !memcmp(p + 1, "K\5\6", 3)) { memcpy((void *)&locator, (void *) p, sizeof(locator)); if (PHAR_GET_16(locator.centraldisk) != 0 || PHAR_GET_16(locator.disknumber) != 0) { /* split archives not handled */ php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: split archives spanning multiple zips cannot be processed in zip-based phar \"%s\"", fname); } return FAILURE; } if (PHAR_GET_16(locator.counthere) != PHAR_GET_16(locator.count)) { if (error) { spprintf(error, 4096, "phar error: corrupt zip archive, conflicting file count in end of central directory record in zip-based phar \"%s\"", fname); } php_stream_close(fp); return FAILURE; } mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); mydata->is_persistent = PHAR_G(persist); /* read in archive comment, if any */ if (PHAR_GET_16(locator.comment_len)) { metadata = p + sizeof(locator); if (PHAR_GET_16(locator.comment_len) != size - (metadata - buf)) { if (error) { spprintf(error, 4096, "phar error: corrupt zip archive, zip file comment truncated in zip-based phar \"%s\"", fname); } php_stream_close(fp); pefree(mydata, mydata->is_persistent); return FAILURE; } mydata->metadata_len = PHAR_GET_16(locator.comment_len); if (phar_parse_metadata(&metadata, &mydata->metadata, PHAR_GET_16(locator.comment_len)) == FAILURE) { mydata->metadata_len = 0; /* if not valid serialized data, it is a regular string */ ZVAL_NEW_STR(&mydata->metadata, zend_string_init(metadata, PHAR_GET_16(locator.comment_len), mydata->is_persistent)); } } else { ZVAL_UNDEF(&mydata->metadata); } goto foundit; } } php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: end of central directory not found in zip-based phar \"%s\"", fname); } return FAILURE; foundit: mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif mydata->is_zip = 1; mydata->fname_len = fname_len; ext = strrchr(mydata->fname, '/'); if (ext) { mydata->ext = memchr(ext, '.', (mydata->fname + fname_len) - ext); if (mydata->ext == ext) { mydata->ext = memchr(ext + 1, '.', (mydata->fname + fname_len) - ext - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + fname_len) - mydata->ext; } } /* clean up on big-endian systems */ /* seek to central directory */ php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET); /* read in central directory */ zend_hash_init(&mydata->manifest, PHAR_GET_16(locator.count), zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->virtual_dirs, PHAR_GET_16(locator.count) * 2, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); entry.phar = mydata; entry.is_zip = 1; entry.fp_type = PHAR_FP; entry.is_persistent = mydata->is_persistent; #define PHAR_ZIP_FAIL_FREE(errmsg, save) \ zend_hash_destroy(&mydata->manifest); \ mydata->manifest.u.flags = 0; \ zend_hash_destroy(&mydata->mounted_dirs); \ mydata->mounted_dirs.u.flags = 0; \ zend_hash_destroy(&mydata->virtual_dirs); \ mydata->virtual_dirs.u.flags = 0; \ php_stream_close(fp); \ zval_dtor(&mydata->metadata); \ if (mydata->signature) { \ efree(mydata->signature); \ } \ if (error) { \ spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \ } \ pefree(mydata->fname, mydata->is_persistent); \ if (mydata->alias) { \ pefree(mydata->alias, mydata->is_persistent); \ } \ pefree(mydata, mydata->is_persistent); \ efree(save); \ return FAILURE; #define PHAR_ZIP_FAIL(errmsg) \ zend_hash_destroy(&mydata->manifest); \ mydata->manifest.u.flags = 0; \ zend_hash_destroy(&mydata->mounted_dirs); \ mydata->mounted_dirs.u.flags = 0; \ zend_hash_destroy(&mydata->virtual_dirs); \ mydata->virtual_dirs.u.flags = 0; \ php_stream_close(fp); \ zval_dtor(&mydata->metadata); \ if (mydata->signature) { \ efree(mydata->signature); \ } \ if (error) { \ spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \ } \ pefree(mydata->fname, mydata->is_persistent); \ if (mydata->alias) { \ pefree(mydata->alias, mydata->is_persistent); \ } \ pefree(mydata, mydata->is_persistent); \ return FAILURE; /* add each central directory item to the manifest */ for (i = 0; i < PHAR_GET_16(locator.count); ++i) { phar_zip_central_dir_file zipentry; zend_off_t beforeus = php_stream_tell(fp); if (sizeof(zipentry) != php_stream_read(fp, (char *) &zipentry, sizeof(zipentry))) { PHAR_ZIP_FAIL("unable to read central directory entry, truncated"); } /* clean up for bigendian systems */ if (memcmp("PK\1\2", zipentry.signature, 4)) { /* corrupted entry */ PHAR_ZIP_FAIL("corrupted central directory entry, no magic signature"); } if (entry.is_persistent) { entry.manifest_pos = i; } entry.compressed_filesize = PHAR_GET_32(zipentry.compsize); entry.uncompressed_filesize = PHAR_GET_32(zipentry.uncompsize); entry.crc32 = PHAR_GET_32(zipentry.crc32); /* do not PHAR_GET_16 either on the next line */ entry.timestamp = phar_zip_d2u_time(zipentry.timestamp, zipentry.datestamp); entry.flags = PHAR_ENT_PERM_DEF_FILE; entry.header_offset = PHAR_GET_32(zipentry.offset); entry.offset = entry.offset_abs = PHAR_GET_32(zipentry.offset) + sizeof(phar_zip_file_header) + PHAR_GET_16(zipentry.filename_len) + PHAR_GET_16(zipentry.extra_len); if (PHAR_GET_16(zipentry.flags) & PHAR_ZIP_FLAG_ENCRYPTED) { PHAR_ZIP_FAIL("Cannot process encrypted zip files"); } if (!PHAR_GET_16(zipentry.filename_len)) { PHAR_ZIP_FAIL("Cannot process zips created from stdin (zero-length filename)"); } entry.filename_len = PHAR_GET_16(zipentry.filename_len); entry.filename = (char *) pemalloc(entry.filename_len + 1, entry.is_persistent); if (entry.filename_len != php_stream_read(fp, entry.filename, entry.filename_len)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in filename from central directory, truncated"); } entry.filename[entry.filename_len] = '\0'; if (entry.filename[entry.filename_len - 1] == '/') { entry.is_dir = 1; if(entry.filename_len > 1) { entry.filename_len--; } entry.flags |= PHAR_ENT_PERM_DEF_DIR; } else { entry.is_dir = 0; } if (entry.filename_len == sizeof(".phar/signature.bin")-1 && !strncmp(entry.filename, ".phar/signature.bin", sizeof(".phar/signature.bin")-1)) { size_t read; php_stream *sigfile; zend_off_t now; char *sig; now = php_stream_tell(fp); pefree(entry.filename, entry.is_persistent); sigfile = php_stream_fopen_tmpfile(); if (!sigfile) { PHAR_ZIP_FAIL("couldn't open temporary file"); } php_stream_seek(fp, 0, SEEK_SET); /* copy file contents + local headers and zip comment, if any, to be hashed for signature */ php_stream_copy_to_stream_ex(fp, sigfile, entry.header_offset, NULL); /* seek to central directory */ php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET); /* copy central directory header */ php_stream_copy_to_stream_ex(fp, sigfile, beforeus - PHAR_GET_32(locator.cdir_offset), NULL); if (metadata) { php_stream_write(sigfile, metadata, PHAR_GET_16(locator.comment_len)); } php_stream_seek(fp, sizeof(phar_zip_file_header) + entry.header_offset + entry.filename_len + PHAR_GET_16(zipentry.extra_len), SEEK_SET); sig = (char *) emalloc(entry.uncompressed_filesize); read = php_stream_read(fp, sig, entry.uncompressed_filesize); if (read != entry.uncompressed_filesize) { php_stream_close(sigfile); efree(sig); PHAR_ZIP_FAIL("signature cannot be read"); } mydata->sig_flags = PHAR_GET_32(sig); if (FAILURE == phar_verify_signature(sigfile, php_stream_tell(sigfile), mydata->sig_flags, sig + 8, entry.uncompressed_filesize - 8, fname, &mydata->signature, &mydata->sig_len, error)) { efree(sig); if (error) { char *save; php_stream_close(sigfile); spprintf(&save, 4096, "signature cannot be verified: %s", *error); efree(*error); PHAR_ZIP_FAIL_FREE(save, save); } else { php_stream_close(sigfile); PHAR_ZIP_FAIL("signature cannot be verified"); } } php_stream_close(sigfile); efree(sig); /* signature checked out, let's ensure this is the last file in the phar */ if (i != PHAR_GET_16(locator.count) - 1) { PHAR_ZIP_FAIL("entries exist after signature, invalid phar"); } continue; } phar_add_virtual_dirs(mydata, entry.filename, entry.filename_len); if (PHAR_GET_16(zipentry.extra_len)) { zend_off_t loc = php_stream_tell(fp); if (FAILURE == phar_zip_process_extra(fp, &entry, PHAR_GET_16(zipentry.extra_len))) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("Unable to process extra field header for file in central directory"); } php_stream_seek(fp, loc + PHAR_GET_16(zipentry.extra_len), SEEK_SET); } switch (PHAR_GET_16(zipentry.compressed)) { case PHAR_ZIP_COMP_NONE : /* compression flag already set */ break; case PHAR_ZIP_COMP_DEFLATE : entry.flags |= PHAR_ENT_COMPRESSED_GZ; if (!PHAR_G(has_zlib)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("zlib extension is required"); } break; case PHAR_ZIP_COMP_BZIP2 : entry.flags |= PHAR_ENT_COMPRESSED_BZ2; if (!PHAR_G(has_bz2)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("bzip2 extension is required"); } break; case 1 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Shrunk) used in this zip"); case 2 : case 3 : case 4 : case 5 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Reduce) used in this zip"); case 6 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Implode) used in this zip"); case 7 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Tokenize) used in this zip"); case 9 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Deflate64) used in this zip"); case 10 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (PKWare Implode/old IBM TERSE) used in this zip"); case 14 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (LZMA) used in this zip"); case 18 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (IBM TERSE) used in this zip"); case 19 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (IBM LZ77) used in this zip"); case 97 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (WavPack) used in this zip"); case 98 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (PPMd) used in this zip"); default : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (unknown) used in this zip"); } /* get file metadata */ if (PHAR_GET_16(zipentry.comment_len)) { if (PHAR_GET_16(zipentry.comment_len) != php_stream_read(fp, buf, PHAR_GET_16(zipentry.comment_len))) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in file comment, truncated"); } p = buf; entry.metadata_len = PHAR_GET_16(zipentry.comment_len); if (phar_parse_metadata(&p, &(entry.metadata), PHAR_GET_16(zipentry.comment_len)) == FAILURE) { entry.metadata_len = 0; /* if not valid serialized data, it is a regular string */ ZVAL_NEW_STR(&entry.metadata, zend_string_init(buf, PHAR_GET_16(zipentry.comment_len), entry.is_persistent)); } } else { ZVAL_UNDEF(&entry.metadata); } if (!actual_alias && entry.filename_len == sizeof(".phar/alias.txt")-1 && !strncmp(entry.filename, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { php_stream_filter *filter; zend_off_t saveloc; /* verify local file header */ phar_zip_file_header local; /* archive alias found */ saveloc = php_stream_tell(fp); php_stream_seek(fp, PHAR_GET_32(zipentry.offset), SEEK_SET); if (sizeof(local) != php_stream_read(fp, (char *) &local, sizeof(local))) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (cannot read local file header for alias)"); } /* verify local header */ if (entry.filename_len != PHAR_GET_16(local.filename_len) || entry.crc32 != PHAR_GET_32(local.crc32) || entry.uncompressed_filesize != PHAR_GET_32(local.uncompsize) || entry.compressed_filesize != PHAR_GET_32(local.compsize)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (local header of alias does not match central directory)"); } /* construct actual offset to file start - local extra_len can be different from central extra_len */ entry.offset = entry.offset_abs = sizeof(local) + entry.header_offset + PHAR_GET_16(local.filename_len) + PHAR_GET_16(local.extra_len); php_stream_seek(fp, entry.offset, SEEK_SET); /* these next lines should be for php < 5.2.6 after 5.3 filters are fixed */ fp->writepos = 0; fp->readpos = 0; php_stream_seek(fp, entry.offset, SEEK_SET); fp->writepos = 0; fp->readpos = 0; /* the above lines should be for php < 5.2.6 after 5.3 filters are fixed */ mydata->alias_len = entry.uncompressed_filesize; if (entry.flags & PHAR_ENT_COMPRESSED_GZ) { filter = php_stream_filter_create("zlib.inflate", NULL, php_stream_is_persistent(fp)); if (!filter) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to decompress alias, zlib filter creation failed"); } php_stream_filter_append(&fp->readfilters, filter); { zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0); if (str) { entry.uncompressed_filesize = ZSTR_LEN(str); actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str)); zend_string_release(str); } else { actual_alias = NULL; entry.uncompressed_filesize = 0; } } if (!entry.uncompressed_filesize || !actual_alias) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, truncated"); } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1); } else if (entry.flags & PHAR_ENT_COMPRESSED_BZ2) { filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp)); if (!filter) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, bzip2 filter creation failed"); } php_stream_filter_append(&fp->readfilters, filter); { zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0); if (str) { entry.uncompressed_filesize = ZSTR_LEN(str); actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str)); zend_string_release(str); } else { actual_alias = NULL; entry.uncompressed_filesize = 0; } } if (!entry.uncompressed_filesize || !actual_alias) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, truncated"); } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1); } else { { zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0); if (str) { entry.uncompressed_filesize = ZSTR_LEN(str); actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str)); zend_string_release(str); } else { actual_alias = NULL; entry.uncompressed_filesize = 0; } } if (!entry.uncompressed_filesize || !actual_alias) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, truncated"); } } /* return to central directory parsing */ php_stream_seek(fp, saveloc, SEEK_SET); } phar_set_inode(&entry); zend_hash_str_add_mem(&mydata->manifest, entry.filename, entry.filename_len, (void *)&entry, sizeof(phar_entry_info)); } mydata->fp = fp; if (zend_hash_str_exists(&(mydata->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1)) { mydata->is_data = 0; } else { mydata->is_data = 1; } zend_hash_str_add_ptr(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len, mydata); if (actual_alias) { phar_archive_data *fd_ptr; if (!phar_validate_alias(actual_alias, mydata->alias_len)) { if (error) { spprintf(error, 4096, "phar error: invalid alias \"%s\" in zip-based phar \"%s\"", actual_alias, fname); } efree(actual_alias); zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len); return FAILURE; } mydata->is_temporary_alias = 0; if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len))) { if (SUCCESS != phar_free_alias(fd_ptr, actual_alias, mydata->alias_len)) { if (error) { spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with implicit alias, alias is already in use", fname); } efree(actual_alias); zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len); return FAILURE; } } mydata->alias = entry.is_persistent ? pestrndup(actual_alias, mydata->alias_len, 1) : actual_alias; if (entry.is_persistent) { efree(actual_alias); } zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len, mydata); } else { phar_archive_data *fd_ptr; if (alias_len) { if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len))) { if (SUCCESS != phar_free_alias(fd_ptr, alias, alias_len)) { if (error) { spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with explicit alias, alias is already in use", fname); } zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len); return FAILURE; } } zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len, mydata); mydata->alias = pestrndup(alias, alias_len, mydata->is_persistent); mydata->alias_len = alias_len; } else { mydata->alias = pestrndup(mydata->fname, fname_len, mydata->is_persistent); mydata->alias_len = fname_len; } mydata->is_temporary_alias = 1; } if (pphar) { *pphar = mydata; } return SUCCESS; } /* }}} */ Commit Message: Fix bug #72928 - Out of bound when verify signature of zip phar in phar_parse_zipfile (cherry picked from commit 19484ab77466f99c78fc0e677f7e03da0584d6a2) CWE ID: CWE-119
int phar_parse_zipfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, char **error) /* {{{ */ { phar_zip_dir_end locator; char buf[sizeof(locator) + 65536]; zend_long size; php_uint16 i; phar_archive_data *mydata = NULL; phar_entry_info entry = {0}; char *p = buf, *ext, *actual_alias = NULL; char *metadata = NULL; size = php_stream_tell(fp); if (size > sizeof(locator) + 65536) { /* seek to max comment length + end of central directory record */ size = sizeof(locator) + 65536; if (FAILURE == php_stream_seek(fp, -size, SEEK_END)) { php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: unable to search for end of central directory in zip-based phar \"%s\"", fname); } return FAILURE; } } else { php_stream_seek(fp, 0, SEEK_SET); } if (!php_stream_read(fp, buf, size)) { php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: unable to read in data to search for end of central directory in zip-based phar \"%s\"", fname); } return FAILURE; } while ((p=(char *) memchr(p + 1, 'P', (size_t) (size - (p + 1 - buf)))) != NULL) { if ((p - buf) + sizeof(locator) <= size && !memcmp(p + 1, "K\5\6", 3)) { memcpy((void *)&locator, (void *) p, sizeof(locator)); if (PHAR_GET_16(locator.centraldisk) != 0 || PHAR_GET_16(locator.disknumber) != 0) { /* split archives not handled */ php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: split archives spanning multiple zips cannot be processed in zip-based phar \"%s\"", fname); } return FAILURE; } if (PHAR_GET_16(locator.counthere) != PHAR_GET_16(locator.count)) { if (error) { spprintf(error, 4096, "phar error: corrupt zip archive, conflicting file count in end of central directory record in zip-based phar \"%s\"", fname); } php_stream_close(fp); return FAILURE; } mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); mydata->is_persistent = PHAR_G(persist); /* read in archive comment, if any */ if (PHAR_GET_16(locator.comment_len)) { metadata = p + sizeof(locator); if (PHAR_GET_16(locator.comment_len) != size - (metadata - buf)) { if (error) { spprintf(error, 4096, "phar error: corrupt zip archive, zip file comment truncated in zip-based phar \"%s\"", fname); } php_stream_close(fp); pefree(mydata, mydata->is_persistent); return FAILURE; } mydata->metadata_len = PHAR_GET_16(locator.comment_len); if (phar_parse_metadata(&metadata, &mydata->metadata, PHAR_GET_16(locator.comment_len)) == FAILURE) { mydata->metadata_len = 0; /* if not valid serialized data, it is a regular string */ ZVAL_NEW_STR(&mydata->metadata, zend_string_init(metadata, PHAR_GET_16(locator.comment_len), mydata->is_persistent)); } } else { ZVAL_UNDEF(&mydata->metadata); } goto foundit; } } php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: end of central directory not found in zip-based phar \"%s\"", fname); } return FAILURE; foundit: mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif mydata->is_zip = 1; mydata->fname_len = fname_len; ext = strrchr(mydata->fname, '/'); if (ext) { mydata->ext = memchr(ext, '.', (mydata->fname + fname_len) - ext); if (mydata->ext == ext) { mydata->ext = memchr(ext + 1, '.', (mydata->fname + fname_len) - ext - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + fname_len) - mydata->ext; } } /* clean up on big-endian systems */ /* seek to central directory */ php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET); /* read in central directory */ zend_hash_init(&mydata->manifest, PHAR_GET_16(locator.count), zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->virtual_dirs, PHAR_GET_16(locator.count) * 2, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); entry.phar = mydata; entry.is_zip = 1; entry.fp_type = PHAR_FP; entry.is_persistent = mydata->is_persistent; #define PHAR_ZIP_FAIL_FREE(errmsg, save) \ zend_hash_destroy(&mydata->manifest); \ mydata->manifest.u.flags = 0; \ zend_hash_destroy(&mydata->mounted_dirs); \ mydata->mounted_dirs.u.flags = 0; \ zend_hash_destroy(&mydata->virtual_dirs); \ mydata->virtual_dirs.u.flags = 0; \ php_stream_close(fp); \ zval_dtor(&mydata->metadata); \ if (mydata->signature) { \ efree(mydata->signature); \ } \ if (error) { \ spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \ } \ pefree(mydata->fname, mydata->is_persistent); \ if (mydata->alias) { \ pefree(mydata->alias, mydata->is_persistent); \ } \ pefree(mydata, mydata->is_persistent); \ efree(save); \ return FAILURE; #define PHAR_ZIP_FAIL(errmsg) \ zend_hash_destroy(&mydata->manifest); \ mydata->manifest.u.flags = 0; \ zend_hash_destroy(&mydata->mounted_dirs); \ mydata->mounted_dirs.u.flags = 0; \ zend_hash_destroy(&mydata->virtual_dirs); \ mydata->virtual_dirs.u.flags = 0; \ php_stream_close(fp); \ zval_dtor(&mydata->metadata); \ if (mydata->signature) { \ efree(mydata->signature); \ } \ if (error) { \ spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \ } \ pefree(mydata->fname, mydata->is_persistent); \ if (mydata->alias) { \ pefree(mydata->alias, mydata->is_persistent); \ } \ pefree(mydata, mydata->is_persistent); \ return FAILURE; /* add each central directory item to the manifest */ for (i = 0; i < PHAR_GET_16(locator.count); ++i) { phar_zip_central_dir_file zipentry; zend_off_t beforeus = php_stream_tell(fp); if (sizeof(zipentry) != php_stream_read(fp, (char *) &zipentry, sizeof(zipentry))) { PHAR_ZIP_FAIL("unable to read central directory entry, truncated"); } /* clean up for bigendian systems */ if (memcmp("PK\1\2", zipentry.signature, 4)) { /* corrupted entry */ PHAR_ZIP_FAIL("corrupted central directory entry, no magic signature"); } if (entry.is_persistent) { entry.manifest_pos = i; } entry.compressed_filesize = PHAR_GET_32(zipentry.compsize); entry.uncompressed_filesize = PHAR_GET_32(zipentry.uncompsize); entry.crc32 = PHAR_GET_32(zipentry.crc32); /* do not PHAR_GET_16 either on the next line */ entry.timestamp = phar_zip_d2u_time(zipentry.timestamp, zipentry.datestamp); entry.flags = PHAR_ENT_PERM_DEF_FILE; entry.header_offset = PHAR_GET_32(zipentry.offset); entry.offset = entry.offset_abs = PHAR_GET_32(zipentry.offset) + sizeof(phar_zip_file_header) + PHAR_GET_16(zipentry.filename_len) + PHAR_GET_16(zipentry.extra_len); if (PHAR_GET_16(zipentry.flags) & PHAR_ZIP_FLAG_ENCRYPTED) { PHAR_ZIP_FAIL("Cannot process encrypted zip files"); } if (!PHAR_GET_16(zipentry.filename_len)) { PHAR_ZIP_FAIL("Cannot process zips created from stdin (zero-length filename)"); } entry.filename_len = PHAR_GET_16(zipentry.filename_len); entry.filename = (char *) pemalloc(entry.filename_len + 1, entry.is_persistent); if (entry.filename_len != php_stream_read(fp, entry.filename, entry.filename_len)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in filename from central directory, truncated"); } entry.filename[entry.filename_len] = '\0'; if (entry.filename[entry.filename_len - 1] == '/') { entry.is_dir = 1; if(entry.filename_len > 1) { entry.filename_len--; } entry.flags |= PHAR_ENT_PERM_DEF_DIR; } else { entry.is_dir = 0; } if (entry.filename_len == sizeof(".phar/signature.bin")-1 && !strncmp(entry.filename, ".phar/signature.bin", sizeof(".phar/signature.bin")-1)) { size_t read; php_stream *sigfile; zend_off_t now; char *sig; now = php_stream_tell(fp); pefree(entry.filename, entry.is_persistent); sigfile = php_stream_fopen_tmpfile(); if (!sigfile) { PHAR_ZIP_FAIL("couldn't open temporary file"); } php_stream_seek(fp, 0, SEEK_SET); /* copy file contents + local headers and zip comment, if any, to be hashed for signature */ php_stream_copy_to_stream_ex(fp, sigfile, entry.header_offset, NULL); /* seek to central directory */ php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET); /* copy central directory header */ php_stream_copy_to_stream_ex(fp, sigfile, beforeus - PHAR_GET_32(locator.cdir_offset), NULL); if (metadata) { php_stream_write(sigfile, metadata, PHAR_GET_16(locator.comment_len)); } php_stream_seek(fp, sizeof(phar_zip_file_header) + entry.header_offset + entry.filename_len + PHAR_GET_16(zipentry.extra_len), SEEK_SET); sig = (char *) emalloc(entry.uncompressed_filesize); read = php_stream_read(fp, sig, entry.uncompressed_filesize); if (read != entry.uncompressed_filesize || read <= 8) { php_stream_close(sigfile); efree(sig); PHAR_ZIP_FAIL("signature cannot be read"); } mydata->sig_flags = PHAR_GET_32(sig); if (FAILURE == phar_verify_signature(sigfile, php_stream_tell(sigfile), mydata->sig_flags, sig + 8, entry.uncompressed_filesize - 8, fname, &mydata->signature, &mydata->sig_len, error)) { efree(sig); if (error) { char *save; php_stream_close(sigfile); spprintf(&save, 4096, "signature cannot be verified: %s", *error); efree(*error); PHAR_ZIP_FAIL_FREE(save, save); } else { php_stream_close(sigfile); PHAR_ZIP_FAIL("signature cannot be verified"); } } php_stream_close(sigfile); efree(sig); /* signature checked out, let's ensure this is the last file in the phar */ if (i != PHAR_GET_16(locator.count) - 1) { PHAR_ZIP_FAIL("entries exist after signature, invalid phar"); } continue; } phar_add_virtual_dirs(mydata, entry.filename, entry.filename_len); if (PHAR_GET_16(zipentry.extra_len)) { zend_off_t loc = php_stream_tell(fp); if (FAILURE == phar_zip_process_extra(fp, &entry, PHAR_GET_16(zipentry.extra_len))) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("Unable to process extra field header for file in central directory"); } php_stream_seek(fp, loc + PHAR_GET_16(zipentry.extra_len), SEEK_SET); } switch (PHAR_GET_16(zipentry.compressed)) { case PHAR_ZIP_COMP_NONE : /* compression flag already set */ break; case PHAR_ZIP_COMP_DEFLATE : entry.flags |= PHAR_ENT_COMPRESSED_GZ; if (!PHAR_G(has_zlib)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("zlib extension is required"); } break; case PHAR_ZIP_COMP_BZIP2 : entry.flags |= PHAR_ENT_COMPRESSED_BZ2; if (!PHAR_G(has_bz2)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("bzip2 extension is required"); } break; case 1 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Shrunk) used in this zip"); case 2 : case 3 : case 4 : case 5 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Reduce) used in this zip"); case 6 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Implode) used in this zip"); case 7 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Tokenize) used in this zip"); case 9 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Deflate64) used in this zip"); case 10 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (PKWare Implode/old IBM TERSE) used in this zip"); case 14 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (LZMA) used in this zip"); case 18 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (IBM TERSE) used in this zip"); case 19 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (IBM LZ77) used in this zip"); case 97 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (WavPack) used in this zip"); case 98 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (PPMd) used in this zip"); default : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (unknown) used in this zip"); } /* get file metadata */ if (PHAR_GET_16(zipentry.comment_len)) { if (PHAR_GET_16(zipentry.comment_len) != php_stream_read(fp, buf, PHAR_GET_16(zipentry.comment_len))) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in file comment, truncated"); } p = buf; entry.metadata_len = PHAR_GET_16(zipentry.comment_len); if (phar_parse_metadata(&p, &(entry.metadata), PHAR_GET_16(zipentry.comment_len)) == FAILURE) { entry.metadata_len = 0; /* if not valid serialized data, it is a regular string */ ZVAL_NEW_STR(&entry.metadata, zend_string_init(buf, PHAR_GET_16(zipentry.comment_len), entry.is_persistent)); } } else { ZVAL_UNDEF(&entry.metadata); } if (!actual_alias && entry.filename_len == sizeof(".phar/alias.txt")-1 && !strncmp(entry.filename, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { php_stream_filter *filter; zend_off_t saveloc; /* verify local file header */ phar_zip_file_header local; /* archive alias found */ saveloc = php_stream_tell(fp); php_stream_seek(fp, PHAR_GET_32(zipentry.offset), SEEK_SET); if (sizeof(local) != php_stream_read(fp, (char *) &local, sizeof(local))) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (cannot read local file header for alias)"); } /* verify local header */ if (entry.filename_len != PHAR_GET_16(local.filename_len) || entry.crc32 != PHAR_GET_32(local.crc32) || entry.uncompressed_filesize != PHAR_GET_32(local.uncompsize) || entry.compressed_filesize != PHAR_GET_32(local.compsize)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (local header of alias does not match central directory)"); } /* construct actual offset to file start - local extra_len can be different from central extra_len */ entry.offset = entry.offset_abs = sizeof(local) + entry.header_offset + PHAR_GET_16(local.filename_len) + PHAR_GET_16(local.extra_len); php_stream_seek(fp, entry.offset, SEEK_SET); /* these next lines should be for php < 5.2.6 after 5.3 filters are fixed */ fp->writepos = 0; fp->readpos = 0; php_stream_seek(fp, entry.offset, SEEK_SET); fp->writepos = 0; fp->readpos = 0; /* the above lines should be for php < 5.2.6 after 5.3 filters are fixed */ mydata->alias_len = entry.uncompressed_filesize; if (entry.flags & PHAR_ENT_COMPRESSED_GZ) { filter = php_stream_filter_create("zlib.inflate", NULL, php_stream_is_persistent(fp)); if (!filter) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to decompress alias, zlib filter creation failed"); } php_stream_filter_append(&fp->readfilters, filter); { zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0); if (str) { entry.uncompressed_filesize = ZSTR_LEN(str); actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str)); zend_string_release(str); } else { actual_alias = NULL; entry.uncompressed_filesize = 0; } } if (!entry.uncompressed_filesize || !actual_alias) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, truncated"); } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1); } else if (entry.flags & PHAR_ENT_COMPRESSED_BZ2) { filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp)); if (!filter) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, bzip2 filter creation failed"); } php_stream_filter_append(&fp->readfilters, filter); { zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0); if (str) { entry.uncompressed_filesize = ZSTR_LEN(str); actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str)); zend_string_release(str); } else { actual_alias = NULL; entry.uncompressed_filesize = 0; } } if (!entry.uncompressed_filesize || !actual_alias) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, truncated"); } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1); } else { { zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0); if (str) { entry.uncompressed_filesize = ZSTR_LEN(str); actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str)); zend_string_release(str); } else { actual_alias = NULL; entry.uncompressed_filesize = 0; } } if (!entry.uncompressed_filesize || !actual_alias) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, truncated"); } } /* return to central directory parsing */ php_stream_seek(fp, saveloc, SEEK_SET); } phar_set_inode(&entry); zend_hash_str_add_mem(&mydata->manifest, entry.filename, entry.filename_len, (void *)&entry, sizeof(phar_entry_info)); } mydata->fp = fp; if (zend_hash_str_exists(&(mydata->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1)) { mydata->is_data = 0; } else { mydata->is_data = 1; } zend_hash_str_add_ptr(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len, mydata); if (actual_alias) { phar_archive_data *fd_ptr; if (!phar_validate_alias(actual_alias, mydata->alias_len)) { if (error) { spprintf(error, 4096, "phar error: invalid alias \"%s\" in zip-based phar \"%s\"", actual_alias, fname); } efree(actual_alias); zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len); return FAILURE; } mydata->is_temporary_alias = 0; if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len))) { if (SUCCESS != phar_free_alias(fd_ptr, actual_alias, mydata->alias_len)) { if (error) { spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with implicit alias, alias is already in use", fname); } efree(actual_alias); zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len); return FAILURE; } } mydata->alias = entry.is_persistent ? pestrndup(actual_alias, mydata->alias_len, 1) : actual_alias; if (entry.is_persistent) { efree(actual_alias); } zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len, mydata); } else { phar_archive_data *fd_ptr; if (alias_len) { if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len))) { if (SUCCESS != phar_free_alias(fd_ptr, alias, alias_len)) { if (error) { spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with explicit alias, alias is already in use", fname); } zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len); return FAILURE; } } zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len, mydata); mydata->alias = pestrndup(alias, alias_len, mydata->is_persistent); mydata->alias_len = alias_len; } else { mydata->alias = pestrndup(mydata->fname, fname_len, mydata->is_persistent); mydata->alias_len = fname_len; } mydata->is_temporary_alias = 1; } if (pphar) { *pphar = mydata; } return SUCCESS; } /* }}} */
166,935
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: exsltFuncFunctionFunction (xmlXPathParserContextPtr ctxt, int nargs) { xmlXPathObjectPtr oldResult, ret; exsltFuncData *data; exsltFuncFunctionData *func; xmlNodePtr paramNode, oldInsert, fake; int oldBase; xsltStackElemPtr params = NULL, param; xsltTransformContextPtr tctxt = xsltXPathGetTransformContext(ctxt); int i, notSet; struct objChain { struct objChain *next; xmlXPathObjectPtr obj; }; struct objChain *savedObjChain = NULL, *savedObj; /* * retrieve func:function template */ data = (exsltFuncData *) xsltGetExtData (tctxt, EXSLT_FUNCTIONS_NAMESPACE); oldResult = data->result; data->result = NULL; func = (exsltFuncFunctionData*) xmlHashLookup2 (data->funcs, ctxt->context->functionURI, ctxt->context->function); /* * params handling */ if (nargs > func->nargs) { xsltGenericError(xsltGenericErrorContext, "{%s}%s: called with too many arguments\n", ctxt->context->functionURI, ctxt->context->function); ctxt->error = XPATH_INVALID_ARITY; return; } if (func->content != NULL) { paramNode = func->content->prev; } else paramNode = NULL; if ((paramNode == NULL) && (func->nargs != 0)) { xsltGenericError(xsltGenericErrorContext, "exsltFuncFunctionFunction: nargs != 0 and " "param == NULL\n"); return; } if (tctxt->funcLevel > MAX_FUNC_RECURSION) { xsltGenericError(xsltGenericErrorContext, "{%s}%s: detected a recursion\n", ctxt->context->functionURI, ctxt->context->function); ctxt->error = XPATH_MEMORY_ERROR; return; } tctxt->funcLevel++; /* * We have a problem with the evaluation of function parameters. * The original library code did not evaluate XPath expressions until * the last moment. After version 1.1.17 of the libxslt, the logic * of other parts of the library was changed, and the evaluation of * XPath expressions within parameters now takes place as soon as the * parameter is parsed/evaluated (xsltParseStylesheetCallerParam). * This means that the parameters need to be evaluated in lexical * order (since a variable is "in scope" as soon as it is declared). * However, on entry to this routine, the values (from the caller) are * in reverse order (held on the XPath context variable stack). To * accomplish what is required, I have added code to pop the XPath * objects off of the stack at the beginning and save them, then use * them (in the reverse order) as the params are evaluated. This * requires an xmlMalloc/xmlFree for each param set by the caller, * which is not very nice. There is probably a much better solution * (like change other code to delay the evaluation). */ /* * In order to give the function params and variables a new 'scope' * we change varsBase in the context. */ oldBase = tctxt->varsBase; tctxt->varsBase = tctxt->varsNr; /* If there are any parameters */ if (paramNode != NULL) { /* Fetch the stored argument values from the caller */ for (i = 0; i < nargs; i++) { savedObj = xmlMalloc(sizeof(struct objChain)); savedObj->next = savedObjChain; savedObj->obj = valuePop(ctxt); savedObjChain = savedObj; } /* * Prepare to process params in reverse order. First, go to * the beginning of the param chain. */ for (i = 1; i <= func->nargs; i++) { if (paramNode->prev == NULL) break; paramNode = paramNode->prev; } /* * i has total # params found, nargs is number which are present * as arguments from the caller * Calculate the number of un-set parameters */ notSet = func->nargs - nargs; for (; i > 0; i--) { param = xsltParseStylesheetCallerParam (tctxt, paramNode); if (i > notSet) { /* if parameter value set */ param->computed = 1; if (param->value != NULL) xmlXPathFreeObject(param->value); savedObj = savedObjChain; /* get next val from chain */ param->value = savedObj->obj; savedObjChain = savedObjChain->next; xmlFree(savedObj); } xsltLocalVariablePush(tctxt, param, -1); param->next = params; params = param; paramNode = paramNode->next; } } /* * actual processing */ fake = xmlNewDocNode(tctxt->output, NULL, (const xmlChar *)"fake", NULL); oldInsert = tctxt->insert; tctxt->insert = fake; xsltApplyOneTemplate (tctxt, xmlXPathGetContextNode(ctxt), func->content, NULL, NULL); xsltLocalVariablePop(tctxt, tctxt->varsBase, -2); tctxt->insert = oldInsert; tctxt->varsBase = oldBase; /* restore original scope */ if (params != NULL) xsltFreeStackElemList(params); if (data->error != 0) goto error; if (data->result != NULL) { ret = data->result; } else ret = xmlXPathNewCString(""); data->result = oldResult; /* * It is an error if the instantiation of the template results in * the generation of result nodes. */ if (fake->children != NULL) { #ifdef LIBXML_DEBUG_ENABLED xmlDebugDumpNode (stderr, fake, 1); #endif xsltGenericError(xsltGenericErrorContext, "{%s}%s: cannot write to result tree while " "executing a function\n", ctxt->context->functionURI, ctxt->context->function); xmlFreeNode(fake); goto error; } xmlFreeNode(fake); valuePush(ctxt, ret); error: /* * IMPORTANT: This enables previously tree fragments marked as * being results of a function, to be garbage-collected after * the calling process exits. */ xsltExtensionInstructionResultFinalize(tctxt); tctxt->funcLevel--; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
exsltFuncFunctionFunction (xmlXPathParserContextPtr ctxt, int nargs) { xmlXPathObjectPtr oldResult, ret; exsltFuncData *data; exsltFuncFunctionData *func; xmlNodePtr paramNode, oldInsert, fake; int oldBase; xsltStackElemPtr params = NULL, param; xsltTransformContextPtr tctxt = xsltXPathGetTransformContext(ctxt); int i, notSet; struct objChain { struct objChain *next; xmlXPathObjectPtr obj; }; struct objChain *savedObjChain = NULL, *savedObj; /* * retrieve func:function template */ data = (exsltFuncData *) xsltGetExtData (tctxt, EXSLT_FUNCTIONS_NAMESPACE); oldResult = data->result; data->result = NULL; func = (exsltFuncFunctionData*) xmlHashLookup2 (data->funcs, ctxt->context->functionURI, ctxt->context->function); if (func == NULL) { /* Should never happen */ xsltGenericError(xsltGenericErrorContext, "{%s}%s: not found\n", ctxt->context->functionURI, ctxt->context->function); ctxt->error = XPATH_UNKNOWN_FUNC_ERROR; return; } /* * params handling */ if (nargs > func->nargs) { xsltGenericError(xsltGenericErrorContext, "{%s}%s: called with too many arguments\n", ctxt->context->functionURI, ctxt->context->function); ctxt->error = XPATH_INVALID_ARITY; return; } if (func->content != NULL) { paramNode = func->content->prev; } else paramNode = NULL; if ((paramNode == NULL) && (func->nargs != 0)) { xsltGenericError(xsltGenericErrorContext, "exsltFuncFunctionFunction: nargs != 0 and " "param == NULL\n"); return; } if (tctxt->funcLevel > MAX_FUNC_RECURSION) { xsltGenericError(xsltGenericErrorContext, "{%s}%s: detected a recursion\n", ctxt->context->functionURI, ctxt->context->function); ctxt->error = XPATH_MEMORY_ERROR; return; } tctxt->funcLevel++; /* * We have a problem with the evaluation of function parameters. * The original library code did not evaluate XPath expressions until * the last moment. After version 1.1.17 of the libxslt, the logic * of other parts of the library was changed, and the evaluation of * XPath expressions within parameters now takes place as soon as the * parameter is parsed/evaluated (xsltParseStylesheetCallerParam). * This means that the parameters need to be evaluated in lexical * order (since a variable is "in scope" as soon as it is declared). * However, on entry to this routine, the values (from the caller) are * in reverse order (held on the XPath context variable stack). To * accomplish what is required, I have added code to pop the XPath * objects off of the stack at the beginning and save them, then use * them (in the reverse order) as the params are evaluated. This * requires an xmlMalloc/xmlFree for each param set by the caller, * which is not very nice. There is probably a much better solution * (like change other code to delay the evaluation). */ /* * In order to give the function params and variables a new 'scope' * we change varsBase in the context. */ oldBase = tctxt->varsBase; tctxt->varsBase = tctxt->varsNr; /* If there are any parameters */ if (paramNode != NULL) { /* Fetch the stored argument values from the caller */ for (i = 0; i < nargs; i++) { savedObj = xmlMalloc(sizeof(struct objChain)); savedObj->next = savedObjChain; savedObj->obj = valuePop(ctxt); savedObjChain = savedObj; } /* * Prepare to process params in reverse order. First, go to * the beginning of the param chain. */ for (i = 1; i <= func->nargs; i++) { if (paramNode->prev == NULL) break; paramNode = paramNode->prev; } /* * i has total # params found, nargs is number which are present * as arguments from the caller * Calculate the number of un-set parameters */ notSet = func->nargs - nargs; for (; i > 0; i--) { param = xsltParseStylesheetCallerParam (tctxt, paramNode); if (i > notSet) { /* if parameter value set */ param->computed = 1; if (param->value != NULL) xmlXPathFreeObject(param->value); savedObj = savedObjChain; /* get next val from chain */ param->value = savedObj->obj; savedObjChain = savedObjChain->next; xmlFree(savedObj); } xsltLocalVariablePush(tctxt, param, -1); param->next = params; params = param; paramNode = paramNode->next; } } /* * actual processing */ fake = xmlNewDocNode(tctxt->output, NULL, (const xmlChar *)"fake", NULL); oldInsert = tctxt->insert; tctxt->insert = fake; xsltApplyOneTemplate (tctxt, xmlXPathGetContextNode(ctxt), func->content, NULL, NULL); xsltLocalVariablePop(tctxt, tctxt->varsBase, -2); tctxt->insert = oldInsert; tctxt->varsBase = oldBase; /* restore original scope */ if (params != NULL) xsltFreeStackElemList(params); if (data->error != 0) goto error; if (data->result != NULL) { ret = data->result; } else ret = xmlXPathNewCString(""); data->result = oldResult; /* * It is an error if the instantiation of the template results in * the generation of result nodes. */ if (fake->children != NULL) { #ifdef LIBXML_DEBUG_ENABLED xmlDebugDumpNode (stderr, fake, 1); #endif xsltGenericError(xsltGenericErrorContext, "{%s}%s: cannot write to result tree while " "executing a function\n", ctxt->context->functionURI, ctxt->context->function); xmlFreeNode(fake); goto error; } xmlFreeNode(fake); valuePush(ctxt, ret); error: /* * IMPORTANT: This enables previously tree fragments marked as * being results of a function, to be garbage-collected after * the calling process exits. */ xsltExtensionInstructionResultFinalize(tctxt); tctxt->funcLevel--; }
173,293
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile) { int i; int j; jpc_dec_tcomp_t *tcomp; jpc_dec_rlvl_t *rlvl; jpc_dec_band_t *band; int compno; int rlvlno; int bandno; int adjust; int v; jpc_dec_ccp_t *ccp; jpc_dec_cmpt_t *cmpt; if (jpc_dec_decodecblks(dec, tile)) { jas_eprintf("jpc_dec_decodecblks failed\n"); return -1; } /* Perform dequantization. */ for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { ccp = &tile->cp->ccps[compno]; for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { if (!rlvl->bands) { continue; } for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { if (!band->data) { continue; } jpc_undo_roi(band->data, band->roishift, ccp->roishift - band->roishift, band->numbps); if (tile->realmode) { jas_matrix_asl(band->data, JPC_FIX_FRACBITS); jpc_dequantize(band->data, band->absstepsize); } } } } /* Apply an inverse wavelet transform if necessary. */ for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { ccp = &tile->cp->ccps[compno]; jpc_tsfb_synthesize(tcomp->tsfb, tcomp->data); } /* Apply an inverse intercomponent transform if necessary. */ switch (tile->cp->mctid) { case JPC_MCT_RCT: if (dec->numcomps < 3) { jas_eprintf("RCT requires at least three components\n"); return -1; } jpc_irct(tile->tcomps[0].data, tile->tcomps[1].data, tile->tcomps[2].data); break; case JPC_MCT_ICT: if (dec->numcomps < 3) { jas_eprintf("ICT requires at least three components\n"); return -1; } jpc_iict(tile->tcomps[0].data, tile->tcomps[1].data, tile->tcomps[2].data); break; } /* Perform rounding and convert to integer values. */ if (tile->realmode) { for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) { for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) { v = jas_matrix_get(tcomp->data, i, j); v = jpc_fix_round(v); jas_matrix_set(tcomp->data, i, j, jpc_fixtoint(v)); } } } } /* Perform level shift. */ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { adjust = cmpt->sgnd ? 0 : (1 << (cmpt->prec - 1)); for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) { for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) { *jas_matrix_getref(tcomp->data, i, j) += adjust; } } } /* Perform clipping. */ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { jpc_fix_t mn; jpc_fix_t mx; mn = cmpt->sgnd ? (-(1 << (cmpt->prec - 1))) : (0); mx = cmpt->sgnd ? ((1 << (cmpt->prec - 1)) - 1) : ((1 << cmpt->prec) - 1); jas_matrix_clip(tcomp->data, mn, mx); } /* XXX need to free tsfb struct */ /* Write the data for each component of the image. */ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { if (jas_image_writecmpt(dec->image, compno, tcomp->xstart - JPC_CEILDIV(dec->xstart, cmpt->hstep), tcomp->ystart - JPC_CEILDIV(dec->ystart, cmpt->vstep), jas_matrix_numcols( tcomp->data), jas_matrix_numrows(tcomp->data), tcomp->data)) { jas_eprintf("write component failed\n"); return -1; } } return 0; } Commit Message: The component domains must be the same for the ICT/RCT in the JPC codec. This was previously enforced with an assertion. Now, it is handled in a more graceful manner. CWE ID:
static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile) { int i; int j; jpc_dec_tcomp_t *tcomp; jpc_dec_rlvl_t *rlvl; jpc_dec_band_t *band; int compno; int rlvlno; int bandno; int adjust; int v; jpc_dec_ccp_t *ccp; jpc_dec_cmpt_t *cmpt; if (jpc_dec_decodecblks(dec, tile)) { jas_eprintf("jpc_dec_decodecblks failed\n"); return -1; } /* Perform dequantization. */ for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { ccp = &tile->cp->ccps[compno]; for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { if (!rlvl->bands) { continue; } for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { if (!band->data) { continue; } jpc_undo_roi(band->data, band->roishift, ccp->roishift - band->roishift, band->numbps); if (tile->realmode) { jas_matrix_asl(band->data, JPC_FIX_FRACBITS); jpc_dequantize(band->data, band->absstepsize); } } } } /* Apply an inverse wavelet transform if necessary. */ for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { ccp = &tile->cp->ccps[compno]; jpc_tsfb_synthesize(tcomp->tsfb, tcomp->data); } /* Apply an inverse intercomponent transform if necessary. */ switch (tile->cp->mctid) { case JPC_MCT_RCT: if (dec->numcomps < 3) { jas_eprintf("RCT requires at least three components\n"); return -1; } if (!jas_image_cmpt_domains_same(dec->image)) { jas_eprintf("RCT requires all components have the same domain\n"); return -1; } jpc_irct(tile->tcomps[0].data, tile->tcomps[1].data, tile->tcomps[2].data); break; case JPC_MCT_ICT: if (dec->numcomps < 3) { jas_eprintf("ICT requires at least three components\n"); return -1; } if (!jas_image_cmpt_domains_same(dec->image)) { jas_eprintf("RCT requires all components have the same domain\n"); return -1; } jpc_iict(tile->tcomps[0].data, tile->tcomps[1].data, tile->tcomps[2].data); break; } /* Perform rounding and convert to integer values. */ if (tile->realmode) { for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) { for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) { v = jas_matrix_get(tcomp->data, i, j); v = jpc_fix_round(v); jas_matrix_set(tcomp->data, i, j, jpc_fixtoint(v)); } } } } /* Perform level shift. */ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { adjust = cmpt->sgnd ? 0 : (1 << (cmpt->prec - 1)); for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) { for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) { *jas_matrix_getref(tcomp->data, i, j) += adjust; } } } /* Perform clipping. */ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { jpc_fix_t mn; jpc_fix_t mx; mn = cmpt->sgnd ? (-(1 << (cmpt->prec - 1))) : (0); mx = cmpt->sgnd ? ((1 << (cmpt->prec - 1)) - 1) : ((1 << cmpt->prec) - 1); jas_matrix_clip(tcomp->data, mn, mx); } /* XXX need to free tsfb struct */ /* Write the data for each component of the image. */ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { if (jas_image_writecmpt(dec->image, compno, tcomp->xstart - JPC_CEILDIV(dec->xstart, cmpt->hstep), tcomp->ystart - JPC_CEILDIV(dec->ystart, cmpt->vstep), jas_matrix_numcols( tcomp->data), jas_matrix_numrows(tcomp->data), tcomp->data)) { jas_eprintf("write component failed\n"); return -1; } } return 0; }
168,738
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_decode_gaps_in_frame_num(dec_struct_t *ps_dec, UWORD16 u2_frame_num) { UWORD32 u4_next_frm_num, u4_start_frm_num; UWORD32 u4_max_frm_num; pocstruct_t s_tmp_poc; WORD32 i4_poc; dec_slice_params_t *ps_cur_slice; dec_pic_params_t *ps_pic_params; WORD8 i1_gap_idx; WORD32 *i4_gaps_start_frm_num; dpb_manager_t *ps_dpb_mgr; WORD32 i4_frame_gaps; WORD8 *pi1_gaps_per_seq; WORD32 ret; ps_cur_slice = ps_dec->ps_cur_slice; if(ps_cur_slice->u1_field_pic_flag) { if(ps_dec->u2_prev_ref_frame_num == u2_frame_num) return 0; } u4_next_frm_num = ps_dec->u2_prev_ref_frame_num + 1; u4_max_frm_num = ps_dec->ps_cur_sps->u2_u4_max_pic_num_minus1 + 1; if(u4_next_frm_num >= u4_max_frm_num) { u4_next_frm_num -= u4_max_frm_num; } if(u4_next_frm_num == u2_frame_num) { return (0); } if((ps_dec->u1_nal_unit_type == IDR_SLICE_NAL) && (u4_next_frm_num >= u2_frame_num)) { return (0); } u4_start_frm_num = u4_next_frm_num; s_tmp_poc.i4_pic_order_cnt_lsb = 0; s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0; s_tmp_poc.i4_pic_order_cnt_lsb = 0; s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0; s_tmp_poc.i4_delta_pic_order_cnt[0] = 0; s_tmp_poc.i4_delta_pic_order_cnt[1] = 0; ps_cur_slice = ps_dec->ps_cur_slice; ps_pic_params = ps_dec->ps_cur_pps; ps_cur_slice->u1_field_pic_flag = 0; i4_frame_gaps = 0; ps_dpb_mgr = ps_dec->ps_dpb_mgr; /* Find a empty slot to store gap seqn info */ i4_gaps_start_frm_num = ps_dpb_mgr->ai4_gaps_start_frm_num; for(i1_gap_idx = 0; i1_gap_idx < MAX_FRAMES; i1_gap_idx++) { if(INVALID_FRAME_NUM == i4_gaps_start_frm_num[i1_gap_idx]) break; } if(MAX_FRAMES == i1_gap_idx) { UWORD32 i4_error_code; i4_error_code = ERROR_DBP_MANAGER_T; return i4_error_code; } i4_poc = 0; i4_gaps_start_frm_num[i1_gap_idx] = u4_start_frm_num; ps_dpb_mgr->ai4_gaps_end_frm_num[i1_gap_idx] = u2_frame_num - 1; pi1_gaps_per_seq = ps_dpb_mgr->ai1_gaps_per_seq; pi1_gaps_per_seq[i1_gap_idx] = 0; while(u4_next_frm_num != u2_frame_num) { ih264d_delete_nonref_nondisplay_pics(ps_dpb_mgr); if(ps_pic_params->ps_sps->u1_pic_order_cnt_type) { /* allocate a picture buffer and insert it as ST node */ ret = ih264d_decode_pic_order_cnt(0, u4_next_frm_num, &ps_dec->s_prev_pic_poc, &s_tmp_poc, ps_cur_slice, ps_pic_params, 1, 0, 0, &i4_poc); if(ret != OK) return ret; /* Display seq no calculations */ if(i4_poc >= ps_dec->i4_max_poc) ps_dec->i4_max_poc = i4_poc; /* IDR Picture or POC wrap around */ if(i4_poc == 0) { ps_dec->i4_prev_max_display_seq = ps_dec->i4_prev_max_display_seq + ps_dec->i4_max_poc + ps_dec->u1_max_dec_frame_buffering + 1; ps_dec->i4_max_poc = 0; } ps_cur_slice->u1_mmco_equalto5 = 0; ps_cur_slice->u2_frame_num = u4_next_frm_num; } if(ps_dpb_mgr->i1_poc_buf_id_entries >= ps_dec->u1_max_dec_frame_buffering) { ret = ih264d_assign_display_seq(ps_dec); if(ret != OK) return ret; } ret = ih264d_insert_pic_in_display_list( ps_dec->ps_dpb_mgr, (WORD8) DO_NOT_DISP, (WORD32)(ps_dec->i4_prev_max_display_seq + i4_poc), u4_next_frm_num); if(ret != OK) return ret; pi1_gaps_per_seq[i1_gap_idx]++; ret = ih264d_do_mmco_for_gaps(ps_dpb_mgr, ps_dec->ps_cur_sps->u1_num_ref_frames); if(ret != OK) return ret; ih264d_delete_nonref_nondisplay_pics(ps_dpb_mgr); u4_next_frm_num++; if(u4_next_frm_num >= u4_max_frm_num) { u4_next_frm_num -= u4_max_frm_num; } i4_frame_gaps++; } return OK; } Commit Message: Decoder: Fixed error handling for dangling fields In case of dangling fields with gaps in frames enabled, field pic in cur_slice was wrongly set to 0. This would cause dangling field to be concealed as a frame, which would result in a number of MB mismatch and hence a hang. Bug: 34097672 Change-Id: Ia9b7f72c4676188c45790b2dfbb4fe2c2d2c01f8 (cherry picked from commit 1a13168ca3510ba91274d10fdee46b3642cc9554) CWE ID: CWE-119
WORD32 ih264d_decode_gaps_in_frame_num(dec_struct_t *ps_dec, UWORD16 u2_frame_num) { UWORD32 u4_next_frm_num, u4_start_frm_num; UWORD32 u4_max_frm_num; pocstruct_t s_tmp_poc; WORD32 i4_poc; dec_slice_params_t *ps_cur_slice; dec_pic_params_t *ps_pic_params; WORD8 i1_gap_idx; WORD32 *i4_gaps_start_frm_num; dpb_manager_t *ps_dpb_mgr; WORD32 i4_frame_gaps; WORD8 *pi1_gaps_per_seq; WORD32 ret; ps_cur_slice = ps_dec->ps_cur_slice; if(ps_cur_slice->u1_field_pic_flag) { if(ps_dec->u2_prev_ref_frame_num == u2_frame_num) return 0; } u4_next_frm_num = ps_dec->u2_prev_ref_frame_num + 1; u4_max_frm_num = ps_dec->ps_cur_sps->u2_u4_max_pic_num_minus1 + 1; if(u4_next_frm_num >= u4_max_frm_num) { u4_next_frm_num -= u4_max_frm_num; } if(u4_next_frm_num == u2_frame_num) { return (0); } if((ps_dec->u1_nal_unit_type == IDR_SLICE_NAL) && (u4_next_frm_num >= u2_frame_num)) { return (0); } u4_start_frm_num = u4_next_frm_num; s_tmp_poc.i4_pic_order_cnt_lsb = 0; s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0; s_tmp_poc.i4_pic_order_cnt_lsb = 0; s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0; s_tmp_poc.i4_delta_pic_order_cnt[0] = 0; s_tmp_poc.i4_delta_pic_order_cnt[1] = 0; ps_cur_slice = ps_dec->ps_cur_slice; ps_pic_params = ps_dec->ps_cur_pps; i4_frame_gaps = 0; ps_dpb_mgr = ps_dec->ps_dpb_mgr; /* Find a empty slot to store gap seqn info */ i4_gaps_start_frm_num = ps_dpb_mgr->ai4_gaps_start_frm_num; for(i1_gap_idx = 0; i1_gap_idx < MAX_FRAMES; i1_gap_idx++) { if(INVALID_FRAME_NUM == i4_gaps_start_frm_num[i1_gap_idx]) break; } if(MAX_FRAMES == i1_gap_idx) { UWORD32 i4_error_code; i4_error_code = ERROR_DBP_MANAGER_T; return i4_error_code; } i4_poc = 0; i4_gaps_start_frm_num[i1_gap_idx] = u4_start_frm_num; ps_dpb_mgr->ai4_gaps_end_frm_num[i1_gap_idx] = u2_frame_num - 1; pi1_gaps_per_seq = ps_dpb_mgr->ai1_gaps_per_seq; pi1_gaps_per_seq[i1_gap_idx] = 0; while(u4_next_frm_num != u2_frame_num) { ih264d_delete_nonref_nondisplay_pics(ps_dpb_mgr); if(ps_pic_params->ps_sps->u1_pic_order_cnt_type) { /* allocate a picture buffer and insert it as ST node */ ret = ih264d_decode_pic_order_cnt(0, u4_next_frm_num, &ps_dec->s_prev_pic_poc, &s_tmp_poc, ps_cur_slice, ps_pic_params, 1, 0, 0, &i4_poc); if(ret != OK) return ret; /* Display seq no calculations */ if(i4_poc >= ps_dec->i4_max_poc) ps_dec->i4_max_poc = i4_poc; /* IDR Picture or POC wrap around */ if(i4_poc == 0) { ps_dec->i4_prev_max_display_seq = ps_dec->i4_prev_max_display_seq + ps_dec->i4_max_poc + ps_dec->u1_max_dec_frame_buffering + 1; ps_dec->i4_max_poc = 0; } ps_cur_slice->u1_mmco_equalto5 = 0; ps_cur_slice->u2_frame_num = u4_next_frm_num; } if(ps_dpb_mgr->i1_poc_buf_id_entries >= ps_dec->u1_max_dec_frame_buffering) { ret = ih264d_assign_display_seq(ps_dec); if(ret != OK) return ret; } ret = ih264d_insert_pic_in_display_list( ps_dec->ps_dpb_mgr, (WORD8) DO_NOT_DISP, (WORD32)(ps_dec->i4_prev_max_display_seq + i4_poc), u4_next_frm_num); if(ret != OK) return ret; pi1_gaps_per_seq[i1_gap_idx]++; ret = ih264d_do_mmco_for_gaps(ps_dpb_mgr, ps_dec->ps_cur_sps->u1_num_ref_frames); if(ret != OK) return ret; ih264d_delete_nonref_nondisplay_pics(ps_dpb_mgr); u4_next_frm_num++; if(u4_next_frm_num >= u4_max_frm_num) { u4_next_frm_num -= u4_max_frm_num; } i4_frame_gaps++; } return OK; }
174,027
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void set_banner(struct openconnect_info *vpninfo) { char *banner, *q; const char *p; if (!vpninfo->banner || !(banner = malloc(strlen(vpninfo->banner)))) { unsetenv("CISCO_BANNER"); return; } p = vpninfo->banner; q = banner; while (*p) { if (*p == '%' && isxdigit((int)(unsigned char)p[1]) && isxdigit((int)(unsigned char)p[2])) { *(q++) = unhex(p + 1); p += 3; } else *(q++) = *(p++); } *q = 0; setenv("CISCO_BANNER", banner, 1); free(banner); } Commit Message: CWE ID: CWE-119
static void set_banner(struct openconnect_info *vpninfo) { char *banner, *q; const char *p; if (!vpninfo->banner || !(banner = malloc(strlen(vpninfo->banner)+1))) { unsetenv("CISCO_BANNER"); return; } p = vpninfo->banner; q = banner; while (*p) { if (*p == '%' && isxdigit((int)(unsigned char)p[1]) && isxdigit((int)(unsigned char)p[2])) { *(q++) = unhex(p + 1); p += 3; } else *(q++) = *(p++); } *q = 0; setenv("CISCO_BANNER", banner, 1); free(banner); }
164,960
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int object_custom(UNSERIALIZE_PARAMETER, zend_class_entry *ce) { long datalen; datalen = parse_iv2((*p) + 2, p); (*p) += 2; if (datalen < 0 || (*p) + datalen >= max) { zend_error(E_WARNING, "Insufficient data for unserializing - %ld required, %ld present", datalen, (long)(max - (*p))); return 0; } if (ce->unserialize == NULL) { zend_error(E_WARNING, "Class %s has no unserializer", ce->name); object_init_ex(*rval, ce); } else if (ce->unserialize(rval, ce, (const unsigned char*)*p, datalen, (zend_unserialize_data *)var_hash TSRMLS_CC) != SUCCESS) { return 0; } (*p) += datalen; return finish_nested_data(UNSERIALIZE_PASSTHRU); } Commit Message: CWE ID: CWE-189
static inline int object_custom(UNSERIALIZE_PARAMETER, zend_class_entry *ce) { long datalen; datalen = parse_iv2((*p) + 2, p); (*p) += 2; if (datalen < 0 || (max - (*p)) <= datalen) { zend_error(E_WARNING, "Insufficient data for unserializing - %ld required, %ld present", datalen, (long)(max - (*p))); return 0; } if (ce->unserialize == NULL) { zend_error(E_WARNING, "Class %s has no unserializer", ce->name); object_init_ex(*rval, ce); } else if (ce->unserialize(rval, ce, (const unsigned char*)*p, datalen, (zend_unserialize_data *)var_hash TSRMLS_CC) != SUCCESS) { return 0; } (*p) += datalen; return finish_nested_data(UNSERIALIZE_PASSTHRU); }
165,149
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; unsigned char buff[128]; int r, i; size_t field_length = 0, modulus_length = 0; sc_path_t tmppath; set_string (&p15card->tokeninfo->label, "ID-kaart"); set_string (&p15card->tokeninfo->manufacturer_id, "AS Sertifitseerimiskeskus"); /* Select application directory */ sc_format_path ("3f00eeee5044", &tmppath); r = sc_select_file (card, &tmppath, NULL); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "select esteid PD failed"); /* read the serial (document number) */ r = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "read document number failed"); buff[r] = '\0'; set_string (&p15card->tokeninfo->serial_number, (const char *) buff); p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION | SC_PKCS15_TOKEN_EID_COMPLIANT | SC_PKCS15_TOKEN_READONLY; /* add certificates */ for (i = 0; i < 2; i++) { static const char *esteid_cert_names[2] = { "Isikutuvastus", "Allkirjastamine"}; static char const *esteid_cert_paths[2] = { "3f00eeeeaace", "3f00eeeeddce"}; static int esteid_cert_ids[2] = {1, 2}; struct sc_pkcs15_cert_info cert_info; struct sc_pkcs15_object cert_obj; memset(&cert_info, 0, sizeof(cert_info)); memset(&cert_obj, 0, sizeof(cert_obj)); cert_info.id.value[0] = esteid_cert_ids[i]; cert_info.id.len = 1; sc_format_path(esteid_cert_paths[i], &cert_info.path); strlcpy(cert_obj.label, esteid_cert_names[i], sizeof(cert_obj.label)); r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info); if (r < 0) return SC_ERROR_INTERNAL; if (i == 0) { sc_pkcs15_cert_t *cert = NULL; r = sc_pkcs15_read_certificate(p15card, &cert_info, &cert); if (r < 0) return SC_ERROR_INTERNAL; if (cert->key->algorithm == SC_ALGORITHM_EC) field_length = cert->key->u.ec.params.field_length; else modulus_length = cert->key->u.rsa.modulus.len * 8; if (r == SC_SUCCESS) { static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }}; u8 *cn_name = NULL; size_t cn_len = 0; sc_pkcs15_get_name_from_dn(card->ctx, cert->subject, cert->subject_len, &cn_oid, &cn_name, &cn_len); if (cn_len > 0) { char *token_name = malloc(cn_len+1); if (token_name) { memcpy(token_name, cn_name, cn_len); token_name[cn_len] = '\0'; set_string(&p15card->tokeninfo->label, (const char*)token_name); free(token_name); } } free(cn_name); sc_pkcs15_free_certificate(cert); } } } /* the file with key pin info (tries left) */ sc_format_path ("3f000016", &tmppath); r = sc_select_file (card, &tmppath, NULL); if (r < 0) return SC_ERROR_INTERNAL; /* add pins */ for (i = 0; i < 3; i++) { unsigned char tries_left; static const char *esteid_pin_names[3] = { "PIN1", "PIN2", "PUK" }; static const int esteid_pin_min[3] = {4, 5, 8}; static const int esteid_pin_ref[3] = {1, 2, 0}; static const int esteid_pin_authid[3] = {1, 2, 3}; static const int esteid_pin_flags[3] = {0, 0, SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN}; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); /* read the number of tries left for the PIN */ r = sc_read_record (card, i + 1, buff, sizeof(buff), SC_RECORD_BY_REC_NR); if (r < 0) return SC_ERROR_INTERNAL; tries_left = buff[5]; pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = esteid_pin_authid[i]; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = esteid_pin_ref[i]; pin_info.attrs.pin.flags = esteid_pin_flags[i]; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = esteid_pin_min[i]; pin_info.attrs.pin.stored_length = 12; pin_info.attrs.pin.max_length = 12; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = (int)tries_left; pin_info.max_tries = 3; strlcpy(pin_obj.label, esteid_pin_names[i], sizeof(pin_obj.label)); pin_obj.flags = esteid_pin_flags[i]; /* Link normal PINs with PUK */ if (i < 2) { pin_obj.auth_id.len = 1; pin_obj.auth_id.value[0] = 3; } r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) return SC_ERROR_INTERNAL; } /* add private keys */ for (i = 0; i < 2; i++) { static int prkey_pin[2] = {1, 2}; static const char *prkey_name[2] = { "Isikutuvastus", "Allkirjastamine"}; struct sc_pkcs15_prkey_info prkey_info; struct sc_pkcs15_object prkey_obj; memset(&prkey_info, 0, sizeof(prkey_info)); memset(&prkey_obj, 0, sizeof(prkey_obj)); prkey_info.id.len = 1; prkey_info.id.value[0] = prkey_pin[i]; prkey_info.native = 1; prkey_info.key_reference = i + 1; prkey_info.field_length = field_length; prkey_info.modulus_length = modulus_length; if (i == 1) prkey_info.usage = SC_PKCS15_PRKEY_USAGE_NONREPUDIATION; else if(field_length > 0) // ECC has sign and derive usage prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_DERIVE; else prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT; strlcpy(prkey_obj.label, prkey_name[i], sizeof(prkey_obj.label)); prkey_obj.auth_id.len = 1; prkey_obj.auth_id.value[0] = prkey_pin[i]; prkey_obj.user_consent = 0; prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE; if(field_length > 0) r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info); else r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info); if (r < 0) return SC_ERROR_INTERNAL; } return SC_SUCCESS; } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415
sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; unsigned char buff[128]; int r, i; size_t field_length = 0, modulus_length = 0; sc_path_t tmppath; set_string (&p15card->tokeninfo->label, "ID-kaart"); set_string (&p15card->tokeninfo->manufacturer_id, "AS Sertifitseerimiskeskus"); /* Select application directory */ sc_format_path ("3f00eeee5044", &tmppath); r = sc_select_file (card, &tmppath, NULL); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "select esteid PD failed"); /* read the serial (document number) */ r = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "read document number failed"); buff[MIN((size_t) r, (sizeof buff)-1)] = '\0'; set_string (&p15card->tokeninfo->serial_number, (const char *) buff); p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION | SC_PKCS15_TOKEN_EID_COMPLIANT | SC_PKCS15_TOKEN_READONLY; /* add certificates */ for (i = 0; i < 2; i++) { static const char *esteid_cert_names[2] = { "Isikutuvastus", "Allkirjastamine"}; static char const *esteid_cert_paths[2] = { "3f00eeeeaace", "3f00eeeeddce"}; static int esteid_cert_ids[2] = {1, 2}; struct sc_pkcs15_cert_info cert_info; struct sc_pkcs15_object cert_obj; memset(&cert_info, 0, sizeof(cert_info)); memset(&cert_obj, 0, sizeof(cert_obj)); cert_info.id.value[0] = esteid_cert_ids[i]; cert_info.id.len = 1; sc_format_path(esteid_cert_paths[i], &cert_info.path); strlcpy(cert_obj.label, esteid_cert_names[i], sizeof(cert_obj.label)); r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info); if (r < 0) return SC_ERROR_INTERNAL; if (i == 0) { sc_pkcs15_cert_t *cert = NULL; r = sc_pkcs15_read_certificate(p15card, &cert_info, &cert); if (r < 0) return SC_ERROR_INTERNAL; if (cert->key->algorithm == SC_ALGORITHM_EC) field_length = cert->key->u.ec.params.field_length; else modulus_length = cert->key->u.rsa.modulus.len * 8; if (r == SC_SUCCESS) { static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }}; u8 *cn_name = NULL; size_t cn_len = 0; sc_pkcs15_get_name_from_dn(card->ctx, cert->subject, cert->subject_len, &cn_oid, &cn_name, &cn_len); if (cn_len > 0) { char *token_name = malloc(cn_len+1); if (token_name) { memcpy(token_name, cn_name, cn_len); token_name[cn_len] = '\0'; set_string(&p15card->tokeninfo->label, (const char*)token_name); free(token_name); } } free(cn_name); sc_pkcs15_free_certificate(cert); } } } /* the file with key pin info (tries left) */ sc_format_path ("3f000016", &tmppath); r = sc_select_file (card, &tmppath, NULL); if (r < 0) return SC_ERROR_INTERNAL; /* add pins */ for (i = 0; i < 3; i++) { unsigned char tries_left; static const char *esteid_pin_names[3] = { "PIN1", "PIN2", "PUK" }; static const int esteid_pin_min[3] = {4, 5, 8}; static const int esteid_pin_ref[3] = {1, 2, 0}; static const int esteid_pin_authid[3] = {1, 2, 3}; static const int esteid_pin_flags[3] = {0, 0, SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN}; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); /* read the number of tries left for the PIN */ r = sc_read_record (card, i + 1, buff, sizeof(buff), SC_RECORD_BY_REC_NR); if (r < 0) return SC_ERROR_INTERNAL; tries_left = buff[5]; pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = esteid_pin_authid[i]; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = esteid_pin_ref[i]; pin_info.attrs.pin.flags = esteid_pin_flags[i]; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = esteid_pin_min[i]; pin_info.attrs.pin.stored_length = 12; pin_info.attrs.pin.max_length = 12; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = (int)tries_left; pin_info.max_tries = 3; strlcpy(pin_obj.label, esteid_pin_names[i], sizeof(pin_obj.label)); pin_obj.flags = esteid_pin_flags[i]; /* Link normal PINs with PUK */ if (i < 2) { pin_obj.auth_id.len = 1; pin_obj.auth_id.value[0] = 3; } r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) return SC_ERROR_INTERNAL; } /* add private keys */ for (i = 0; i < 2; i++) { static int prkey_pin[2] = {1, 2}; static const char *prkey_name[2] = { "Isikutuvastus", "Allkirjastamine"}; struct sc_pkcs15_prkey_info prkey_info; struct sc_pkcs15_object prkey_obj; memset(&prkey_info, 0, sizeof(prkey_info)); memset(&prkey_obj, 0, sizeof(prkey_obj)); prkey_info.id.len = 1; prkey_info.id.value[0] = prkey_pin[i]; prkey_info.native = 1; prkey_info.key_reference = i + 1; prkey_info.field_length = field_length; prkey_info.modulus_length = modulus_length; if (i == 1) prkey_info.usage = SC_PKCS15_PRKEY_USAGE_NONREPUDIATION; else if(field_length > 0) // ECC has sign and derive usage prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_DERIVE; else prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT; strlcpy(prkey_obj.label, prkey_name[i], sizeof(prkey_obj.label)); prkey_obj.auth_id.len = 1; prkey_obj.auth_id.value[0] = prkey_pin[i]; prkey_obj.user_consent = 0; prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE; if(field_length > 0) r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info); else r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info); if (r < 0) return SC_ERROR_INTERNAL; } return SC_SUCCESS; }
169,076
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Resource::~Resource() { } Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed, BUG=85808 Review URL: http://codereview.chromium.org/7196001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
Resource::~Resource() { ResourceTracker::Get()->ResourceDestroyed(this); }
170,415
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int tcp_v4_rcv(struct sk_buff *skb) { struct net *net = dev_net(skb->dev); const struct iphdr *iph; const struct tcphdr *th; bool refcounted; struct sock *sk; int ret; if (skb->pkt_type != PACKET_HOST) goto discard_it; /* Count it even if it's bad */ __TCP_INC_STATS(net, TCP_MIB_INSEGS); if (!pskb_may_pull(skb, sizeof(struct tcphdr))) goto discard_it; th = (const struct tcphdr *)skb->data; if (unlikely(th->doff < sizeof(struct tcphdr) / 4)) goto bad_packet; if (!pskb_may_pull(skb, th->doff * 4)) goto discard_it; /* An explanation is required here, I think. * Packet length and doff are validated by header prediction, * provided case of th->doff==0 is eliminated. * So, we defer the checks. */ if (skb_checksum_init(skb, IPPROTO_TCP, inet_compute_pseudo)) goto csum_error; th = (const struct tcphdr *)skb->data; iph = ip_hdr(skb); /* This is tricky : We move IPCB at its correct location into TCP_SKB_CB() * barrier() makes sure compiler wont play fool^Waliasing games. */ memmove(&TCP_SKB_CB(skb)->header.h4, IPCB(skb), sizeof(struct inet_skb_parm)); barrier(); TCP_SKB_CB(skb)->seq = ntohl(th->seq); TCP_SKB_CB(skb)->end_seq = (TCP_SKB_CB(skb)->seq + th->syn + th->fin + skb->len - th->doff * 4); TCP_SKB_CB(skb)->ack_seq = ntohl(th->ack_seq); TCP_SKB_CB(skb)->tcp_flags = tcp_flag_byte(th); TCP_SKB_CB(skb)->tcp_tw_isn = 0; TCP_SKB_CB(skb)->ip_dsfield = ipv4_get_dsfield(iph); TCP_SKB_CB(skb)->sacked = 0; lookup: sk = __inet_lookup_skb(&tcp_hashinfo, skb, __tcp_hdrlen(th), th->source, th->dest, &refcounted); if (!sk) goto no_tcp_socket; process: if (sk->sk_state == TCP_TIME_WAIT) goto do_time_wait; if (sk->sk_state == TCP_NEW_SYN_RECV) { struct request_sock *req = inet_reqsk(sk); struct sock *nsk; sk = req->rsk_listener; if (unlikely(tcp_v4_inbound_md5_hash(sk, skb))) { sk_drops_add(sk, skb); reqsk_put(req); goto discard_it; } if (unlikely(sk->sk_state != TCP_LISTEN)) { inet_csk_reqsk_queue_drop_and_put(sk, req); goto lookup; } /* We own a reference on the listener, increase it again * as we might lose it too soon. */ sock_hold(sk); refcounted = true; nsk = tcp_check_req(sk, skb, req, false); if (!nsk) { reqsk_put(req); goto discard_and_relse; } if (nsk == sk) { reqsk_put(req); } else if (tcp_child_process(sk, nsk, skb)) { tcp_v4_send_reset(nsk, skb); goto discard_and_relse; } else { sock_put(sk); return 0; } } if (unlikely(iph->ttl < inet_sk(sk)->min_ttl)) { __NET_INC_STATS(net, LINUX_MIB_TCPMINTTLDROP); goto discard_and_relse; } if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) goto discard_and_relse; if (tcp_v4_inbound_md5_hash(sk, skb)) goto discard_and_relse; nf_reset(skb); if (sk_filter(sk, skb)) goto discard_and_relse; skb->dev = NULL; if (sk->sk_state == TCP_LISTEN) { ret = tcp_v4_do_rcv(sk, skb); goto put_and_return; } sk_incoming_cpu_update(sk); bh_lock_sock_nested(sk); tcp_segs_in(tcp_sk(sk), skb); ret = 0; if (!sock_owned_by_user(sk)) { if (!tcp_prequeue(sk, skb)) ret = tcp_v4_do_rcv(sk, skb); } else if (tcp_add_backlog(sk, skb)) { goto discard_and_relse; } bh_unlock_sock(sk); put_and_return: if (refcounted) sock_put(sk); return ret; no_tcp_socket: if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) goto discard_it; if (tcp_checksum_complete(skb)) { csum_error: __TCP_INC_STATS(net, TCP_MIB_CSUMERRORS); bad_packet: __TCP_INC_STATS(net, TCP_MIB_INERRS); } else { tcp_v4_send_reset(NULL, skb); } discard_it: /* Discard frame. */ kfree_skb(skb); return 0; discard_and_relse: sk_drops_add(sk, skb); if (refcounted) sock_put(sk); goto discard_it; do_time_wait: if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) { inet_twsk_put(inet_twsk(sk)); goto discard_it; } if (tcp_checksum_complete(skb)) { inet_twsk_put(inet_twsk(sk)); goto csum_error; } switch (tcp_timewait_state_process(inet_twsk(sk), skb, th)) { case TCP_TW_SYN: { struct sock *sk2 = inet_lookup_listener(dev_net(skb->dev), &tcp_hashinfo, skb, __tcp_hdrlen(th), iph->saddr, th->source, iph->daddr, th->dest, inet_iif(skb)); if (sk2) { inet_twsk_deschedule_put(inet_twsk(sk)); sk = sk2; refcounted = false; goto process; } /* Fall through to ACK */ } case TCP_TW_ACK: tcp_v4_timewait_ack(sk, skb); break; case TCP_TW_RST: tcp_v4_send_reset(sk, skb); inet_twsk_deschedule_put(inet_twsk(sk)); goto discard_it; case TCP_TW_SUCCESS:; } goto discard_it; } Commit Message: tcp: take care of truncations done by sk_filter() With syzkaller help, Marco Grassi found a bug in TCP stack, crashing in tcp_collapse() Root cause is that sk_filter() can truncate the incoming skb, but TCP stack was not really expecting this to happen. It probably was expecting a simple DROP or ACCEPT behavior. We first need to make sure no part of TCP header could be removed. Then we need to adjust TCP_SKB_CB(skb)->end_seq Many thanks to syzkaller team and Marco for giving us a reproducer. Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Marco Grassi <[email protected]> Reported-by: Vladis Dronov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-284
int tcp_v4_rcv(struct sk_buff *skb) { struct net *net = dev_net(skb->dev); const struct iphdr *iph; const struct tcphdr *th; bool refcounted; struct sock *sk; int ret; if (skb->pkt_type != PACKET_HOST) goto discard_it; /* Count it even if it's bad */ __TCP_INC_STATS(net, TCP_MIB_INSEGS); if (!pskb_may_pull(skb, sizeof(struct tcphdr))) goto discard_it; th = (const struct tcphdr *)skb->data; if (unlikely(th->doff < sizeof(struct tcphdr) / 4)) goto bad_packet; if (!pskb_may_pull(skb, th->doff * 4)) goto discard_it; /* An explanation is required here, I think. * Packet length and doff are validated by header prediction, * provided case of th->doff==0 is eliminated. * So, we defer the checks. */ if (skb_checksum_init(skb, IPPROTO_TCP, inet_compute_pseudo)) goto csum_error; th = (const struct tcphdr *)skb->data; iph = ip_hdr(skb); /* This is tricky : We move IPCB at its correct location into TCP_SKB_CB() * barrier() makes sure compiler wont play fool^Waliasing games. */ memmove(&TCP_SKB_CB(skb)->header.h4, IPCB(skb), sizeof(struct inet_skb_parm)); barrier(); TCP_SKB_CB(skb)->seq = ntohl(th->seq); TCP_SKB_CB(skb)->end_seq = (TCP_SKB_CB(skb)->seq + th->syn + th->fin + skb->len - th->doff * 4); TCP_SKB_CB(skb)->ack_seq = ntohl(th->ack_seq); TCP_SKB_CB(skb)->tcp_flags = tcp_flag_byte(th); TCP_SKB_CB(skb)->tcp_tw_isn = 0; TCP_SKB_CB(skb)->ip_dsfield = ipv4_get_dsfield(iph); TCP_SKB_CB(skb)->sacked = 0; lookup: sk = __inet_lookup_skb(&tcp_hashinfo, skb, __tcp_hdrlen(th), th->source, th->dest, &refcounted); if (!sk) goto no_tcp_socket; process: if (sk->sk_state == TCP_TIME_WAIT) goto do_time_wait; if (sk->sk_state == TCP_NEW_SYN_RECV) { struct request_sock *req = inet_reqsk(sk); struct sock *nsk; sk = req->rsk_listener; if (unlikely(tcp_v4_inbound_md5_hash(sk, skb))) { sk_drops_add(sk, skb); reqsk_put(req); goto discard_it; } if (unlikely(sk->sk_state != TCP_LISTEN)) { inet_csk_reqsk_queue_drop_and_put(sk, req); goto lookup; } /* We own a reference on the listener, increase it again * as we might lose it too soon. */ sock_hold(sk); refcounted = true; nsk = tcp_check_req(sk, skb, req, false); if (!nsk) { reqsk_put(req); goto discard_and_relse; } if (nsk == sk) { reqsk_put(req); } else if (tcp_child_process(sk, nsk, skb)) { tcp_v4_send_reset(nsk, skb); goto discard_and_relse; } else { sock_put(sk); return 0; } } if (unlikely(iph->ttl < inet_sk(sk)->min_ttl)) { __NET_INC_STATS(net, LINUX_MIB_TCPMINTTLDROP); goto discard_and_relse; } if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) goto discard_and_relse; if (tcp_v4_inbound_md5_hash(sk, skb)) goto discard_and_relse; nf_reset(skb); if (tcp_filter(sk, skb)) goto discard_and_relse; th = (const struct tcphdr *)skb->data; iph = ip_hdr(skb); skb->dev = NULL; if (sk->sk_state == TCP_LISTEN) { ret = tcp_v4_do_rcv(sk, skb); goto put_and_return; } sk_incoming_cpu_update(sk); bh_lock_sock_nested(sk); tcp_segs_in(tcp_sk(sk), skb); ret = 0; if (!sock_owned_by_user(sk)) { if (!tcp_prequeue(sk, skb)) ret = tcp_v4_do_rcv(sk, skb); } else if (tcp_add_backlog(sk, skb)) { goto discard_and_relse; } bh_unlock_sock(sk); put_and_return: if (refcounted) sock_put(sk); return ret; no_tcp_socket: if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) goto discard_it; if (tcp_checksum_complete(skb)) { csum_error: __TCP_INC_STATS(net, TCP_MIB_CSUMERRORS); bad_packet: __TCP_INC_STATS(net, TCP_MIB_INERRS); } else { tcp_v4_send_reset(NULL, skb); } discard_it: /* Discard frame. */ kfree_skb(skb); return 0; discard_and_relse: sk_drops_add(sk, skb); if (refcounted) sock_put(sk); goto discard_it; do_time_wait: if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) { inet_twsk_put(inet_twsk(sk)); goto discard_it; } if (tcp_checksum_complete(skb)) { inet_twsk_put(inet_twsk(sk)); goto csum_error; } switch (tcp_timewait_state_process(inet_twsk(sk), skb, th)) { case TCP_TW_SYN: { struct sock *sk2 = inet_lookup_listener(dev_net(skb->dev), &tcp_hashinfo, skb, __tcp_hdrlen(th), iph->saddr, th->source, iph->daddr, th->dest, inet_iif(skb)); if (sk2) { inet_twsk_deschedule_put(inet_twsk(sk)); sk = sk2; refcounted = false; goto process; } /* Fall through to ACK */ } case TCP_TW_ACK: tcp_v4_timewait_ack(sk, skb); break; case TCP_TW_RST: tcp_v4_send_reset(sk, skb); inet_twsk_deschedule_put(inet_twsk(sk)); goto discard_it; case TCP_TW_SUCCESS:; } goto discard_it; }
166,913
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadAVSImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; register PixelPacket *q; register ssize_t x; register unsigned char *p; size_t height, width; ssize_t count, y; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read AVS X image. */ width=ReadBlobMSBLong(image); height=ReadBlobMSBLong(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((width == 0UL) || (height == 0UL)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { ssize_t length; /* Convert AVS raster image to pixel packets. */ image->columns=width; image->rows=height; image->depth=8; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; pixels=(unsigned char *) AcquireQuantumMemory(image->columns, 4*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=(size_t) 4*image->columns; for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if (count != length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelAlpha(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); if (q->opacity != OpaqueOpacity) image->matte=MagickTrue; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; width=ReadBlobMSBLong(image); height=ReadBlobMSBLong(image); if ((width != 0UL) && (height != 0UL)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((width != 0UL) && (height != 0UL)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadAVSImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; register PixelPacket *q; register ssize_t x; register unsigned char *p; size_t height, width; ssize_t count, y; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read AVS X image. */ width=ReadBlobMSBLong(image); height=ReadBlobMSBLong(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((width == 0UL) || (height == 0UL)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { ssize_t length; /* Convert AVS raster image to pixel packets. */ image->columns=width; image->rows=height; image->depth=8; 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)); } pixels=(unsigned char *) AcquireQuantumMemory(image->columns, 4*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=(size_t) 4*image->columns; for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if (count != length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelAlpha(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); if (q->opacity != OpaqueOpacity) image->matte=MagickTrue; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; width=ReadBlobMSBLong(image); height=ReadBlobMSBLong(image); if ((width != 0UL) && (height != 0UL)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((width != 0UL) && (height != 0UL)); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,548
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ManifestChangeNotifier::DidChangeManifest() { if (weak_factory_.HasWeakPtrs()) return; if (!render_frame()->GetWebFrame()->IsLoading()) { render_frame() ->GetTaskRunner(blink::TaskType::kUnspecedLoading) ->PostTask(FROM_HERE, base::BindOnce(&ManifestChangeNotifier::ReportManifestChange, weak_factory_.GetWeakPtr())); return; } ReportManifestChange(); } Commit Message: Fail the web app manifest fetch if the document is sandboxed. This ensures that sandboxed pages are regarded as non-PWAs, and that other features in the browser process which trust the web manifest do not receive the manifest at all if the document itself cannot access the manifest. BUG=771709 Change-Id: Ifd4d00c2fccff8cc0e5e8d2457bd55b992b0a8f4 Reviewed-on: https://chromium-review.googlesource.com/866529 Commit-Queue: Dominick Ng <[email protected]> Reviewed-by: Mounir Lamouri <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#531121} CWE ID:
void ManifestChangeNotifier::DidChangeManifest() { // Manifests are not considered when the current page has a unique origin. if (!ManifestManager::CanFetchManifest(render_frame())) return; if (weak_factory_.HasWeakPtrs()) return; if (!render_frame()->GetWebFrame()->IsLoading()) { render_frame() ->GetTaskRunner(blink::TaskType::kUnspecedLoading) ->PostTask(FROM_HERE, base::BindOnce(&ManifestChangeNotifier::ReportManifestChange, weak_factory_.GetWeakPtr())); return; } ReportManifestChange(); }
172,920
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool LayoutSVGResourceMarker::calculateLocalTransform() { return selfNeedsLayout(); } Commit Message: Avoid using forced layout to trigger paint invalidation for SVG containers Currently, SVG containers in the LayoutObject hierarchy force layout of their children if the transform changes. The main reason for this is to trigger paint invalidation of the subtree. In some cases - changes to the scale factor - there are other reasons to trigger layout, like computing a new scale factor for <text> or re-layout nodes with non-scaling stroke. Compute a "scale-factor change" in addition to the "transform change" already computed, then use this new signal to determine if layout should be forced for the subtree. Trigger paint invalidation using the LayoutObject flags instead. The downside to this is that paint invalidation will walk into "hidden" containers which rarely require repaint (since they are not technically visible). This will hopefully be rectified in a follow-up CL. For the testcase from 603850, this essentially eliminates the cost of layout (from ~350ms to ~0ms on authors machine; layout cost is related to text metrics recalculation), bumping frame rate significantly. BUG=603956,603850 Review-Url: https://codereview.chromium.org/1996543002 Cr-Commit-Position: refs/heads/master@{#400950} CWE ID:
bool LayoutSVGResourceMarker::calculateLocalTransform() LayoutSVGContainer::TransformChange LayoutSVGResourceMarker::calculateLocalTransform() { return selfNeedsLayout() ? TransformChange::Full : TransformChange::None; }
171,665
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: _PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle, TALLOC_CTX *ctx, const char *src, size_t n) { size_t size=0; char *dest; if (!src) { return NULL; } /* this takes advantage of the fact that upper/lower can't change the length of a character by more than 1 byte */ dest = talloc_array(ctx, char, 2*(n+1)); if (dest == NULL) { return NULL; } while (n-- && *src) { size_t c_size; codepoint_t c = next_codepoint_handle(iconv_handle, src, &c_size); src += c_size; c = toupper_m(c); c_size = push_codepoint_handle(iconv_handle, dest+size, c); if (c_size == -1) { talloc_free(dest); return NULL; } size += c_size; } dest[size] = 0; /* trim it so talloc_append_string() works */ dest = talloc_realloc(ctx, dest, char, size+1); talloc_set_name_const(dest, dest); return dest; } Commit Message: CWE ID: CWE-200
_PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle, TALLOC_CTX *ctx, const char *src, size_t n) { size_t size=0; char *dest; if (!src) { return NULL; } /* this takes advantage of the fact that upper/lower can't change the length of a character by more than 1 byte */ dest = talloc_array(ctx, char, 2*(n+1)); if (dest == NULL) { return NULL; } while (n-- && *src) { size_t c_size; codepoint_t c = next_codepoint_handle_ext(iconv_handle, src, n, CH_UNIX, &c_size); src += c_size; c = toupper_m(c); c_size = push_codepoint_handle(iconv_handle, dest+size, c); if (c_size == -1) { talloc_free(dest); return NULL; } size += c_size; } dest[size] = 0; /* trim it so talloc_append_string() works */ dest = talloc_realloc(ctx, dest, char, size+1); talloc_set_name_const(dest, dest); return dest; }
164,672
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int intel_pmu_drain_bts_buffer(void) { struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events); struct debug_store *ds = cpuc->ds; struct bts_record { u64 from; u64 to; u64 flags; }; struct perf_event *event = cpuc->events[X86_PMC_IDX_FIXED_BTS]; struct bts_record *at, *top; struct perf_output_handle handle; struct perf_event_header header; struct perf_sample_data data; struct pt_regs regs; if (!event) return 0; if (!x86_pmu.bts_active) return 0; at = (struct bts_record *)(unsigned long)ds->bts_buffer_base; top = (struct bts_record *)(unsigned long)ds->bts_index; if (top <= at) return 0; ds->bts_index = ds->bts_buffer_base; perf_sample_data_init(&data, 0); data.period = event->hw.last_period; regs.ip = 0; /* * Prepare a generic sample, i.e. fill in the invariant fields. * We will overwrite the from and to address before we output * the sample. */ perf_prepare_sample(&header, &data, event, &regs); if (perf_output_begin(&handle, event, header.size * (top - at), 1, 1)) return 1; for (; at < top; at++) { data.ip = at->from; data.addr = at->to; perf_output_sample(&handle, &header, &data, event); } perf_output_end(&handle); /* There's new data available. */ event->hw.interrupts++; event->pending_kill = POLL_IN; return 1; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
static int intel_pmu_drain_bts_buffer(void) { struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events); struct debug_store *ds = cpuc->ds; struct bts_record { u64 from; u64 to; u64 flags; }; struct perf_event *event = cpuc->events[X86_PMC_IDX_FIXED_BTS]; struct bts_record *at, *top; struct perf_output_handle handle; struct perf_event_header header; struct perf_sample_data data; struct pt_regs regs; if (!event) return 0; if (!x86_pmu.bts_active) return 0; at = (struct bts_record *)(unsigned long)ds->bts_buffer_base; top = (struct bts_record *)(unsigned long)ds->bts_index; if (top <= at) return 0; ds->bts_index = ds->bts_buffer_base; perf_sample_data_init(&data, 0); data.period = event->hw.last_period; regs.ip = 0; /* * Prepare a generic sample, i.e. fill in the invariant fields. * We will overwrite the from and to address before we output * the sample. */ perf_prepare_sample(&header, &data, event, &regs); if (perf_output_begin(&handle, event, header.size * (top - at), 1)) return 1; for (; at < top; at++) { data.ip = at->from; data.addr = at->to; perf_output_sample(&handle, &header, &data, event); } perf_output_end(&handle); /* There's new data available. */ event->hw.interrupts++; event->pending_kill = POLL_IN; return 1; }
165,821
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cp2112_gpio_get_all(struct gpio_chip *chip) { struct cp2112_device *dev = gpiochip_get_data(chip); struct hid_device *hdev = dev->hdev; u8 *buf = dev->in_out_buffer; unsigned long flags; int ret; spin_lock_irqsave(&dev->lock, flags); ret = hid_hw_raw_request(hdev, CP2112_GPIO_GET, buf, CP2112_GPIO_GET_LENGTH, HID_FEATURE_REPORT, HID_REQ_GET_REPORT); if (ret != CP2112_GPIO_GET_LENGTH) { hid_err(hdev, "error requesting GPIO values: %d\n", ret); ret = ret < 0 ? ret : -EIO; goto exit; } ret = buf[1]; exit: spin_unlock_irqrestore(&dev->lock, flags); return ret; } Commit Message: HID: cp2112: fix sleep-while-atomic A recent commit fixing DMA-buffers on stack added a shared transfer buffer protected by a spinlock. This is broken as the USB HID request callbacks can sleep. Fix this up by replacing the spinlock with a mutex. Fixes: 1ffb3c40ffb5 ("HID: cp2112: make transfer buffers DMA capable") Cc: stable <[email protected]> # 4.9 Signed-off-by: Johan Hovold <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-404
static int cp2112_gpio_get_all(struct gpio_chip *chip) { struct cp2112_device *dev = gpiochip_get_data(chip); struct hid_device *hdev = dev->hdev; u8 *buf = dev->in_out_buffer; int ret; mutex_lock(&dev->lock); ret = hid_hw_raw_request(hdev, CP2112_GPIO_GET, buf, CP2112_GPIO_GET_LENGTH, HID_FEATURE_REPORT, HID_REQ_GET_REPORT); if (ret != CP2112_GPIO_GET_LENGTH) { hid_err(hdev, "error requesting GPIO values: %d\n", ret); ret = ret < 0 ? ret : -EIO; goto exit; } ret = buf[1]; exit: mutex_unlock(&dev->lock); return ret; }
168,210
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int write_output(void) { int fd; struct filter_op *fop; struct filter_header fh; size_t ninst, i; u_char *data; /* conver the tree to an array of filter_op */ ninst = compile_tree(&fop); if (fop == NULL) return -E_NOTHANDLED; /* create the file */ fd = open(EF_GBL_OPTIONS->output_file, O_CREAT | O_RDWR | O_TRUNC | O_BINARY, 0644); ON_ERROR(fd, -1, "Can't create file %s", EF_GBL_OPTIONS->output_file); /* display the message */ fprintf(stdout, " Writing output to \'%s\' ", EF_GBL_OPTIONS->output_file); fflush(stdout); /* compute the header */ fh.magic = htons(EC_FILTER_MAGIC); strncpy(fh.version, EC_VERSION, sizeof(fh.version)); fh.data = sizeof(fh); data = create_data_segment(&fh, fop, ninst); /* write the header */ write(fd, &fh, sizeof(struct filter_header)); /* write the data segment */ write(fd, data, fh.code - fh.data); /* write the instructions */ for (i = 0; i <= ninst; i++) { print_progress_bar(&fop[i]); write(fd, &fop[i], sizeof(struct filter_op)); } close(fd); fprintf(stdout, " done.\n\n"); fprintf(stdout, " -> Script encoded into %d instructions.\n\n", (int)(i - 1)); return E_SUCCESS; } Commit Message: Exit gracefully in case of corrupted filters (Closes issue #782) CWE ID: CWE-125
int write_output(void) { int fd; struct filter_op *fop; struct filter_header fh; size_t ninst, i; u_char *data; /* conver the tree to an array of filter_op */ ninst = compile_tree(&fop); if (fop == NULL) return -E_NOTHANDLED; if (ninst == 0) return -E_INVALID; /* create the file */ fd = open(EF_GBL_OPTIONS->output_file, O_CREAT | O_RDWR | O_TRUNC | O_BINARY, 0644); ON_ERROR(fd, -1, "Can't create file %s", EF_GBL_OPTIONS->output_file); /* display the message */ fprintf(stdout, " Writing output to \'%s\' ", EF_GBL_OPTIONS->output_file); fflush(stdout); /* compute the header */ fh.magic = htons(EC_FILTER_MAGIC); strncpy(fh.version, EC_VERSION, sizeof(fh.version)); fh.data = sizeof(fh); data = create_data_segment(&fh, fop, ninst); /* write the header */ write(fd, &fh, sizeof(struct filter_header)); /* write the data segment */ write(fd, data, fh.code - fh.data); /* write the instructions */ for (i = 0; i <= ninst; i++) { print_progress_bar(&fop[i]); write(fd, &fop[i], sizeof(struct filter_op)); } close(fd); fprintf(stdout, " done.\n\n"); fprintf(stdout, " -> Script encoded into %d instructions.\n\n", (int)(i - 1)); return E_SUCCESS; }
168,338
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RunCoeffCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < kNumCoeffs; ++j) input_block[j] = rnd.Rand8() - rnd.Rand8(); fwd_txfm_ref(input_block, output_ref_block, pitch_, tx_type_); REGISTER_STATE_CHECK(RunFwdTxfm(input_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) EXPECT_EQ(output_block[j], output_ref_block[j]); } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunCoeffCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED(16, int16_t, input_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, output_ref_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, output_block[kNumCoeffs]); for (int i = 0; i < count_test_block; ++i) { // Initialize a test block with input range [-mask_, mask_]. for (int j = 0; j < kNumCoeffs; ++j) input_block[j] = (rnd.Rand16() & mask_) - (rnd.Rand16() & mask_); fwd_txfm_ref(input_block, output_ref_block, pitch_, tx_type_); ASM_REGISTER_STATE_CHECK(RunFwdTxfm(input_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) EXPECT_EQ(output_block[j], output_ref_block[j]); } }
174,520
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int process_numeric_entity(const char **buf, unsigned *code_point) { long code_l; int hexadecimal = (**buf == 'x' || **buf == 'X'); /* TODO: XML apparently disallows "X" */ char *endptr; if (hexadecimal && (**buf != '\0')) (*buf)++; /* strtol allows whitespace and other stuff in the beginning * we're not interested */ if ((hexadecimal && !isxdigit(**buf)) || (!hexadecimal && !isdigit(**buf))) { return FAILURE; } code_l = strtol(*buf, &endptr, hexadecimal ? 16 : 10); /* we're guaranteed there were valid digits, so *endptr > buf */ *buf = endptr; if (**buf != ';') return FAILURE; /* many more are invalid, but that depends on whether it's HTML * (and which version) or XML. */ if (code_l > 0x10FFFFL) return FAILURE; if (code_point != NULL) *code_point = (unsigned)code_l; return SUCCESS; } Commit Message: Fix bug #72135 - don't create strings with lengths outside int range CWE ID: CWE-190
static inline int process_numeric_entity(const char **buf, unsigned *code_point) { long code_l; int hexadecimal = (**buf == 'x' || **buf == 'X'); /* TODO: XML apparently disallows "X" */ char *endptr; if (hexadecimal && (**buf != '\0')) (*buf)++; /* strtol allows whitespace and other stuff in the beginning * we're not interested */ if ((hexadecimal && !isxdigit(**buf)) || (!hexadecimal && !isdigit(**buf))) { return FAILURE; } code_l = strtol(*buf, &endptr, hexadecimal ? 16 : 10); /* we're guaranteed there were valid digits, so *endptr > buf */ *buf = endptr; if (**buf != ';') return FAILURE; /* many more are invalid, but that depends on whether it's HTML * (and which version) or XML. */ if (code_l > 0x10FFFFL) return FAILURE; if (code_point != NULL) *code_point = (unsigned)code_l; return SUCCESS; }
167,177
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ftrace_syscall_exit(void *data, struct pt_regs *regs, long ret) { struct trace_array *tr = data; struct ftrace_event_file *ftrace_file; struct syscall_trace_exit *entry; struct syscall_metadata *sys_data; struct ring_buffer_event *event; struct ring_buffer *buffer; unsigned long irq_flags; int pc; int syscall_nr; syscall_nr = trace_get_syscall_nr(current, regs); if (syscall_nr < 0) return; /* Here we're inside tp handler's rcu_read_lock_sched (__DO_TRACE()) */ ftrace_file = rcu_dereference_sched(tr->exit_syscall_files[syscall_nr]); if (!ftrace_file) return; if (ftrace_trigger_soft_disabled(ftrace_file)) return; sys_data = syscall_nr_to_meta(syscall_nr); if (!sys_data) return; local_save_flags(irq_flags); pc = preempt_count(); buffer = tr->trace_buffer.buffer; event = trace_buffer_lock_reserve(buffer, sys_data->exit_event->event.type, sizeof(*entry), irq_flags, pc); if (!event) return; entry = ring_buffer_event_data(event); entry->nr = syscall_nr; entry->ret = syscall_get_return_value(current, regs); event_trigger_unlock_commit(ftrace_file, buffer, event, entry, irq_flags, pc); } Commit Message: tracing/syscalls: Ignore numbers outside NR_syscalls' range ARM has some private syscalls (for example, set_tls(2)) which lie outside the range of NR_syscalls. If any of these are called while syscall tracing is being performed, out-of-bounds array access will occur in the ftrace and perf sys_{enter,exit} handlers. # trace-cmd record -e raw_syscalls:* true && trace-cmd report ... true-653 [000] 384.675777: sys_enter: NR 192 (0, 1000, 3, 4000022, ffffffff, 0) true-653 [000] 384.675812: sys_exit: NR 192 = 1995915264 true-653 [000] 384.675971: sys_enter: NR 983045 (76f74480, 76f74000, 76f74b28, 76f74480, 76f76f74, 1) true-653 [000] 384.675988: sys_exit: NR 983045 = 0 ... # trace-cmd record -e syscalls:* true [ 17.289329] Unable to handle kernel paging request at virtual address aaaaaace [ 17.289590] pgd = 9e71c000 [ 17.289696] [aaaaaace] *pgd=00000000 [ 17.289985] Internal error: Oops: 5 [#1] PREEMPT SMP ARM [ 17.290169] Modules linked in: [ 17.290391] CPU: 0 PID: 704 Comm: true Not tainted 3.18.0-rc2+ #21 [ 17.290585] task: 9f4dab00 ti: 9e710000 task.ti: 9e710000 [ 17.290747] PC is at ftrace_syscall_enter+0x48/0x1f8 [ 17.290866] LR is at syscall_trace_enter+0x124/0x184 Fix this by ignoring out-of-NR_syscalls-bounds syscall numbers. Commit cd0980fc8add "tracing: Check invalid syscall nr while tracing syscalls" added the check for less than zero, but it should have also checked for greater than NR_syscalls. Link: http://lkml.kernel.org/p/[email protected] Fixes: cd0980fc8add "tracing: Check invalid syscall nr while tracing syscalls" Cc: [email protected] # 2.6.33+ Signed-off-by: Rabin Vincent <[email protected]> Signed-off-by: Steven Rostedt <[email protected]> CWE ID: CWE-264
static void ftrace_syscall_exit(void *data, struct pt_regs *regs, long ret) { struct trace_array *tr = data; struct ftrace_event_file *ftrace_file; struct syscall_trace_exit *entry; struct syscall_metadata *sys_data; struct ring_buffer_event *event; struct ring_buffer *buffer; unsigned long irq_flags; int pc; int syscall_nr; syscall_nr = trace_get_syscall_nr(current, regs); if (syscall_nr < 0 || syscall_nr >= NR_syscalls) return; /* Here we're inside tp handler's rcu_read_lock_sched (__DO_TRACE()) */ ftrace_file = rcu_dereference_sched(tr->exit_syscall_files[syscall_nr]); if (!ftrace_file) return; if (ftrace_trigger_soft_disabled(ftrace_file)) return; sys_data = syscall_nr_to_meta(syscall_nr); if (!sys_data) return; local_save_flags(irq_flags); pc = preempt_count(); buffer = tr->trace_buffer.buffer; event = trace_buffer_lock_reserve(buffer, sys_data->exit_event->event.type, sizeof(*entry), irq_flags, pc); if (!event) return; entry = ring_buffer_event_data(event); entry->nr = syscall_nr; entry->ret = syscall_get_return_value(current, regs); event_trigger_unlock_commit(ftrace_file, buffer, event, entry, irq_flags, pc); }
166,255
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CreatePersistentHistogramAllocator() { GlobalHistogramAllocator::GetCreateHistogramResultHistogram(); GlobalHistogramAllocator::CreateWithLocalMemory( kAllocatorMemorySize, 0, "HistogramAllocatorTest"); allocator_ = GlobalHistogramAllocator::Get()->memory_allocator(); } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264
void CreatePersistentHistogramAllocator() { GlobalHistogramAllocator::CreateWithLocalMemory( kAllocatorMemorySize, 0, "HistogramAllocatorTest"); allocator_ = GlobalHistogramAllocator::Get()->memory_allocator(); }
172,130
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GpuChannelHost::Connect( const IPC::ChannelHandle& channel_handle, base::ProcessHandle client_process_for_gpu) { DCHECK(factory_->IsMainThread()); scoped_refptr<base::MessageLoopProxy> io_loop = factory_->GetIOLoopProxy(); channel_.reset(new IPC::SyncChannel( channel_handle, IPC::Channel::MODE_CLIENT, NULL, io_loop, true, factory_->GetShutDownEvent())); sync_filter_ = new IPC::SyncMessageFilter( factory_->GetShutDownEvent()); channel_->AddFilter(sync_filter_.get()); channel_filter_ = new MessageFilter(this); channel_->AddFilter(channel_filter_.get()); state_ = kConnected; Send(new GpuChannelMsg_Initialize(client_process_for_gpu)); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuChannelHost::Connect( const IPC::ChannelHandle& channel_handle) { DCHECK(factory_->IsMainThread()); scoped_refptr<base::MessageLoopProxy> io_loop = factory_->GetIOLoopProxy(); channel_.reset(new IPC::SyncChannel( channel_handle, IPC::Channel::MODE_CLIENT, NULL, io_loop, true, factory_->GetShutDownEvent())); sync_filter_ = new IPC::SyncMessageFilter( factory_->GetShutDownEvent()); channel_->AddFilter(sync_filter_.get()); channel_filter_ = new MessageFilter(this); channel_->AddFilter(channel_filter_.get()); state_ = kConnected; }
170,928
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static PassRefPtr<StaticBitmapImage> cropImage( Image* image, const ParsedOptions& parsedOptions, AlphaDisposition imageFormat = PremultiplyAlpha, ImageDecoder::ColorSpaceOption colorSpaceOp = ImageDecoder::ColorSpaceApplied) { ASSERT(image); IntRect imgRect(IntPoint(), IntSize(image->width(), image->height())); const IntRect srcRect = intersection(imgRect, parsedOptions.cropRect); if (srcRect.isEmpty() && !parsedOptions.premultiplyAlpha) { SkImageInfo info = SkImageInfo::Make(parsedOptions.resizeWidth, parsedOptions.resizeHeight, kN32_SkColorType, kUnpremul_SkAlphaType); RefPtr<ArrayBuffer> dstBuffer = ArrayBuffer::createOrNull( static_cast<size_t>(info.width()) * info.height(), info.bytesPerPixel()); if (!dstBuffer) return nullptr; RefPtr<Uint8Array> dstPixels = Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength()); return StaticBitmapImage::create(newSkImageFromRaster( info, std::move(dstPixels), static_cast<size_t>(info.width()) * info.bytesPerPixel())); } sk_sp<SkImage> skiaImage = image->imageForCurrentFrame(); if ((((!parsedOptions.premultiplyAlpha && !skiaImage->isOpaque()) || !skiaImage) && image->data() && imageFormat == PremultiplyAlpha) || colorSpaceOp == ImageDecoder::ColorSpaceIgnored) { std::unique_ptr<ImageDecoder> decoder(ImageDecoder::create( image->data(), true, parsedOptions.premultiplyAlpha ? ImageDecoder::AlphaPremultiplied : ImageDecoder::AlphaNotPremultiplied, colorSpaceOp)); if (!decoder) return nullptr; skiaImage = ImageBitmap::getSkImageFromDecoder(std::move(decoder)); if (!skiaImage) return nullptr; } if (parsedOptions.cropRect == srcRect && !parsedOptions.shouldScaleInput) { sk_sp<SkImage> croppedSkImage = skiaImage->makeSubset(srcRect); if (parsedOptions.flipY) return StaticBitmapImage::create(flipSkImageVertically( croppedSkImage.get(), parsedOptions.premultiplyAlpha ? PremultiplyAlpha : DontPremultiplyAlpha)); if (parsedOptions.premultiplyAlpha && imageFormat == DontPremultiplyAlpha) return StaticBitmapImage::create( unPremulSkImageToPremul(croppedSkImage.get())); croppedSkImage->preroll(); return StaticBitmapImage::create(std::move(croppedSkImage)); } sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul( parsedOptions.resizeWidth, parsedOptions.resizeHeight); if (!surface) return nullptr; if (srcRect.isEmpty()) return StaticBitmapImage::create(surface->makeImageSnapshot()); SkScalar dstLeft = std::min(0, -parsedOptions.cropRect.x()); SkScalar dstTop = std::min(0, -parsedOptions.cropRect.y()); if (parsedOptions.cropRect.x() < 0) dstLeft = -parsedOptions.cropRect.x(); if (parsedOptions.cropRect.y() < 0) dstTop = -parsedOptions.cropRect.y(); if (parsedOptions.flipY) { surface->getCanvas()->translate(0, surface->height()); surface->getCanvas()->scale(1, -1); } if (parsedOptions.shouldScaleInput) { SkRect drawSrcRect = SkRect::MakeXYWH( parsedOptions.cropRect.x(), parsedOptions.cropRect.y(), parsedOptions.cropRect.width(), parsedOptions.cropRect.height()); SkRect drawDstRect = SkRect::MakeXYWH(0, 0, parsedOptions.resizeWidth, parsedOptions.resizeHeight); SkPaint paint; paint.setFilterQuality(parsedOptions.resizeQuality); surface->getCanvas()->drawImageRect(skiaImage, drawSrcRect, drawDstRect, &paint); } else { surface->getCanvas()->drawImage(skiaImage, dstLeft, dstTop); } skiaImage = surface->makeImageSnapshot(); if (parsedOptions.premultiplyAlpha) { if (imageFormat == DontPremultiplyAlpha) return StaticBitmapImage::create( unPremulSkImageToPremul(skiaImage.get())); return StaticBitmapImage::create(std::move(skiaImage)); } return StaticBitmapImage::create(premulSkImageToUnPremul(skiaImage.get())); } Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull Currently when ImageBitmap's constructor is invoked, we check whether dstSize will overflow size_t or not. The problem comes when we call ArrayBuffer::createOrNull some times in the code. Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap when we call this method, the first parameter is usually width * height. This could overflow unsigned even if it has been checked safe with size_t, the reason is that unsigned is a 32-bit value on 64-bit systems, while size_t is a 64-bit value. This CL makes a change such that we check whether the dstSize will overflow unsigned or not. In this case, we can guarantee that createOrNull will not have any crash. BUG=664139 Review-Url: https://codereview.chromium.org/2500493002 Cr-Commit-Position: refs/heads/master@{#431936} CWE ID: CWE-787
static PassRefPtr<StaticBitmapImage> cropImage( Image* image, const ParsedOptions& parsedOptions, AlphaDisposition imageFormat = PremultiplyAlpha, ImageDecoder::ColorSpaceOption colorSpaceOp = ImageDecoder::ColorSpaceApplied) { ASSERT(image); IntRect imgRect(IntPoint(), IntSize(image->width(), image->height())); const IntRect srcRect = intersection(imgRect, parsedOptions.cropRect); if (srcRect.isEmpty() && !parsedOptions.premultiplyAlpha) { SkImageInfo info = SkImageInfo::Make(parsedOptions.resizeWidth, parsedOptions.resizeHeight, kN32_SkColorType, kUnpremul_SkAlphaType); RefPtr<ArrayBuffer> dstBuffer = ArrayBuffer::createOrNull( static_cast<unsigned>(info.width()) * info.height(), info.bytesPerPixel()); if (!dstBuffer) return nullptr; RefPtr<Uint8Array> dstPixels = Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength()); return StaticBitmapImage::create(newSkImageFromRaster( info, std::move(dstPixels), static_cast<unsigned>(info.width()) * info.bytesPerPixel())); } sk_sp<SkImage> skiaImage = image->imageForCurrentFrame(); if ((((!parsedOptions.premultiplyAlpha && !skiaImage->isOpaque()) || !skiaImage) && image->data() && imageFormat == PremultiplyAlpha) || colorSpaceOp == ImageDecoder::ColorSpaceIgnored) { std::unique_ptr<ImageDecoder> decoder(ImageDecoder::create( image->data(), true, parsedOptions.premultiplyAlpha ? ImageDecoder::AlphaPremultiplied : ImageDecoder::AlphaNotPremultiplied, colorSpaceOp)); if (!decoder) return nullptr; skiaImage = ImageBitmap::getSkImageFromDecoder(std::move(decoder)); if (!skiaImage) return nullptr; } if (parsedOptions.cropRect == srcRect && !parsedOptions.shouldScaleInput) { sk_sp<SkImage> croppedSkImage = skiaImage->makeSubset(srcRect); if (parsedOptions.flipY) return StaticBitmapImage::create(flipSkImageVertically( croppedSkImage.get(), parsedOptions.premultiplyAlpha ? PremultiplyAlpha : DontPremultiplyAlpha)); if (parsedOptions.premultiplyAlpha && imageFormat == DontPremultiplyAlpha) return StaticBitmapImage::create( unPremulSkImageToPremul(croppedSkImage.get())); croppedSkImage->preroll(); return StaticBitmapImage::create(std::move(croppedSkImage)); } sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul( parsedOptions.resizeWidth, parsedOptions.resizeHeight); if (!surface) return nullptr; if (srcRect.isEmpty()) return StaticBitmapImage::create(surface->makeImageSnapshot()); SkScalar dstLeft = std::min(0, -parsedOptions.cropRect.x()); SkScalar dstTop = std::min(0, -parsedOptions.cropRect.y()); if (parsedOptions.cropRect.x() < 0) dstLeft = -parsedOptions.cropRect.x(); if (parsedOptions.cropRect.y() < 0) dstTop = -parsedOptions.cropRect.y(); if (parsedOptions.flipY) { surface->getCanvas()->translate(0, surface->height()); surface->getCanvas()->scale(1, -1); } if (parsedOptions.shouldScaleInput) { SkRect drawSrcRect = SkRect::MakeXYWH( parsedOptions.cropRect.x(), parsedOptions.cropRect.y(), parsedOptions.cropRect.width(), parsedOptions.cropRect.height()); SkRect drawDstRect = SkRect::MakeXYWH(0, 0, parsedOptions.resizeWidth, parsedOptions.resizeHeight); SkPaint paint; paint.setFilterQuality(parsedOptions.resizeQuality); surface->getCanvas()->drawImageRect(skiaImage, drawSrcRect, drawDstRect, &paint); } else { surface->getCanvas()->drawImage(skiaImage, dstLeft, dstTop); } skiaImage = surface->makeImageSnapshot(); if (parsedOptions.premultiplyAlpha) { if (imageFormat == DontPremultiplyAlpha) return StaticBitmapImage::create( unPremulSkImageToPremul(skiaImage.get())); return StaticBitmapImage::create(std::move(skiaImage)); } return StaticBitmapImage::create(premulSkImageToUnPremul(skiaImage.get())); }
172,500
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void cJSON_AddItemReferenceToObject( cJSON *object, const char *string, cJSON *item ) { cJSON_AddItemToObject( object, string, create_reference( item ) ); } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
void cJSON_AddItemReferenceToObject( cJSON *object, const char *string, cJSON *item )
167,266
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: rename_principal_2_svc(rprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg1, *prime_arg2; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; restriction_t *rp; const char *errmsg = NULL; size_t tlen1, tlen2, clen, slen; char *tdots1, *tdots2, *cdots, *sdots; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->src, &prime_arg1) || krb5_unparse_name(handle->context, arg->dest, &prime_arg2)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } tlen1 = strlen(prime_arg1); trunc_name(&tlen1, &tdots1); tlen2 = strlen(prime_arg2); trunc_name(&tlen2, &tdots2); clen = client_name.length; trunc_name(&clen, &cdots); slen = service_name.length; trunc_name(&slen, &sdots); ret.code = KADM5_OK; if (! CHANGEPW_SERVICE(rqstp)) { if (!kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_DELETE, arg->src, NULL)) ret.code = KADM5_AUTH_DELETE; /* any restrictions at all on the ADD kills the RENAME */ if (!kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD, arg->dest, &rp) || rp) { if (ret.code == KADM5_AUTH_DELETE) ret.code = KADM5_AUTH_INSUFFICIENT; else ret.code = KADM5_AUTH_ADD; } } else ret.code = KADM5_AUTH_INSUFFICIENT; if (ret.code != KADM5_OK) { /* okay to cast lengths to int because trunc_name limits max value */ krb5_klog_syslog(LOG_NOTICE, _("Unauthorized request: kadm5_rename_principal, " "%.*s%s to %.*s%s, " "client=%.*s%s, service=%.*s%s, addr=%s"), (int)tlen1, prime_arg1, tdots1, (int)tlen2, prime_arg2, tdots2, (int)clen, (char *)client_name.value, cdots, (int)slen, (char *)service_name.value, sdots, client_addr(rqstp->rq_xprt)); } else { ret.code = kadm5_rename_principal((void *)handle, arg->src, arg->dest); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); /* okay to cast lengths to int because trunc_name limits max value */ krb5_klog_syslog(LOG_NOTICE, _("Request: kadm5_rename_principal, " "%.*s%s to %.*s%s, %s, " "client=%.*s%s, service=%.*s%s, addr=%s"), (int)tlen1, prime_arg1, tdots1, (int)tlen2, prime_arg2, tdots2, errmsg ? errmsg : _("success"), (int)clen, (char *)client_name.value, cdots, (int)slen, (char *)service_name.value, sdots, client_addr(rqstp->rq_xprt)); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg1); free(prime_arg2); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
rename_principal_2_svc(rprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg1 = NULL, *prime_arg2 = NULL; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; restriction_t *rp; const char *errmsg = NULL; size_t tlen1, tlen2, clen, slen; char *tdots1, *tdots2, *cdots, *sdots; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->src, &prime_arg1) || krb5_unparse_name(handle->context, arg->dest, &prime_arg2)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } tlen1 = strlen(prime_arg1); trunc_name(&tlen1, &tdots1); tlen2 = strlen(prime_arg2); trunc_name(&tlen2, &tdots2); clen = client_name.length; trunc_name(&clen, &cdots); slen = service_name.length; trunc_name(&slen, &sdots); ret.code = KADM5_OK; if (! CHANGEPW_SERVICE(rqstp)) { if (!kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_DELETE, arg->src, NULL)) ret.code = KADM5_AUTH_DELETE; /* any restrictions at all on the ADD kills the RENAME */ if (!kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD, arg->dest, &rp) || rp) { if (ret.code == KADM5_AUTH_DELETE) ret.code = KADM5_AUTH_INSUFFICIENT; else ret.code = KADM5_AUTH_ADD; } } else ret.code = KADM5_AUTH_INSUFFICIENT; if (ret.code != KADM5_OK) { /* okay to cast lengths to int because trunc_name limits max value */ krb5_klog_syslog(LOG_NOTICE, _("Unauthorized request: kadm5_rename_principal, " "%.*s%s to %.*s%s, " "client=%.*s%s, service=%.*s%s, addr=%s"), (int)tlen1, prime_arg1, tdots1, (int)tlen2, prime_arg2, tdots2, (int)clen, (char *)client_name.value, cdots, (int)slen, (char *)service_name.value, sdots, client_addr(rqstp->rq_xprt)); } else { ret.code = kadm5_rename_principal((void *)handle, arg->src, arg->dest); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); /* okay to cast lengths to int because trunc_name limits max value */ krb5_klog_syslog(LOG_NOTICE, _("Request: kadm5_rename_principal, " "%.*s%s to %.*s%s, %s, " "client=%.*s%s, service=%.*s%s, addr=%s"), (int)tlen1, prime_arg1, tdots1, (int)tlen2, prime_arg2, tdots2, errmsg ? errmsg : _("success"), (int)clen, (char *)client_name.value, cdots, (int)slen, (char *)service_name.value, sdots, client_addr(rqstp->rq_xprt)); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } exit_func: free(prime_arg1); free(prime_arg2); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,523
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MediaElementAudioSourceHandler::OnCurrentSrcChanged( const KURL& current_src) { DCHECK(IsMainThread()); Locker<MediaElementAudioSourceHandler> locker(*this); passes_current_src_cors_access_check_ = PassesCurrentSrcCORSAccessCheck(current_src); maybe_print_cors_message_ = !passes_current_src_cors_access_check_; current_src_string_ = current_src.GetString(); } Commit Message: Redirect should not circumvent same-origin restrictions Check whether we have access to the audio data when the format is set. At this point we have enough information to determine this. The old approach based on when the src was changed was incorrect because at the point, we only know the new src; none of the response headers have been read yet. This new approach also removes the incorrect message reported in 619114. Bug: 826552, 619114 Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6 Reviewed-on: https://chromium-review.googlesource.com/1069540 Commit-Queue: Raymond Toy <[email protected]> Reviewed-by: Yutaka Hirano <[email protected]> Reviewed-by: Hongchan Choi <[email protected]> Cr-Commit-Position: refs/heads/master@{#564313} CWE ID: CWE-20
void MediaElementAudioSourceHandler::OnCurrentSrcChanged( bool MediaElementAudioSourceHandler::WouldTaintOrigin() { // If we're cross-origin and allowed access vie CORS, we're not tainted. if (MediaElement()->GetWebMediaPlayer()->DidPassCORSAccessCheck()) { return false; } // Handles the case where the url is a redirect to another site that we're not // allowed to access. if (!MediaElement()->HasSingleSecurityOrigin()) { return true; }
173,145
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: update_display(struct display *dp) /* called once after the first read to update all the info, original_pp and * original_ip must have been filled in. */ { png_structp pp; png_infop ip; /* Now perform the initial read with a 0 tranform. */ read_png(dp, &dp->original_file, "original read", 0/*no transform*/); /* Move the result to the 'original' fields */ dp->original_pp = pp = dp->read_pp, dp->read_pp = NULL; dp->original_ip = ip = dp->read_ip, dp->read_ip = NULL; dp->original_rowbytes = png_get_rowbytes(pp, ip); if (dp->original_rowbytes == 0) display_log(dp, LIBPNG_BUG, "png_get_rowbytes returned 0"); dp->chunks = png_get_valid(pp, ip, 0xffffffff); if ((dp->chunks & PNG_INFO_IDAT) == 0) /* set by png_read_png */ display_log(dp, LIBPNG_BUG, "png_read_png did not set IDAT flag"); dp->original_rows = png_get_rows(pp, ip); if (dp->original_rows == NULL) display_log(dp, LIBPNG_BUG, "png_read_png did not create row buffers"); if (!png_get_IHDR(pp, ip, &dp->width, &dp->height, &dp->bit_depth, &dp->color_type, &dp->interlace_method, &dp->compression_method, &dp->filter_method)) display_log(dp, LIBPNG_BUG, "png_get_IHDR failed"); /* 'active' transforms are discovered based on the original image format; * running one active transform can activate others. At present the code * does not attempt to determine the closure. */ { png_uint_32 chunks = dp->chunks; int active = 0, inactive = 0; int ct = dp->color_type; int bd = dp->bit_depth; unsigned int i; for (i=0; i<TTABLE_SIZE; ++i) { int transform = transform_info[i].transform; if ((transform_info[i].valid_chunks == 0 || (transform_info[i].valid_chunks & chunks) != 0) && (transform_info[i].color_mask_required & ct) == transform_info[i].color_mask_required && (transform_info[i].color_mask_absent & ct) == 0 && (transform_info[i].bit_depths & bd) != 0 && (transform_info[i].when & TRANSFORM_R) != 0) active |= transform; else if ((transform_info[i].when & TRANSFORM_R) != 0) inactive |= transform; } /* Some transforms appear multiple times in the table; the 'active' status * is the logical OR of these and the inactive status must be adjusted to * take this into account. */ inactive &= ~active; dp->active_transforms = active; dp->ignored_transforms = inactive; /* excluding write-only transforms */ if (active == 0) display_log(dp, INTERNAL_ERROR, "bad transform table"); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
update_display(struct display *dp) /* called once after the first read to update all the info, original_pp and * original_ip must have been filled in. */ { png_structp pp; png_infop ip; /* Now perform the initial read with a 0 tranform. */ read_png(dp, &dp->original_file, "original read", 0/*no transform*/); /* Move the result to the 'original' fields */ dp->original_pp = pp = dp->read_pp, dp->read_pp = NULL; dp->original_ip = ip = dp->read_ip, dp->read_ip = NULL; dp->original_rowbytes = png_get_rowbytes(pp, ip); if (dp->original_rowbytes == 0) display_log(dp, LIBPNG_BUG, "png_get_rowbytes returned 0"); dp->chunks = png_get_valid(pp, ip, 0xffffffff); if ((dp->chunks & PNG_INFO_IDAT) == 0) /* set by png_read_png */ display_log(dp, LIBPNG_BUG, "png_read_png did not set IDAT flag"); dp->original_rows = png_get_rows(pp, ip); if (dp->original_rows == NULL) display_log(dp, LIBPNG_BUG, "png_read_png did not create row buffers"); if (!png_get_IHDR(pp, ip, &dp->width, &dp->height, &dp->bit_depth, &dp->color_type, &dp->interlace_method, &dp->compression_method, &dp->filter_method)) display_log(dp, LIBPNG_BUG, "png_get_IHDR failed"); /* 'active' transforms are discovered based on the original image format; * running one active transform can activate others. At present the code * does not attempt to determine the closure. */ { png_uint_32 chunks = dp->chunks; int active = 0, inactive = 0; int ct = dp->color_type; int bd = dp->bit_depth; unsigned int i; for (i=0; i<TTABLE_SIZE; ++i) if (transform_info[i].name != NULL) { int transform = transform_info[i].transform; if ((transform_info[i].valid_chunks == 0 || (transform_info[i].valid_chunks & chunks) != 0) && (transform_info[i].color_mask_required & ct) == transform_info[i].color_mask_required && (transform_info[i].color_mask_absent & ct) == 0 && (transform_info[i].bit_depths & bd) != 0 && (transform_info[i].when & TRANSFORM_R) != 0) active |= transform; else if ((transform_info[i].when & TRANSFORM_R) != 0) inactive |= transform; } /* Some transforms appear multiple times in the table; the 'active' status * is the logical OR of these and the inactive status must be adjusted to * take this into account. */ inactive &= ~active; dp->active_transforms = active; dp->ignored_transforms = inactive; /* excluding write-only transforms */ } }
173,591
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AddExpectationsForSimulatedAttrib0( GLsizei num_vertices, GLuint buffer_id) { EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, kServiceAttrib0BufferId)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BufferData(GL_ARRAY_BUFFER, num_vertices * sizeof(GLfloat) * 4, _, GL_DYNAMIC_DRAW)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BufferSubData( GL_ARRAY_BUFFER, 0, num_vertices * sizeof(GLfloat) * 4, _)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, 0)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, buffer_id)) .Times(1) .RetiresOnSaturation(); } Commit Message: Revert "Revert 100494 - Fix bug in SimulateAttrib0.""" TEST=none BUG=95625 [email protected] Review URL: http://codereview.chromium.org/7796016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@100507 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void AddExpectationsForSimulatedAttrib0( void AddExpectationsForSimulatedAttrib0WithError( GLsizei num_vertices, GLuint buffer_id, GLenum error) { if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) { return; } EXPECT_CALL(*gl_, GetError()) .WillOnce(Return(GL_NO_ERROR)) .WillOnce(Return(error)) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, kServiceAttrib0BufferId)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BufferData(GL_ARRAY_BUFFER, num_vertices * sizeof(GLfloat) * 4, _, GL_DYNAMIC_DRAW)) .Times(1) .RetiresOnSaturation(); if (error == GL_NO_ERROR) { EXPECT_CALL(*gl_, BufferSubData( GL_ARRAY_BUFFER, 0, num_vertices * sizeof(GLfloat) * 4, _)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, 0)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, buffer_id)) .Times(1) .RetiresOnSaturation(); } } void AddExpectationsForSimulatedAttrib0( GLsizei num_vertices, GLuint buffer_id) { AddExpectationsForSimulatedAttrib0WithError( num_vertices, buffer_id, GL_NO_ERROR); }
170,334
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: archive_acl_from_text_l(struct archive_acl *acl, const char *text, int want_type, struct archive_string_conv *sc) { struct { const char *start; const char *end; } field[6], name; const char *s, *st; int numfields, fields, n, r, sol, ret; int type, types, tag, permset, id; size_t len; char sep; switch (want_type) { case ARCHIVE_ENTRY_ACL_TYPE_POSIX1E: want_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; __LA_FALLTHROUGH; case ARCHIVE_ENTRY_ACL_TYPE_ACCESS: case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT: numfields = 5; break; case ARCHIVE_ENTRY_ACL_TYPE_NFS4: numfields = 6; break; default: return (ARCHIVE_FATAL); } ret = ARCHIVE_OK; types = 0; while (text != NULL && *text != '\0') { /* * Parse the fields out of the next entry, * advance 'text' to start of next entry. */ fields = 0; do { const char *start, *end; next_field(&text, &start, &end, &sep); if (fields < numfields) { field[fields].start = start; field[fields].end = end; } ++fields; } while (sep == ':'); /* Set remaining fields to blank. */ for (n = fields; n < numfields; ++n) field[n].start = field[n].end = NULL; if (field[0].start != NULL && *(field[0].start) == '#') { /* Comment, skip entry */ continue; } n = 0; sol = 0; id = -1; permset = 0; name.start = name.end = NULL; if (want_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) { /* POSIX.1e ACLs */ /* * Default keyword "default:user::rwx" * if found, we have one more field * * We also support old Solaris extension: * "defaultuser::rwx" is the default ACL corresponding * to "user::rwx", etc. valid only for first field */ s = field[0].start; len = field[0].end - field[0].start; if (*s == 'd' && (len == 1 || (len >= 7 && memcmp((s + 1), "efault", 6) == 0))) { type = ARCHIVE_ENTRY_ACL_TYPE_DEFAULT; if (len > 7) field[0].start += 7; else n = 1; } else type = want_type; /* Check for a numeric ID in field n+1 or n+3. */ isint(field[n + 1].start, field[n + 1].end, &id); /* Field n+3 is optional. */ if (id == -1 && fields > (n + 3)) isint(field[n + 3].start, field[n + 3].end, &id); tag = 0; s = field[n].start; st = field[n].start + 1; len = field[n].end - field[n].start; switch (*s) { case 'u': if (len == 1 || (len == 4 && memcmp(st, "ser", 3) == 0)) tag = ARCHIVE_ENTRY_ACL_USER_OBJ; break; case 'g': if (len == 1 || (len == 5 && memcmp(st, "roup", 4) == 0)) tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; break; case 'o': if (len == 1 || (len == 5 && memcmp(st, "ther", 4) == 0)) tag = ARCHIVE_ENTRY_ACL_OTHER; break; case 'm': if (len == 1 || (len == 4 && memcmp(st, "ask", 3) == 0)) tag = ARCHIVE_ENTRY_ACL_MASK; break; default: break; } switch (tag) { case ARCHIVE_ENTRY_ACL_OTHER: case ARCHIVE_ENTRY_ACL_MASK: if (fields == (n + 2) && field[n + 1].start < field[n + 1].end && ismode(field[n + 1].start, field[n + 1].end, &permset)) { /* This is Solaris-style "other:rwx" */ sol = 1; } else if (fields == (n + 3) && field[n + 1].start < field[n + 1].end) { /* Invalid mask or other field */ ret = ARCHIVE_WARN; continue; } break; case ARCHIVE_ENTRY_ACL_USER_OBJ: case ARCHIVE_ENTRY_ACL_GROUP_OBJ: if (id != -1 || field[n + 1].start < field[n + 1].end) { name = field[n + 1]; if (tag == ARCHIVE_ENTRY_ACL_USER_OBJ) tag = ARCHIVE_ENTRY_ACL_USER; else tag = ARCHIVE_ENTRY_ACL_GROUP; } break; default: /* Invalid tag, skip entry */ ret = ARCHIVE_WARN; continue; } /* * Without "default:" we expect mode in field 3 * Exception: Solaris other and mask fields */ if (permset == 0 && !ismode(field[n + 2 - sol].start, field[n + 2 - sol].end, &permset)) { /* Invalid mode, skip entry */ ret = ARCHIVE_WARN; continue; } } else { /* NFS4 ACLs */ s = field[0].start; len = field[0].end - field[0].start; tag = 0; switch (len) { case 4: if (memcmp(s, "user", 4) == 0) tag = ARCHIVE_ENTRY_ACL_USER; break; case 5: if (memcmp(s, "group", 5) == 0) tag = ARCHIVE_ENTRY_ACL_GROUP; break; case 6: if (memcmp(s, "owner@", 6) == 0) tag = ARCHIVE_ENTRY_ACL_USER_OBJ; else if (memcmp(s, "group@", 6) == 0) tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; break; case 9: if (memcmp(s, "everyone@", 9) == 0) tag = ARCHIVE_ENTRY_ACL_EVERYONE; break; default: break; } if (tag == 0) { /* Invalid tag, skip entry */ ret = ARCHIVE_WARN; continue; } else if (tag == ARCHIVE_ENTRY_ACL_USER || tag == ARCHIVE_ENTRY_ACL_GROUP) { n = 1; name = field[1]; isint(name.start, name.end, &id); } else n = 0; if (!is_nfs4_perms(field[1 + n].start, field[1 + n].end, &permset)) { /* Invalid NFSv4 perms, skip entry */ ret = ARCHIVE_WARN; continue; } if (!is_nfs4_flags(field[2 + n].start, field[2 + n].end, &permset)) { /* Invalid NFSv4 flags, skip entry */ ret = ARCHIVE_WARN; continue; } s = field[3 + n].start; len = field[3 + n].end - field[3 + n].start; type = 0; if (len == 4) { if (memcmp(s, "deny", 4) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_DENY; } else if (len == 5) { if (memcmp(s, "allow", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW; else if (memcmp(s, "audit", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_AUDIT; else if (memcmp(s, "alarm", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_ALARM; } if (type == 0) { /* Invalid entry type, skip entry */ ret = ARCHIVE_WARN; continue; } isint(field[4 + n].start, field[4 + n].end, &id); } /* Add entry to the internal list. */ r = archive_acl_add_entry_len_l(acl, type, permset, tag, id, name.start, name.end - name.start, sc); if (r < ARCHIVE_WARN) return (r); if (r != ARCHIVE_OK) ret = ARCHIVE_WARN; types |= type; } /* Reset ACL */ archive_acl_reset(acl, types); return (ret); } Commit Message: Skip 0-length ACL fields Currently, it is possible to create an archive that crashes bsdtar with a malformed ACL: Program received signal SIGSEGV, Segmentation fault. archive_acl_from_text_l (acl=<optimised out>, text=0x7e2e92 "", want_type=<optimised out>, sc=<optimised out>) at libarchive/archive_acl.c:1726 1726 switch (*s) { (gdb) p n $1 = 1 (gdb) p field[n] $2 = {start = 0x0, end = 0x0} Stop this by checking that the length is not zero before beginning the switch statement. I am pretty sure this is the bug mentioned in the qsym paper [1], and I was able to replicate it with a qsym + AFL + afl-rb setup. [1] https://www.usenix.org/conference/usenixsecurity18/presentation/yun CWE ID: CWE-476
archive_acl_from_text_l(struct archive_acl *acl, const char *text, int want_type, struct archive_string_conv *sc) { struct { const char *start; const char *end; } field[6], name; const char *s, *st; int numfields, fields, n, r, sol, ret; int type, types, tag, permset, id; size_t len; char sep; switch (want_type) { case ARCHIVE_ENTRY_ACL_TYPE_POSIX1E: want_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; __LA_FALLTHROUGH; case ARCHIVE_ENTRY_ACL_TYPE_ACCESS: case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT: numfields = 5; break; case ARCHIVE_ENTRY_ACL_TYPE_NFS4: numfields = 6; break; default: return (ARCHIVE_FATAL); } ret = ARCHIVE_OK; types = 0; while (text != NULL && *text != '\0') { /* * Parse the fields out of the next entry, * advance 'text' to start of next entry. */ fields = 0; do { const char *start, *end; next_field(&text, &start, &end, &sep); if (fields < numfields) { field[fields].start = start; field[fields].end = end; } ++fields; } while (sep == ':'); /* Set remaining fields to blank. */ for (n = fields; n < numfields; ++n) field[n].start = field[n].end = NULL; if (field[0].start != NULL && *(field[0].start) == '#') { /* Comment, skip entry */ continue; } n = 0; sol = 0; id = -1; permset = 0; name.start = name.end = NULL; if (want_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) { /* POSIX.1e ACLs */ /* * Default keyword "default:user::rwx" * if found, we have one more field * * We also support old Solaris extension: * "defaultuser::rwx" is the default ACL corresponding * to "user::rwx", etc. valid only for first field */ s = field[0].start; len = field[0].end - field[0].start; if (*s == 'd' && (len == 1 || (len >= 7 && memcmp((s + 1), "efault", 6) == 0))) { type = ARCHIVE_ENTRY_ACL_TYPE_DEFAULT; if (len > 7) field[0].start += 7; else n = 1; } else type = want_type; /* Check for a numeric ID in field n+1 or n+3. */ isint(field[n + 1].start, field[n + 1].end, &id); /* Field n+3 is optional. */ if (id == -1 && fields > (n + 3)) isint(field[n + 3].start, field[n + 3].end, &id); tag = 0; s = field[n].start; st = field[n].start + 1; len = field[n].end - field[n].start; if (len == 0) { ret = ARCHIVE_WARN; continue; } switch (*s) { case 'u': if (len == 1 || (len == 4 && memcmp(st, "ser", 3) == 0)) tag = ARCHIVE_ENTRY_ACL_USER_OBJ; break; case 'g': if (len == 1 || (len == 5 && memcmp(st, "roup", 4) == 0)) tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; break; case 'o': if (len == 1 || (len == 5 && memcmp(st, "ther", 4) == 0)) tag = ARCHIVE_ENTRY_ACL_OTHER; break; case 'm': if (len == 1 || (len == 4 && memcmp(st, "ask", 3) == 0)) tag = ARCHIVE_ENTRY_ACL_MASK; break; default: break; } switch (tag) { case ARCHIVE_ENTRY_ACL_OTHER: case ARCHIVE_ENTRY_ACL_MASK: if (fields == (n + 2) && field[n + 1].start < field[n + 1].end && ismode(field[n + 1].start, field[n + 1].end, &permset)) { /* This is Solaris-style "other:rwx" */ sol = 1; } else if (fields == (n + 3) && field[n + 1].start < field[n + 1].end) { /* Invalid mask or other field */ ret = ARCHIVE_WARN; continue; } break; case ARCHIVE_ENTRY_ACL_USER_OBJ: case ARCHIVE_ENTRY_ACL_GROUP_OBJ: if (id != -1 || field[n + 1].start < field[n + 1].end) { name = field[n + 1]; if (tag == ARCHIVE_ENTRY_ACL_USER_OBJ) tag = ARCHIVE_ENTRY_ACL_USER; else tag = ARCHIVE_ENTRY_ACL_GROUP; } break; default: /* Invalid tag, skip entry */ ret = ARCHIVE_WARN; continue; } /* * Without "default:" we expect mode in field 3 * Exception: Solaris other and mask fields */ if (permset == 0 && !ismode(field[n + 2 - sol].start, field[n + 2 - sol].end, &permset)) { /* Invalid mode, skip entry */ ret = ARCHIVE_WARN; continue; } } else { /* NFS4 ACLs */ s = field[0].start; len = field[0].end - field[0].start; tag = 0; switch (len) { case 4: if (memcmp(s, "user", 4) == 0) tag = ARCHIVE_ENTRY_ACL_USER; break; case 5: if (memcmp(s, "group", 5) == 0) tag = ARCHIVE_ENTRY_ACL_GROUP; break; case 6: if (memcmp(s, "owner@", 6) == 0) tag = ARCHIVE_ENTRY_ACL_USER_OBJ; else if (memcmp(s, "group@", 6) == 0) tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; break; case 9: if (memcmp(s, "everyone@", 9) == 0) tag = ARCHIVE_ENTRY_ACL_EVERYONE; break; default: break; } if (tag == 0) { /* Invalid tag, skip entry */ ret = ARCHIVE_WARN; continue; } else if (tag == ARCHIVE_ENTRY_ACL_USER || tag == ARCHIVE_ENTRY_ACL_GROUP) { n = 1; name = field[1]; isint(name.start, name.end, &id); } else n = 0; if (!is_nfs4_perms(field[1 + n].start, field[1 + n].end, &permset)) { /* Invalid NFSv4 perms, skip entry */ ret = ARCHIVE_WARN; continue; } if (!is_nfs4_flags(field[2 + n].start, field[2 + n].end, &permset)) { /* Invalid NFSv4 flags, skip entry */ ret = ARCHIVE_WARN; continue; } s = field[3 + n].start; len = field[3 + n].end - field[3 + n].start; type = 0; if (len == 4) { if (memcmp(s, "deny", 4) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_DENY; } else if (len == 5) { if (memcmp(s, "allow", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW; else if (memcmp(s, "audit", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_AUDIT; else if (memcmp(s, "alarm", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_ALARM; } if (type == 0) { /* Invalid entry type, skip entry */ ret = ARCHIVE_WARN; continue; } isint(field[4 + n].start, field[4 + n].end, &id); } /* Add entry to the internal list. */ r = archive_acl_add_entry_len_l(acl, type, permset, tag, id, name.start, name.end - name.start, sc); if (r < ARCHIVE_WARN) return (r); if (r != ARCHIVE_OK) ret = ARCHIVE_WARN; types |= type; } /* Reset ACL */ archive_acl_reset(acl, types); return (ret); }
168,929
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void on_read(h2o_socket_t *sock, int status) { h2o_http2_conn_t *conn = sock->data; if (status != 0) { h2o_socket_read_stop(conn->sock); close_connection(conn); return; } update_idle_timeout(conn); parse_input(conn); /* write immediately, if there is no write in flight and if pending write exists */ if (h2o_timeout_is_linked(&conn->_write.timeout_entry)) { h2o_timeout_unlink(&conn->_write.timeout_entry); do_emit_writereq(conn); } } Commit Message: h2: use after free on premature connection close #920 lib/http2/connection.c:on_read() calls parse_input(), which might free `conn`. It does so in particular if the connection preface isn't the expected one in expect_preface(). `conn` is then used after the free in `if (h2o_timeout_is_linked(&conn->_write.timeout_entry)`. We fix this by adding a return value to close_connection that returns a negative value if `conn` has been free'd and can't be used anymore. Credits for finding the bug to Tim Newsham. CWE ID:
static void on_read(h2o_socket_t *sock, int status) { h2o_http2_conn_t *conn = sock->data; if (status != 0) { h2o_socket_read_stop(conn->sock); close_connection(conn); return; } update_idle_timeout(conn); if (parse_input(conn) != 0) return; /* write immediately, if there is no write in flight and if pending write exists */ if (h2o_timeout_is_linked(&conn->_write.timeout_entry)) { h2o_timeout_unlink(&conn->_write.timeout_entry); do_emit_writereq(conn); } }
167,226
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void __skb_tstamp_tx(struct sk_buff *orig_skb, struct skb_shared_hwtstamps *hwtstamps, struct sock *sk, int tstype) { struct sk_buff *skb; bool tsonly; if (!sk) return; tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY; if (!skb_may_tx_timestamp(sk, tsonly)) return; if (tsonly) { #ifdef CONFIG_INET if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) && sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) skb = tcp_get_timestamping_opt_stats(sk); else #endif skb = alloc_skb(0, GFP_ATOMIC); } else { skb = skb_clone(orig_skb, GFP_ATOMIC); } if (!skb) return; if (tsonly) { skb_shinfo(skb)->tx_flags = skb_shinfo(orig_skb)->tx_flags; skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey; } if (hwtstamps) *skb_hwtstamps(skb) = *hwtstamps; else skb->tstamp = ktime_get_real(); __skb_complete_tx_timestamp(skb, sk, tstype); } Commit Message: tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled while packets are collected on the error queue. So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags is not enough to safely assume that the skb contains OPT_STATS data. Add a bit in sock_exterr_skb to indicate whether the skb contains opt_stats data. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <[email protected]> Signed-off-by: Soheil Hassas Yeganeh <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125
void __skb_tstamp_tx(struct sk_buff *orig_skb, struct skb_shared_hwtstamps *hwtstamps, struct sock *sk, int tstype) { struct sk_buff *skb; bool tsonly, opt_stats = false; if (!sk) return; tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY; if (!skb_may_tx_timestamp(sk, tsonly)) return; if (tsonly) { #ifdef CONFIG_INET if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) && sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) { skb = tcp_get_timestamping_opt_stats(sk); opt_stats = true; } else #endif skb = alloc_skb(0, GFP_ATOMIC); } else { skb = skb_clone(orig_skb, GFP_ATOMIC); } if (!skb) return; if (tsonly) { skb_shinfo(skb)->tx_flags = skb_shinfo(orig_skb)->tx_flags; skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey; } if (hwtstamps) *skb_hwtstamps(skb) = *hwtstamps; else skb->tstamp = ktime_get_real(); __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats); }
170,072
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gplotMakeOutput(GPLOT *gplot) { char buf[L_BUF_SIZE]; char *cmdname; l_int32 ignore; PROCNAME("gplotMakeOutput"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); gplotGenCommandFile(gplot); gplotGenDataFiles(gplot); cmdname = genPathname(gplot->cmdname, NULL); #ifndef _WIN32 snprintf(buf, L_BUF_SIZE, "gnuplot %s", cmdname); #else snprintf(buf, L_BUF_SIZE, "wgnuplot %s", cmdname); #endif /* _WIN32 */ #ifndef OS_IOS /* iOS 11 does not support system() */ ignore = system(buf); /* gnuplot || wgnuplot */ #endif /* !OS_IOS */ LEPT_FREE(cmdname); return 0; } Commit Message: Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf(). CWE ID: CWE-119
gplotMakeOutput(GPLOT *gplot) { char buf[L_BUFSIZE]; char *cmdname; l_int32 ignore; PROCNAME("gplotMakeOutput"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); gplotGenCommandFile(gplot); gplotGenDataFiles(gplot); cmdname = genPathname(gplot->cmdname, NULL); #ifndef _WIN32 snprintf(buf, L_BUFSIZE, "gnuplot %s", cmdname); #else snprintf(buf, L_BUFSIZE, "wgnuplot %s", cmdname); #endif /* _WIN32 */ #ifndef OS_IOS /* iOS 11 does not support system() */ ignore = system(buf); /* gnuplot || wgnuplot */ #endif /* !OS_IOS */ LEPT_FREE(cmdname); return 0; }
169,326
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ssl3_get_client_hello(SSL *s) { int i, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1, cookie_valid = 0; unsigned int cookie_len; long n; unsigned long id; unsigned char *p, *d; SSL_CIPHER *c; #ifndef OPENSSL_NO_COMP unsigned char *q; SSL_COMP *comp = NULL; #endif STACK_OF(SSL_CIPHER) *ciphers = NULL; if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet) goto retry_cert; /* * We do this so that we will respond with our native type. If we are * TLSv1 and we get SSLv3, we will respond with TLSv1, This down * switching should be handled by a different method. If we are SSLv3, we * will respond with SSLv3, even if prompted with TLSv1. */ if (s->state == SSL3_ST_SR_CLNT_HELLO_A) { s->state = SSL3_ST_SR_CLNT_HELLO_B; } s->first_packet = 1; n = s->method->ssl_get_message(s, SSL3_ST_SR_CLNT_HELLO_B, SSL3_ST_SR_CLNT_HELLO_C, SSL3_MT_CLIENT_HELLO, SSL3_RT_MAX_PLAIN_LENGTH, &ok); if (!ok) return ((int)n); s->first_packet = 0; d = p = (unsigned char *)s->init_msg; /* * 2 bytes for client version, SSL3_RANDOM_SIZE bytes for random, 1 byte * for session id length */ if (n < 2 + SSL3_RANDOM_SIZE + 1) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* * use version from inside client hello, not from record header (may * differ: see RFC 2246, Appendix E, second paragraph) */ s->client_version = (((int)p[0]) << 8) | (int)p[1]; p += 2; if (SSL_IS_DTLS(s) ? (s->client_version > s->version && s->method->version != DTLS_ANY_VERSION) : (s->client_version < s->version)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); if ((s->client_version >> 8) == SSL3_VERSION_MAJOR && !s->enc_write_ctx && !s->write_hash) { /* * similar to ssl3_get_record, send alert using remote version * number */ s->version = s->client_version; } al = SSL_AD_PROTOCOL_VERSION; goto f_err; } /* * If we require cookies and this ClientHello doesn't contain one, just * return since we do not want to allocate any memory yet. So check * cookie length... */ if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) { unsigned int session_length, cookie_length; session_length = *(p + SSL3_RANDOM_SIZE); if (p + SSL3_RANDOM_SIZE + session_length + 1 >= d + n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1); if (cookie_length == 0) return 1; } /* load the client random */ memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE); p += SSL3_RANDOM_SIZE; /* get the session-id */ j = *(p++); if (p + j > d + n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } if ((j < 0) || (j > SSL_MAX_SSL_SESSION_ID_LENGTH)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } s->hit = 0; /* * Versions before 0.9.7 always allow clients to resume sessions in * renegotiation. 0.9.7 and later allow this by default, but optionally * ignore resumption requests with flag * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather * than a change to default behavior so that applications relying on this * for security won't even compile against older library versions). * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to * request renegotiation but not a new session (s->new_session remains * unset): for servers, this essentially just means that the * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be ignored. */ if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) { if (!ssl_get_new_session(s, 1)) goto err; } else { i = ssl_get_prev_session(s, p, j, d + n); /* * Only resume if the session's version matches the negotiated * version. * RFC 5246 does not provide much useful advice on resumption * with a different protocol version. It doesn't forbid it but * the sanity of such behaviour would be questionable. * In practice, clients do not accept a version mismatch and * will abort the handshake with an error. */ if (i == 1 && s->version == s->session->ssl_version) { /* previous * session */ s->hit = 1; } else if (i == -1) goto err; else { /* i == 0 */ if (!ssl_get_new_session(s, 1)) goto err; } } p += j; if (SSL_IS_DTLS(s)) { /* cookie stuff */ if (p + 1 > d + n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } cookie_len = *(p++); if (p + cookie_len > d + n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* * The ClientHello may contain a cookie even if the * HelloVerify message has not been sent--make sure that it * does not cause an overflow. */ if (cookie_len > sizeof(s->d1->rcvd_cookie)) { /* too much data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* verify the cookie if appropriate option is set. */ if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) { memcpy(s->d1->rcvd_cookie, p, cookie_len); if (s->ctx->app_verify_cookie_cb != NULL) { if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie, cookie_len) == 0) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* else cookie verification succeeded */ } /* default verification */ else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie, s->d1->cookie_len) != 0) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } cookie_valid = 1; } p += cookie_len; if (s->method->version == DTLS_ANY_VERSION) { /* Select version to use */ if (s->client_version <= DTLS1_2_VERSION && !(s->options & SSL_OP_NO_DTLSv1_2)) { s->version = DTLS1_2_VERSION; s->method = DTLSv1_2_server_method(); } else if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); s->version = s->client_version; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } else if (s->client_version <= DTLS1_VERSION && !(s->options & SSL_OP_NO_DTLSv1)) { s->version = DTLS1_VERSION; s->method = DTLSv1_server_method(); } else { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); s->version = s->client_version; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } s->session->ssl_version = s->version; } } if (p + 2 > d + n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p, i); if (i == 0) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED); goto f_err; } /* i bytes of cipher data + 1 byte for compression length later */ if ((p + i + 1) > (d + n)) { /* not enough data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers)) == NULL) { goto err; } p += i; /* If it is a hit, check that the cipher is in the list */ if (s->hit) { j = 0; id = s->session->cipher->id; #ifdef CIPHER_DEBUG fprintf(stderr, "client sent %d ciphers\n", sk_SSL_CIPHER_num(ciphers)); #endif for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) { c = sk_SSL_CIPHER_value(ciphers, i); #ifdef CIPHER_DEBUG fprintf(stderr, "client [%2d of %2d]:%s\n", i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c)); #endif if (c->id == id) { j = 1; break; } } /* * Disabled because it can be used in a ciphersuite downgrade attack: * CVE-2010-4180. */ #if 0 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1)) { /* * Special case as client bug workaround: the previously used * cipher may not be in the current list, the client instead * might be trying to continue using a cipher that before wasn't * chosen due to server preferences. We'll have to reject the * connection if the cipher is not enabled, though. */ c = sk_SSL_CIPHER_value(ciphers, 0); if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) { s->session->cipher = c; j = 1; } } #endif if (j == 0) { /* * we need to have the cipher in the cipher list if we are asked * to reuse it */ al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_REQUIRED_CIPHER_MISSING); goto f_err; } } /* compression */ i = *(p++); if ((p + i) > (d + n)) { /* not enough data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } #ifndef OPENSSL_NO_COMP q = p; #endif for (j = 0; j < i; j++) { if (p[j] == 0) break; } p += i; if (j >= i) { /* no compress */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* TLS extensions */ if (s->version >= SSL3_VERSION) { if (!ssl_parse_clienthello_tlsext(s, &p, d + n)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT); goto err; } } /* * Check if we want to use external pre-shared secret for this handshake * for not reused session only. We need to generate server_random before * calling tls_session_secret_cb in order to allow SessionTicket * processing to use it in key derivation. */ { unsigned char *pos; pos = s->s3->server_random; if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) { goto f_err; } } if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher = NULL; s->session->master_key_length = sizeof(s->session->master_key); if (s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, ciphers, &pref_cipher, s->tls_session_secret_cb_arg)) { s->hit = 1; s->session->ciphers = ciphers; s->session->verify_result = X509_V_OK; ciphers = NULL; /* check if some cipher was preferred by call back */ pref_cipher = pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s-> session->ciphers, SSL_get_ciphers (s)); if (pref_cipher == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER); goto f_err; } s->session->cipher = pref_cipher; if (s->cipher_list) sk_SSL_CIPHER_free(s->cipher_list); if (s->cipher_list_by_id) sk_SSL_CIPHER_free(s->cipher_list_by_id); s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers); s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers); } } #endif /* * Worst case, we will use the NULL compression, but if we have other * options, we will now look for them. We have i-1 compression * algorithms from the client, starting at q. */ s->s3->tmp.new_compression = NULL; #ifndef OPENSSL_NO_COMP /* This only happens if we have a cache hit */ if (s->session->compress_meth != 0) { int m, comp_id = s->session->compress_meth; /* Perform sanity checks on resumed compression algorithm */ /* Can't disable compression */ if (s->options & SSL_OP_NO_COMPRESSION) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } /* Look for resumed compression method */ for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, m); if (comp_id == comp->id) { s->s3->tmp.new_compression = comp; break; } } if (s->s3->tmp.new_compression == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INVALID_COMPRESSION_ALGORITHM); goto f_err; } /* Look for resumed method in compression list */ for (m = 0; m < i; m++) { if (q[m] == comp_id) break; } if (m >= i) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING); goto f_err; } } else if (s->hit) comp = NULL; else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods) { /* See if we have a match */ int m, nn, o, v, done = 0; nn = sk_SSL_COMP_num(s->ctx->comp_methods); for (m = 0; m < nn; m++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, m); v = comp->id; for (o = 0; o < i; o++) { if (v == q[o]) { done = 1; break; } } if (done) break; } if (done) s->s3->tmp.new_compression = comp; else comp = NULL; } #else /* * If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #endif /* * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher */ if (!s->hit) { #ifdef OPENSSL_NO_COMP s->session->compress_meth = 0; #else s->session->compress_meth = (comp == NULL) ? 0 : comp->id; #endif if (s->session->ciphers != NULL) sk_SSL_CIPHER_free(s->session->ciphers); s->session->ciphers = ciphers; if (ciphers == NULL) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto f_err; } ciphers = NULL; if (!tls1_set_server_sigalgs(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } /* Let cert callback update server certificates if required */ retry_cert: if (s->cert->cert_cb) { int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg); if (rv == 0) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR); goto f_err; } if (rv < 0) { s->rwstate = SSL_X509_LOOKUP; return -1; } s->rwstate = SSL_NOTHING; } c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s)); if (c == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER); goto f_err; } s->s3->tmp.new_cipher = c; } else { /* Session-id reuse */ #ifdef REUSE_CIPHER_BUG STACK_OF(SSL_CIPHER) *sk; SSL_CIPHER *nc = NULL; SSL_CIPHER *ec = NULL; if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) { sk = s->session->ciphers; for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) { c = sk_SSL_CIPHER_value(sk, i); if (c->algorithm_enc & SSL_eNULL) nc = c; if (SSL_C_IS_EXPORT(c)) ec = c; } if (nc != NULL) s->s3->tmp.new_cipher = nc; else if (ec != NULL) s->s3->tmp.new_cipher = ec; else s->s3->tmp.new_cipher = s->session->cipher; } else #endif s->s3->tmp.new_cipher = s->session->cipher; } if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) { if (!ssl3_digest_cached_records(s)) goto f_err; } /*- * we now have the following setup. * client_random * cipher_list - our prefered list of ciphers * ciphers - the clients prefered list of ciphers * compression - basically ignored right now * ssl version is set - sslv3 * s->session - The ssl session has been setup. * s->hit - session reuse flag * s->tmp.new_cipher - the new cipher to use. */ /* Handles TLS extensions that we couldn't check earlier */ if (s->version >= SSL3_VERSION) { if (ssl_check_clienthello_tlsext_late(s) <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } } ret = cookie_valid ? 2 : 1; if (0) { f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: s->state = SSL_ST_ERR; } if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers); return ret; } Commit Message: CWE ID: CWE-190
int ssl3_get_client_hello(SSL *s) { int i, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1, cookie_valid = 0; unsigned int cookie_len; long n; unsigned long id; unsigned char *p, *d; SSL_CIPHER *c; #ifndef OPENSSL_NO_COMP unsigned char *q; SSL_COMP *comp = NULL; #endif STACK_OF(SSL_CIPHER) *ciphers = NULL; if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet) goto retry_cert; /* * We do this so that we will respond with our native type. If we are * TLSv1 and we get SSLv3, we will respond with TLSv1, This down * switching should be handled by a different method. If we are SSLv3, we * will respond with SSLv3, even if prompted with TLSv1. */ if (s->state == SSL3_ST_SR_CLNT_HELLO_A) { s->state = SSL3_ST_SR_CLNT_HELLO_B; } s->first_packet = 1; n = s->method->ssl_get_message(s, SSL3_ST_SR_CLNT_HELLO_B, SSL3_ST_SR_CLNT_HELLO_C, SSL3_MT_CLIENT_HELLO, SSL3_RT_MAX_PLAIN_LENGTH, &ok); if (!ok) return ((int)n); s->first_packet = 0; d = p = (unsigned char *)s->init_msg; /* * 2 bytes for client version, SSL3_RANDOM_SIZE bytes for random, 1 byte * for session id length */ if (n < 2 + SSL3_RANDOM_SIZE + 1) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* * use version from inside client hello, not from record header (may * differ: see RFC 2246, Appendix E, second paragraph) */ s->client_version = (((int)p[0]) << 8) | (int)p[1]; p += 2; if (SSL_IS_DTLS(s) ? (s->client_version > s->version && s->method->version != DTLS_ANY_VERSION) : (s->client_version < s->version)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); if ((s->client_version >> 8) == SSL3_VERSION_MAJOR && !s->enc_write_ctx && !s->write_hash) { /* * similar to ssl3_get_record, send alert using remote version * number */ s->version = s->client_version; } al = SSL_AD_PROTOCOL_VERSION; goto f_err; } /* * If we require cookies and this ClientHello doesn't contain one, just * return since we do not want to allocate any memory yet. So check * cookie length... */ if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) { unsigned int session_length, cookie_length; session_length = *(p + SSL3_RANDOM_SIZE); if (SSL3_RANDOM_SIZE + session_length + 1 >= (d + n) - p) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1); if (cookie_length == 0) return 1; } /* load the client random */ memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE); p += SSL3_RANDOM_SIZE; /* get the session-id */ j = *(p++); if ((d + n) - p < j) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } if ((j < 0) || (j > SSL_MAX_SSL_SESSION_ID_LENGTH)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } s->hit = 0; /* * Versions before 0.9.7 always allow clients to resume sessions in * renegotiation. 0.9.7 and later allow this by default, but optionally * ignore resumption requests with flag * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather * than a change to default behavior so that applications relying on this * for security won't even compile against older library versions). * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to * request renegotiation but not a new session (s->new_session remains * unset): for servers, this essentially just means that the * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be ignored. */ if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) { if (!ssl_get_new_session(s, 1)) goto err; } else { i = ssl_get_prev_session(s, p, j, d + n); /* * Only resume if the session's version matches the negotiated * version. * RFC 5246 does not provide much useful advice on resumption * with a different protocol version. It doesn't forbid it but * the sanity of such behaviour would be questionable. * In practice, clients do not accept a version mismatch and * will abort the handshake with an error. */ if (i == 1 && s->version == s->session->ssl_version) { /* previous * session */ s->hit = 1; } else if (i == -1) goto err; else { /* i == 0 */ if (!ssl_get_new_session(s, 1)) goto err; } } p += j; if (SSL_IS_DTLS(s)) { /* cookie stuff */ if ((d + n) - p < 1) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } cookie_len = *(p++); if ((d + n ) - p < cookie_len) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* * The ClientHello may contain a cookie even if the * HelloVerify message has not been sent--make sure that it * does not cause an overflow. */ if (cookie_len > sizeof(s->d1->rcvd_cookie)) { /* too much data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* verify the cookie if appropriate option is set. */ if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) { memcpy(s->d1->rcvd_cookie, p, cookie_len); if (s->ctx->app_verify_cookie_cb != NULL) { if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie, cookie_len) == 0) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* else cookie verification succeeded */ } /* default verification */ else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie, s->d1->cookie_len) != 0) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } cookie_valid = 1; } p += cookie_len; if (s->method->version == DTLS_ANY_VERSION) { /* Select version to use */ if (s->client_version <= DTLS1_2_VERSION && !(s->options & SSL_OP_NO_DTLSv1_2)) { s->version = DTLS1_2_VERSION; s->method = DTLSv1_2_server_method(); } else if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); s->version = s->client_version; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } else if (s->client_version <= DTLS1_VERSION && !(s->options & SSL_OP_NO_DTLSv1)) { s->version = DTLS1_VERSION; s->method = DTLSv1_server_method(); } else { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); s->version = s->client_version; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } s->session->ssl_version = s->version; } } if ((d + n ) - p < 2) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p, i); if (i == 0) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED); goto f_err; } /* i bytes of cipher data + 1 byte for compression length later */ if ((d + n) - p < i + 1) { /* not enough data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers)) == NULL) { goto err; } p += i; /* If it is a hit, check that the cipher is in the list */ if (s->hit) { j = 0; id = s->session->cipher->id; #ifdef CIPHER_DEBUG fprintf(stderr, "client sent %d ciphers\n", sk_SSL_CIPHER_num(ciphers)); #endif for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) { c = sk_SSL_CIPHER_value(ciphers, i); #ifdef CIPHER_DEBUG fprintf(stderr, "client [%2d of %2d]:%s\n", i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c)); #endif if (c->id == id) { j = 1; break; } } /* * Disabled because it can be used in a ciphersuite downgrade attack: * CVE-2010-4180. */ #if 0 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1)) { /* * Special case as client bug workaround: the previously used * cipher may not be in the current list, the client instead * might be trying to continue using a cipher that before wasn't * chosen due to server preferences. We'll have to reject the * connection if the cipher is not enabled, though. */ c = sk_SSL_CIPHER_value(ciphers, 0); if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) { s->session->cipher = c; j = 1; } } #endif if (j == 0) { /* * we need to have the cipher in the cipher list if we are asked * to reuse it */ al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_REQUIRED_CIPHER_MISSING); goto f_err; } } /* compression */ i = *(p++); if ((d + n) - p < i) { /* not enough data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } #ifndef OPENSSL_NO_COMP q = p; #endif for (j = 0; j < i; j++) { if (p[j] == 0) break; } p += i; if (j >= i) { /* no compress */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* TLS extensions */ if (s->version >= SSL3_VERSION) { if (!ssl_parse_clienthello_tlsext(s, &p, d + n)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT); goto err; } } /* * Check if we want to use external pre-shared secret for this handshake * for not reused session only. We need to generate server_random before * calling tls_session_secret_cb in order to allow SessionTicket * processing to use it in key derivation. */ { unsigned char *pos; pos = s->s3->server_random; if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) { goto f_err; } } if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher = NULL; s->session->master_key_length = sizeof(s->session->master_key); if (s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, ciphers, &pref_cipher, s->tls_session_secret_cb_arg)) { s->hit = 1; s->session->ciphers = ciphers; s->session->verify_result = X509_V_OK; ciphers = NULL; /* check if some cipher was preferred by call back */ pref_cipher = pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s-> session->ciphers, SSL_get_ciphers (s)); if (pref_cipher == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER); goto f_err; } s->session->cipher = pref_cipher; if (s->cipher_list) sk_SSL_CIPHER_free(s->cipher_list); if (s->cipher_list_by_id) sk_SSL_CIPHER_free(s->cipher_list_by_id); s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers); s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers); } } #endif /* * Worst case, we will use the NULL compression, but if we have other * options, we will now look for them. We have i-1 compression * algorithms from the client, starting at q. */ s->s3->tmp.new_compression = NULL; #ifndef OPENSSL_NO_COMP /* This only happens if we have a cache hit */ if (s->session->compress_meth != 0) { int m, comp_id = s->session->compress_meth; /* Perform sanity checks on resumed compression algorithm */ /* Can't disable compression */ if (s->options & SSL_OP_NO_COMPRESSION) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } /* Look for resumed compression method */ for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, m); if (comp_id == comp->id) { s->s3->tmp.new_compression = comp; break; } } if (s->s3->tmp.new_compression == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INVALID_COMPRESSION_ALGORITHM); goto f_err; } /* Look for resumed method in compression list */ for (m = 0; m < i; m++) { if (q[m] == comp_id) break; } if (m >= i) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING); goto f_err; } } else if (s->hit) comp = NULL; else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods) { /* See if we have a match */ int m, nn, o, v, done = 0; nn = sk_SSL_COMP_num(s->ctx->comp_methods); for (m = 0; m < nn; m++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, m); v = comp->id; for (o = 0; o < i; o++) { if (v == q[o]) { done = 1; break; } } if (done) break; } if (done) s->s3->tmp.new_compression = comp; else comp = NULL; } #else /* * If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #endif /* * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher */ if (!s->hit) { #ifdef OPENSSL_NO_COMP s->session->compress_meth = 0; #else s->session->compress_meth = (comp == NULL) ? 0 : comp->id; #endif if (s->session->ciphers != NULL) sk_SSL_CIPHER_free(s->session->ciphers); s->session->ciphers = ciphers; if (ciphers == NULL) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto f_err; } ciphers = NULL; if (!tls1_set_server_sigalgs(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } /* Let cert callback update server certificates if required */ retry_cert: if (s->cert->cert_cb) { int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg); if (rv == 0) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR); goto f_err; } if (rv < 0) { s->rwstate = SSL_X509_LOOKUP; return -1; } s->rwstate = SSL_NOTHING; } c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s)); if (c == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER); goto f_err; } s->s3->tmp.new_cipher = c; } else { /* Session-id reuse */ #ifdef REUSE_CIPHER_BUG STACK_OF(SSL_CIPHER) *sk; SSL_CIPHER *nc = NULL; SSL_CIPHER *ec = NULL; if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) { sk = s->session->ciphers; for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) { c = sk_SSL_CIPHER_value(sk, i); if (c->algorithm_enc & SSL_eNULL) nc = c; if (SSL_C_IS_EXPORT(c)) ec = c; } if (nc != NULL) s->s3->tmp.new_cipher = nc; else if (ec != NULL) s->s3->tmp.new_cipher = ec; else s->s3->tmp.new_cipher = s->session->cipher; } else #endif s->s3->tmp.new_cipher = s->session->cipher; } if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) { if (!ssl3_digest_cached_records(s)) goto f_err; } /*- * we now have the following setup. * client_random * cipher_list - our prefered list of ciphers * ciphers - the clients prefered list of ciphers * compression - basically ignored right now * ssl version is set - sslv3 * s->session - The ssl session has been setup. * s->hit - session reuse flag * s->tmp.new_cipher - the new cipher to use. */ /* Handles TLS extensions that we couldn't check earlier */ if (s->version >= SSL3_VERSION) { if (ssl_check_clienthello_tlsext_late(s) <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } } ret = cookie_valid ? 2 : 1; if (0) { f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: s->state = SSL_ST_ERR; } if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers); return ret; }
165,200
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void balloon_process(struct work_struct *work) { enum bp_state state = BP_DONE; long credit; do { mutex_lock(&balloon_mutex); credit = current_credit(); if (credit > 0) { if (balloon_is_inflated()) state = increase_reservation(credit); else state = reserve_additional_memory(); } if (credit < 0) state = decrease_reservation(-credit, GFP_BALLOON); state = update_schedule(state); mutex_unlock(&balloon_mutex); cond_resched(); } while (credit && state == BP_DONE); /* Schedule more work if there is some still to be done. */ if (state == BP_EAGAIN) schedule_delayed_work(&balloon_worker, balloon_stats.schedule_delay * HZ); } Commit Message: xen: let alloc_xenballooned_pages() fail if not enough memory free commit a1078e821b605813b63bf6bca414a85f804d5c66 upstream. Instead of trying to allocate pages with GFP_USER in add_ballooned_pages() check the available free memory via si_mem_available(). GFP_USER is far less limiting memory exhaustion than the test via si_mem_available(). This will avoid dom0 running out of memory due to excessive foreign page mappings especially on ARM and on x86 in PVH mode, as those don't have a pre-ballooned area which can be used for foreign mappings. As the normal ballooning suffers from the same problem don't balloon down more than si_mem_available() pages in one iteration. At the same time limit the default maximum number of retries. This is part of XSA-300. Signed-off-by: Juergen Gross <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-400
static void balloon_process(struct work_struct *work) { enum bp_state state = BP_DONE; long credit; do { mutex_lock(&balloon_mutex); credit = current_credit(); if (credit > 0) { if (balloon_is_inflated()) state = increase_reservation(credit); else state = reserve_additional_memory(); } if (credit < 0) { long n_pages; n_pages = min(-credit, si_mem_available()); state = decrease_reservation(n_pages, GFP_BALLOON); if (state == BP_DONE && n_pages != -credit && n_pages < totalreserve_pages) state = BP_EAGAIN; } state = update_schedule(state); mutex_unlock(&balloon_mutex); cond_resched(); } while (credit && state == BP_DONE); /* Schedule more work if there is some still to be done. */ if (state == BP_EAGAIN) schedule_delayed_work(&balloon_worker, balloon_stats.schedule_delay * HZ); }
169,494
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ieee80211_sta_ps_deliver_wakeup(struct sta_info *sta) { struct ieee80211_sub_if_data *sdata = sta->sdata; struct ieee80211_local *local = sdata->local; struct sk_buff_head pending; int filtered = 0, buffered = 0, ac; unsigned long flags; clear_sta_flag(sta, WLAN_STA_SP); BUILD_BUG_ON(BITS_TO_LONGS(IEEE80211_NUM_TIDS) > 1); sta->driver_buffered_tids = 0; if (!(local->hw.flags & IEEE80211_HW_AP_LINK_PS)) drv_sta_notify(local, sdata, STA_NOTIFY_AWAKE, &sta->sta); skb_queue_head_init(&pending); /* Send all buffered frames to the station */ for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) { int count = skb_queue_len(&pending), tmp; spin_lock_irqsave(&sta->tx_filtered[ac].lock, flags); skb_queue_splice_tail_init(&sta->tx_filtered[ac], &pending); spin_unlock_irqrestore(&sta->tx_filtered[ac].lock, flags); tmp = skb_queue_len(&pending); filtered += tmp - count; count = tmp; spin_lock_irqsave(&sta->ps_tx_buf[ac].lock, flags); skb_queue_splice_tail_init(&sta->ps_tx_buf[ac], &pending); spin_unlock_irqrestore(&sta->ps_tx_buf[ac].lock, flags); tmp = skb_queue_len(&pending); buffered += tmp - count; } ieee80211_add_pending_skbs_fn(local, &pending, clear_sta_ps_flags, sta); /* This station just woke up and isn't aware of our SMPS state */ if (!ieee80211_smps_is_restrictive(sta->known_smps_mode, sdata->smps_mode) && sta->known_smps_mode != sdata->bss->req_smps && sta_info_tx_streams(sta) != 1) { ht_dbg(sdata, "%pM just woke up and MIMO capable - update SMPS\n", sta->sta.addr); ieee80211_send_smps_action(sdata, sdata->bss->req_smps, sta->sta.addr, sdata->vif.bss_conf.bssid); } local->total_ps_buffered -= buffered; sta_info_recalc_tim(sta); ps_dbg(sdata, "STA %pM aid %d sending %d filtered/%d PS frames since STA not sleeping anymore\n", sta->sta.addr, sta->sta.aid, filtered, buffered); } Commit Message: mac80211: fix AP powersave TX vs. wakeup race There is a race between the TX path and the STA wakeup: while a station is sleeping, mac80211 buffers frames until it wakes up, then the frames are transmitted. However, the RX and TX path are concurrent, so the packet indicating wakeup can be processed while a packet is being transmitted. This can lead to a situation where the buffered frames list is emptied on the one side, while a frame is being added on the other side, as the station is still seen as sleeping in the TX path. As a result, the newly added frame will not be send anytime soon. It might be sent much later (and out of order) when the station goes to sleep and wakes up the next time. Additionally, it can lead to the crash below. Fix all this by synchronising both paths with a new lock. Both path are not fastpath since they handle PS situations. In a later patch we'll remove the extra skb queue locks to reduce locking overhead. BUG: unable to handle kernel NULL pointer dereference at 000000b0 IP: [<ff6f1791>] ieee80211_report_used_skb+0x11/0x3e0 [mac80211] *pde = 00000000 Oops: 0000 [#1] SMP DEBUG_PAGEALLOC EIP: 0060:[<ff6f1791>] EFLAGS: 00210282 CPU: 1 EIP is at ieee80211_report_used_skb+0x11/0x3e0 [mac80211] EAX: e5900da0 EBX: 00000000 ECX: 00000001 EDX: 00000000 ESI: e41d00c0 EDI: e5900da0 EBP: ebe458e4 ESP: ebe458b0 DS: 007b ES: 007b FS: 00d8 GS: 00e0 SS: 0068 CR0: 8005003b CR2: 000000b0 CR3: 25a78000 CR4: 000407d0 DR0: 00000000 DR1: 00000000 DR2: 00000000 DR3: 00000000 DR6: ffff0ff0 DR7: 00000400 Process iperf (pid: 3934, ti=ebe44000 task=e757c0b0 task.ti=ebe44000) iwlwifi 0000:02:00.0: I iwl_pcie_enqueue_hcmd Sending command LQ_CMD (#4e), seq: 0x0903, 92 bytes at 3[3]:9 Stack: e403b32c ebe458c4 00200002 00200286 e403b338 ebe458cc c10960bb e5900da0 ff76a6ec ebe458d8 00000000 e41d00c0 e5900da0 ebe458f0 ff6f1b75 e403b210 ebe4598c ff723dc1 00000000 ff76a6ec e597c978 e403b758 00000002 00000002 Call Trace: [<ff6f1b75>] ieee80211_free_txskb+0x15/0x20 [mac80211] [<ff723dc1>] invoke_tx_handlers+0x1661/0x1780 [mac80211] [<ff7248a5>] ieee80211_tx+0x75/0x100 [mac80211] [<ff7249bf>] ieee80211_xmit+0x8f/0xc0 [mac80211] [<ff72550e>] ieee80211_subif_start_xmit+0x4fe/0xe20 [mac80211] [<c149ef70>] dev_hard_start_xmit+0x450/0x950 [<c14b9aa9>] sch_direct_xmit+0xa9/0x250 [<c14b9c9b>] __qdisc_run+0x4b/0x150 [<c149f732>] dev_queue_xmit+0x2c2/0xca0 Cc: [email protected] Reported-by: Yaara Rozenblum <[email protected]> Signed-off-by: Emmanuel Grumbach <[email protected]> Reviewed-by: Stanislaw Gruszka <[email protected]> [reword commit log, use a separate lock] Signed-off-by: Johannes Berg <[email protected]> CWE ID: CWE-362
void ieee80211_sta_ps_deliver_wakeup(struct sta_info *sta) { struct ieee80211_sub_if_data *sdata = sta->sdata; struct ieee80211_local *local = sdata->local; struct sk_buff_head pending; int filtered = 0, buffered = 0, ac; unsigned long flags; clear_sta_flag(sta, WLAN_STA_SP); BUILD_BUG_ON(BITS_TO_LONGS(IEEE80211_NUM_TIDS) > 1); sta->driver_buffered_tids = 0; if (!(local->hw.flags & IEEE80211_HW_AP_LINK_PS)) drv_sta_notify(local, sdata, STA_NOTIFY_AWAKE, &sta->sta); skb_queue_head_init(&pending); /* sync with ieee80211_tx_h_unicast_ps_buf */ spin_lock(&sta->ps_lock); /* Send all buffered frames to the station */ for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) { int count = skb_queue_len(&pending), tmp; spin_lock_irqsave(&sta->tx_filtered[ac].lock, flags); skb_queue_splice_tail_init(&sta->tx_filtered[ac], &pending); spin_unlock_irqrestore(&sta->tx_filtered[ac].lock, flags); tmp = skb_queue_len(&pending); filtered += tmp - count; count = tmp; spin_lock_irqsave(&sta->ps_tx_buf[ac].lock, flags); skb_queue_splice_tail_init(&sta->ps_tx_buf[ac], &pending); spin_unlock_irqrestore(&sta->ps_tx_buf[ac].lock, flags); tmp = skb_queue_len(&pending); buffered += tmp - count; } ieee80211_add_pending_skbs_fn(local, &pending, clear_sta_ps_flags, sta); spin_unlock(&sta->ps_lock); /* This station just woke up and isn't aware of our SMPS state */ if (!ieee80211_smps_is_restrictive(sta->known_smps_mode, sdata->smps_mode) && sta->known_smps_mode != sdata->bss->req_smps && sta_info_tx_streams(sta) != 1) { ht_dbg(sdata, "%pM just woke up and MIMO capable - update SMPS\n", sta->sta.addr); ieee80211_send_smps_action(sdata, sdata->bss->req_smps, sta->sta.addr, sdata->vif.bss_conf.bssid); } local->total_ps_buffered -= buffered; sta_info_recalc_tim(sta); ps_dbg(sdata, "STA %pM aid %d sending %d filtered/%d PS frames since STA not sleeping anymore\n", sta->sta.addr, sta->sta.aid, filtered, buffered); }
166,391
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: make_size(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type, int bdlo, int PNG_CONST bdhi) { for (; bdlo <= bdhi; ++bdlo) { png_uint_32 width; for (width = 1; width <= 16; ++width) { png_uint_32 height; for (height = 1; height <= 16; ++height) { /* The four combinations of DIY interlace and interlace or not - * no interlace + DIY should be identical to no interlace with * libpng doing it. */ make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE, width, height, 0); make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE, width, height, 1); # ifdef PNG_WRITE_INTERLACING_SUPPORTED make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7, width, height, 0); make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7, width, height, 1); # endif } } } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
make_size(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type, int bdlo, make_size(png_store* const ps, png_byte const colour_type, int bdlo, int const bdhi) { for (; bdlo <= bdhi; ++bdlo) { png_uint_32 width; for (width = 1; width <= 16; ++width) { png_uint_32 height; for (height = 1; height <= 16; ++height) { /* The four combinations of DIY interlace and interlace or not - * no interlace + DIY should be identical to no interlace with * libpng doing it. */ make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE, width, height, 0); make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE, width, height, 1); # ifdef PNG_WRITE_INTERLACING_SUPPORTED make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7, width, height, 0); # endif # if CAN_WRITE_INTERLACE /* 1.7.0 removes the hack that prevented app write of an interlaced * image if WRITE_INTERLACE was not supported */ make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7, width, height, 1); # endif } } } }
173,663
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ndp_sock_open(struct ndp *ndp) { int sock; int ret; int err; int val; sock = socket(PF_INET6, SOCK_RAW, IPPROTO_ICMPV6); if (sock == -1) { err(ndp, "Failed to create ICMP6 socket."); return -errno; } val = 1; ret = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &val, sizeof(val)); if (ret == -1) { err(ndp, "Failed to setsockopt IPV6_RECVPKTINFO."); err = -errno; goto close_sock; } val = 255; ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &val, sizeof(val)); if (ret == -1) { err(ndp, "Failed to setsockopt IPV6_MULTICAST_HOPS."); err = -errno; goto close_sock; } ndp->sock = sock; return 0; close_sock: close(sock); return err; } Commit Message: libndp: validate the IPv6 hop limit None of the NDP messages should ever come from a non-local network; as stated in RFC4861's 6.1.1 (RS), 6.1.2 (RA), 7.1.1 (NS), 7.1.2 (NA), and 8.1. (redirect): - The IP Hop Limit field has a value of 255, i.e., the packet could not possibly have been forwarded by a router. This fixes CVE-2016-3698. Reported by: Julien BERNARD <[email protected]> Signed-off-by: Lubomir Rintel <[email protected]> Signed-off-by: Jiri Pirko <[email protected]> CWE ID: CWE-284
static int ndp_sock_open(struct ndp *ndp) { int sock; int ret; int err; int val; sock = socket(PF_INET6, SOCK_RAW, IPPROTO_ICMPV6); if (sock == -1) { err(ndp, "Failed to create ICMP6 socket."); return -errno; } val = 1; ret = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &val, sizeof(val)); if (ret == -1) { err(ndp, "Failed to setsockopt IPV6_RECVPKTINFO."); err = -errno; goto close_sock; } val = 255; ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &val, sizeof(val)); if (ret == -1) { err(ndp, "Failed to setsockopt IPV6_MULTICAST_HOPS."); err = -errno; goto close_sock; } val = 1; ret = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &val, sizeof(val)); if (ret == -1) { err(ndp, "Failed to setsockopt IPV6_RECVHOPLIMIT,."); err = -errno; goto close_sock; } ndp->sock = sock; return 0; close_sock: close(sock); return err; }
167,349
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char **argv) { int i, n_valid, do_write, do_scrub; char *c, *dname, *name; DIR *dir; FILE *fp; pdf_t *pdf; pdf_flag_t flags; if (argc < 2) usage(); /* Args */ do_write = do_scrub = flags = 0; name = NULL; for (i=1; i<argc; i++) { if (strncmp(argv[i], "-w", 2) == 0) do_write = 1; else if (strncmp(argv[i], "-i", 2) == 0) flags |= PDF_FLAG_DISP_CREATOR; else if (strncmp(argv[i], "-q", 2) == 0) flags |= PDF_FLAG_QUIET; else if (strncmp(argv[i], "-s", 2) == 0) do_scrub = 1; else if (argv[i][0] != '-') name = argv[i]; else if (argv[i][0] == '-') usage(); } if (!name) usage(); if (!(fp = fopen(name, "r"))) { ERR("Could not open file '%s'\n", argv[1]); return -1; } else if (!pdf_is_pdf(fp)) { ERR("'%s' specified is not a valid PDF\n", name); fclose(fp); return -1; } /* Load PDF */ if (!(pdf = init_pdf(fp, name))) { fclose(fp); return -1; } /* Count valid xrefs */ for (i=0, n_valid=0; i<pdf->n_xrefs; i++) if (pdf->xrefs[i].version) ++n_valid; /* Bail if we only have 1 valid */ if (n_valid < 2) { if (!(flags & (PDF_FLAG_QUIET | PDF_FLAG_DISP_CREATOR))) printf("%s: There is only one version of this PDF\n", pdf->name); if (do_write) { fclose(fp); pdf_delete(pdf); return 0; } } dname = NULL; if (do_write) { /* Create directory to place the various versions in */ if ((c = strrchr(name, '/'))) name = c + 1; if ((c = strrchr(name, '.'))) *c = '\0'; dname = malloc(strlen(name) + 16); sprintf(dname, "%s-versions", name); if (!(dir = opendir(dname))) mkdir(dname, S_IRWXU); else { ERR("This directory already exists, PDF version extraction will " "not occur.\n"); fclose(fp); closedir(dir); free(dname); pdf_delete(pdf); return -1; } /* Write the pdf as a pervious version */ for (i=0; i<pdf->n_xrefs; i++) if (pdf->xrefs[i].version) write_version(fp, name, dname, &pdf->xrefs[i]); } /* Generate a per-object summary */ pdf_summarize(fp, pdf, dname, flags); /* Have we been summoned to scrub history from this PDF */ if (do_scrub) scrub_document(fp, pdf); /* Display extra information */ if (flags & PDF_FLAG_DISP_CREATOR) display_creator(fp, pdf); fclose(fp); free(dname); pdf_delete(pdf); return 0; } Commit Message: Zero and sanity check all dynamic allocs. This addresses the memory issues in Issue #6 expressed in calloc_some.pdf and malloc_some.pdf CWE ID: CWE-787
int main(int argc, char **argv) { int i, n_valid, do_write, do_scrub; char *c, *dname, *name; DIR *dir; FILE *fp; pdf_t *pdf; pdf_flag_t flags; if (argc < 2) usage(); /* Args */ do_write = do_scrub = flags = 0; name = NULL; for (i=1; i<argc; i++) { if (strncmp(argv[i], "-w", 2) == 0) do_write = 1; else if (strncmp(argv[i], "-i", 2) == 0) flags |= PDF_FLAG_DISP_CREATOR; else if (strncmp(argv[i], "-q", 2) == 0) flags |= PDF_FLAG_QUIET; else if (strncmp(argv[i], "-s", 2) == 0) do_scrub = 1; else if (argv[i][0] != '-') name = argv[i]; else if (argv[i][0] == '-') usage(); } if (!name) usage(); if (!(fp = fopen(name, "r"))) { ERR("Could not open file '%s'\n", argv[1]); return -1; } else if (!pdf_is_pdf(fp)) { ERR("'%s' specified is not a valid PDF\n", name); fclose(fp); return -1; } /* Load PDF */ if (!(pdf = init_pdf(fp, name))) { fclose(fp); return -1; } /* Count valid xrefs */ for (i=0, n_valid=0; i<pdf->n_xrefs; i++) if (pdf->xrefs[i].version) ++n_valid; /* Bail if we only have 1 valid */ if (n_valid < 2) { if (!(flags & (PDF_FLAG_QUIET | PDF_FLAG_DISP_CREATOR))) printf("%s: There is only one version of this PDF\n", pdf->name); if (do_write) { fclose(fp); pdf_delete(pdf); return 0; } } dname = NULL; if (do_write) { /* Create directory to place the various versions in */ if ((c = strrchr(name, '/'))) name = c + 1; if ((c = strrchr(name, '.'))) *c = '\0'; dname = safe_calloc(strlen(name) + 16); sprintf(dname, "%s-versions", name); if (!(dir = opendir(dname))) mkdir(dname, S_IRWXU); else { ERR("This directory already exists, PDF version extraction will " "not occur.\n"); fclose(fp); closedir(dir); free(dname); pdf_delete(pdf); return -1; } /* Write the pdf as a pervious version */ for (i=0; i<pdf->n_xrefs; i++) if (pdf->xrefs[i].version) write_version(fp, name, dname, &pdf->xrefs[i]); } /* Generate a per-object summary */ pdf_summarize(fp, pdf, dname, flags); /* Have we been summoned to scrub history from this PDF */ if (do_scrub) scrub_document(fp, pdf); /* Display extra information */ if (flags & PDF_FLAG_DISP_CREATOR) display_creator(fp, pdf); fclose(fp); free(dname); pdf_delete(pdf); return 0; }
169,564
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p) { memcpy(&p->id, &x->id, sizeof(p->id)); memcpy(&p->sel, &x->sel, sizeof(p->sel)); memcpy(&p->lft, &x->lft, sizeof(p->lft)); memcpy(&p->curlft, &x->curlft, sizeof(p->curlft)); memcpy(&p->stats, &x->stats, sizeof(p->stats)); memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr)); p->mode = x->props.mode; p->replay_window = x->props.replay_window; p->reqid = x->props.reqid; p->family = x->props.family; p->flags = x->props.flags; p->seq = x->km.seq; } Commit Message: xfrm_user: fix info leak in copy_to_user_state() The memory reserved to dump the xfrm state includes the padding bytes of struct xfrm_usersa_info added by the compiler for alignment (7 for amd64, 3 for i386). Add an explicit memset(0) before filling the buffer to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Acked-by: Steffen Klassert <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p) { memset(p, 0, sizeof(*p)); memcpy(&p->id, &x->id, sizeof(p->id)); memcpy(&p->sel, &x->sel, sizeof(p->sel)); memcpy(&p->lft, &x->lft, sizeof(p->lft)); memcpy(&p->curlft, &x->curlft, sizeof(p->curlft)); memcpy(&p->stats, &x->stats, sizeof(p->stats)); memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr)); p->mode = x->props.mode; p->replay_window = x->props.replay_window; p->reqid = x->props.reqid; p->family = x->props.family; p->flags = x->props.flags; p->seq = x->km.seq; }
166,189
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: horAcc16(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint16* wp = (uint16*) cp0; tmsize_t wc = cc / 2; assert((cc%(2*stride))==0); if (wc > stride) { wc -= stride; do { REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] + (unsigned int)wp[0]) & 0xffff); wp++) wc -= stride; } while (wc > 0); } } Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-119
horAcc16(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint16* wp = (uint16*) cp0; tmsize_t wc = cc / 2; if((cc%(2*stride))!=0) { TIFFErrorExt(tif->tif_clientdata, "horAcc16", "%s", "cc%(2*stride))!=0"); return 0; } if (wc > stride) { wc -= stride; do { REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] + (unsigned int)wp[0]) & 0xffff); wp++) wc -= stride; } while (wc > 0); } return 1; }
166,882
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) { ALOGV("entering parseChunk %lld/%d", *offset, depth); uint32_t hdr[2]; if (mDataSource->readAt(*offset, hdr, 8) < 8) { return ERROR_IO; } uint64_t chunk_size = ntohl(hdr[0]); uint32_t chunk_type = ntohl(hdr[1]); off64_t data_offset = *offset + 8; if (chunk_size == 1) { if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) { return ERROR_IO; } chunk_size = ntoh64(chunk_size); data_offset += 8; if (chunk_size < 16) { return ERROR_MALFORMED; } } else if (chunk_size == 0) { if (depth == 0) { off64_t sourceSize; if (mDataSource->getSize(&sourceSize) == OK) { chunk_size = (sourceSize - *offset); } else { ALOGE("atom size is 0, and data source has no size"); return ERROR_MALFORMED; } } else { *offset += 4; return OK; } } else if (chunk_size < 8) { ALOGE("invalid chunk size: %" PRIu64, chunk_size); return ERROR_MALFORMED; } char chunk[5]; MakeFourCCString(chunk_type, chunk); ALOGV("chunk: %s @ %lld, %d", chunk, *offset, depth); #if 0 static const char kWhitespace[] = " "; const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth]; printf("%sfound chunk '%s' of size %" PRIu64 "\n", indent, chunk, chunk_size); char buffer[256]; size_t n = chunk_size; if (n > sizeof(buffer)) { n = sizeof(buffer); } if (mDataSource->readAt(*offset, buffer, n) < (ssize_t)n) { return ERROR_IO; } hexdump(buffer, n); #endif PathAdder autoAdder(&mPath, chunk_type); off64_t chunk_data_size = *offset + chunk_size - data_offset; if (chunk_type != FOURCC('c', 'p', 'r', 't') && chunk_type != FOURCC('c', 'o', 'v', 'r') && mPath.size() == 5 && underMetaDataPath(mPath)) { off64_t stop_offset = *offset + chunk_size; *offset = data_offset; while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } return OK; } switch(chunk_type) { case FOURCC('m', 'o', 'o', 'v'): case FOURCC('t', 'r', 'a', 'k'): case FOURCC('m', 'd', 'i', 'a'): case FOURCC('m', 'i', 'n', 'f'): case FOURCC('d', 'i', 'n', 'f'): case FOURCC('s', 't', 'b', 'l'): case FOURCC('m', 'v', 'e', 'x'): case FOURCC('m', 'o', 'o', 'f'): case FOURCC('t', 'r', 'a', 'f'): case FOURCC('m', 'f', 'r', 'a'): case FOURCC('u', 'd', 't', 'a'): case FOURCC('i', 'l', 's', 't'): case FOURCC('s', 'i', 'n', 'f'): case FOURCC('s', 'c', 'h', 'i'): case FOURCC('e', 'd', 't', 's'): { if (chunk_type == FOURCC('s', 't', 'b', 'l')) { ALOGV("sampleTable chunk is %" PRIu64 " bytes long.", chunk_size); if (mDataSource->flags() & (DataSource::kWantsPrefetching | DataSource::kIsCachingDataSource)) { sp<MPEG4DataSource> cachedSource = new MPEG4DataSource(mDataSource); if (cachedSource->setCachedRange(*offset, chunk_size) == OK) { mDataSource = cachedSource; } } mLastTrack->sampleTable = new SampleTable(mDataSource); } bool isTrack = false; if (chunk_type == FOURCC('t', 'r', 'a', 'k')) { isTrack = true; Track *track = new Track; track->next = NULL; if (mLastTrack) { mLastTrack->next = track; } else { mFirstTrack = track; } mLastTrack = track; track->meta = new MetaData; track->includes_expensive_metadata = false; track->skipTrack = false; track->timescale = 0; track->meta->setCString(kKeyMIMEType, "application/octet-stream"); } off64_t stop_offset = *offset + chunk_size; *offset = data_offset; while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } if (isTrack) { if (mLastTrack->skipTrack) { Track *cur = mFirstTrack; if (cur == mLastTrack) { delete cur; mFirstTrack = mLastTrack = NULL; } else { while (cur && cur->next != mLastTrack) { cur = cur->next; } cur->next = NULL; delete mLastTrack; mLastTrack = cur; } return OK; } status_t err = verifyTrack(mLastTrack); if (err != OK) { return err; } } else if (chunk_type == FOURCC('m', 'o', 'o', 'v')) { mInitCheck = OK; if (!mIsDrm) { return UNKNOWN_ERROR; // Return a dummy error. } else { return OK; } } break; } case FOURCC('e', 'l', 's', 't'): { *offset += chunk_size; uint8_t version; if (mDataSource->readAt(data_offset, &version, 1) < 1) { return ERROR_IO; } uint32_t entry_count; if (!mDataSource->getUInt32(data_offset + 4, &entry_count)) { return ERROR_IO; } if (entry_count != 1) { ALOGW("ignoring edit list with %d entries", entry_count); } else if (mHeaderTimescale == 0) { ALOGW("ignoring edit list because timescale is 0"); } else { off64_t entriesoffset = data_offset + 8; uint64_t segment_duration; int64_t media_time; if (version == 1) { if (!mDataSource->getUInt64(entriesoffset, &segment_duration) || !mDataSource->getUInt64(entriesoffset + 8, (uint64_t*)&media_time)) { return ERROR_IO; } } else if (version == 0) { uint32_t sd; int32_t mt; if (!mDataSource->getUInt32(entriesoffset, &sd) || !mDataSource->getUInt32(entriesoffset + 4, (uint32_t*)&mt)) { return ERROR_IO; } segment_duration = sd; media_time = mt; } else { return ERROR_IO; } uint64_t halfscale = mHeaderTimescale / 2; segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale; media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale; int64_t duration; int32_t samplerate; if (!mLastTrack) { return ERROR_MALFORMED; } if (mLastTrack->meta->findInt64(kKeyDuration, &duration) && mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) { int64_t delay = (media_time * samplerate + 500000) / 1000000; mLastTrack->meta->setInt32(kKeyEncoderDelay, delay); int64_t paddingus = duration - (segment_duration + media_time); if (paddingus < 0) { paddingus = 0; } int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000; mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples); } } break; } case FOURCC('f', 'r', 'm', 'a'): { *offset += chunk_size; uint32_t original_fourcc; if (mDataSource->readAt(data_offset, &original_fourcc, 4) < 4) { return ERROR_IO; } original_fourcc = ntohl(original_fourcc); ALOGV("read original format: %d", original_fourcc); mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(original_fourcc)); uint32_t num_channels = 0; uint32_t sample_rate = 0; if (AdjustChannelsAndRate(original_fourcc, &num_channels, &sample_rate)) { mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); } break; } case FOURCC('t', 'e', 'n', 'c'): { *offset += chunk_size; if (chunk_size < 32) { return ERROR_MALFORMED; } char buf[4]; memset(buf, 0, 4); if (mDataSource->readAt(data_offset + 4, buf + 1, 3) < 3) { return ERROR_IO; } uint32_t defaultAlgorithmId = ntohl(*((int32_t*)buf)); if (defaultAlgorithmId > 1) { return ERROR_MALFORMED; } memset(buf, 0, 4); if (mDataSource->readAt(data_offset + 7, buf + 3, 1) < 1) { return ERROR_IO; } uint32_t defaultIVSize = ntohl(*((int32_t*)buf)); if ((defaultAlgorithmId == 0 && defaultIVSize != 0) || (defaultAlgorithmId != 0 && defaultIVSize == 0)) { return ERROR_MALFORMED; } else if (defaultIVSize != 0 && defaultIVSize != 8 && defaultIVSize != 16) { return ERROR_MALFORMED; } uint8_t defaultKeyId[16]; if (mDataSource->readAt(data_offset + 8, &defaultKeyId, 16) < 16) { return ERROR_IO; } mLastTrack->meta->setInt32(kKeyCryptoMode, defaultAlgorithmId); mLastTrack->meta->setInt32(kKeyCryptoDefaultIVSize, defaultIVSize); mLastTrack->meta->setData(kKeyCryptoKey, 'tenc', defaultKeyId, 16); break; } case FOURCC('t', 'k', 'h', 'd'): { *offset += chunk_size; status_t err; if ((err = parseTrackHeader(data_offset, chunk_data_size)) != OK) { return err; } break; } case FOURCC('p', 's', 's', 'h'): { *offset += chunk_size; PsshInfo pssh; if (mDataSource->readAt(data_offset + 4, &pssh.uuid, 16) < 16) { return ERROR_IO; } uint32_t psshdatalen = 0; if (mDataSource->readAt(data_offset + 20, &psshdatalen, 4) < 4) { return ERROR_IO; } pssh.datalen = ntohl(psshdatalen); ALOGV("pssh data size: %d", pssh.datalen); if (pssh.datalen + 20 > chunk_size) { return ERROR_MALFORMED; } pssh.data = new (std::nothrow) uint8_t[pssh.datalen]; if (pssh.data == NULL) { return ERROR_MALFORMED; } ALOGV("allocated pssh @ %p", pssh.data); ssize_t requested = (ssize_t) pssh.datalen; if (mDataSource->readAt(data_offset + 24, pssh.data, requested) < requested) { return ERROR_IO; } mPssh.push_back(pssh); break; } case FOURCC('m', 'd', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 4 || mLastTrack == NULL) { return ERROR_MALFORMED; } uint8_t version; if (mDataSource->readAt( data_offset, &version, sizeof(version)) < (ssize_t)sizeof(version)) { return ERROR_IO; } off64_t timescale_offset; if (version == 1) { timescale_offset = data_offset + 4 + 16; } else if (version == 0) { timescale_offset = data_offset + 4 + 8; } else { return ERROR_IO; } uint32_t timescale; if (mDataSource->readAt( timescale_offset, &timescale, sizeof(timescale)) < (ssize_t)sizeof(timescale)) { return ERROR_IO; } mLastTrack->timescale = ntohl(timescale); int64_t duration = 0; if (version == 1) { if (mDataSource->readAt( timescale_offset + 4, &duration, sizeof(duration)) < (ssize_t)sizeof(duration)) { return ERROR_IO; } if (duration != -1) { duration = ntoh64(duration); } } else { uint32_t duration32; if (mDataSource->readAt( timescale_offset + 4, &duration32, sizeof(duration32)) < (ssize_t)sizeof(duration32)) { return ERROR_IO; } if (duration32 != 0xffffffff) { duration = ntohl(duration32); } } if (duration != 0) { mLastTrack->meta->setInt64( kKeyDuration, (duration * 1000000) / mLastTrack->timescale); } uint8_t lang[2]; off64_t lang_offset; if (version == 1) { lang_offset = timescale_offset + 4 + 8; } else if (version == 0) { lang_offset = timescale_offset + 4 + 4; } else { return ERROR_IO; } if (mDataSource->readAt(lang_offset, &lang, sizeof(lang)) < (ssize_t)sizeof(lang)) { return ERROR_IO; } char lang_code[4]; lang_code[0] = ((lang[0] >> 2) & 0x1f) + 0x60; lang_code[1] = ((lang[0] & 0x3) << 3 | (lang[1] >> 5)) + 0x60; lang_code[2] = (lang[1] & 0x1f) + 0x60; lang_code[3] = '\0'; mLastTrack->meta->setCString( kKeyMediaLanguage, lang_code); break; } case FOURCC('s', 't', 's', 'd'): { if (chunk_data_size < 8) { return ERROR_MALFORMED; } uint8_t buffer[8]; if (chunk_data_size < (off64_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, 8) < 8) { return ERROR_IO; } if (U32_AT(buffer) != 0) { return ERROR_MALFORMED; } uint32_t entry_count = U32_AT(&buffer[4]); if (entry_count > 1) { const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) && strcasecmp(mime, "application/octet-stream")) { mLastTrack->skipTrack = true; *offset += chunk_size; break; } } off64_t stop_offset = *offset + chunk_size; *offset = data_offset + 8; for (uint32_t i = 0; i < entry_count; ++i) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'p', '4', 'a'): case FOURCC('e', 'n', 'c', 'a'): case FOURCC('s', 'a', 'm', 'r'): case FOURCC('s', 'a', 'w', 'b'): { uint8_t buffer[8 + 20]; if (chunk_data_size < (ssize_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { return ERROR_IO; } uint16_t data_ref_index = U16_AT(&buffer[6]); uint32_t num_channels = U16_AT(&buffer[16]); uint16_t sample_size = U16_AT(&buffer[18]); uint32_t sample_rate = U32_AT(&buffer[24]) >> 16; if (chunk_type != FOURCC('e', 'n', 'c', 'a')) { mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); AdjustChannelsAndRate(chunk_type, &num_channels, &sample_rate); } ALOGV("*** coding='%s' %d channels, size %d, rate %d\n", chunk, num_channels, sample_size, sample_rate); mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'p', '4', 'v'): case FOURCC('e', 'n', 'c', 'v'): case FOURCC('s', '2', '6', '3'): case FOURCC('H', '2', '6', '3'): case FOURCC('h', '2', '6', '3'): case FOURCC('a', 'v', 'c', '1'): case FOURCC('h', 'v', 'c', '1'): case FOURCC('h', 'e', 'v', '1'): { mHasVideo = true; uint8_t buffer[78]; if (chunk_data_size < (ssize_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { return ERROR_IO; } uint16_t data_ref_index = U16_AT(&buffer[6]); uint16_t width = U16_AT(&buffer[6 + 18]); uint16_t height = U16_AT(&buffer[6 + 20]); if (width == 0) width = 352; if (height == 0) height = 288; if (chunk_type != FOURCC('e', 'n', 'c', 'v')) { mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); } mLastTrack->meta->setInt32(kKeyWidth, width); mLastTrack->meta->setInt32(kKeyHeight, height); off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('s', 't', 'c', 'o'): case FOURCC('c', 'o', '6', '4'): { status_t err = mLastTrack->sampleTable->setChunkOffsetParams( chunk_type, data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 'c'): { status_t err = mLastTrack->sampleTable->setSampleToChunkParams( data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 'z'): case FOURCC('s', 't', 'z', '2'): { status_t err = mLastTrack->sampleTable->setSampleSizeParams( chunk_type, data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } size_t max_size; err = mLastTrack->sampleTable->getMaxSampleSize(&max_size); if (err != OK) { return err; } if (max_size != 0) { mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2); } else { int32_t width, height; if (!mLastTrack->meta->findInt32(kKeyWidth, &width) || !mLastTrack->meta->findInt32(kKeyHeight, &height)) { ALOGE("No width or height, assuming worst case 1080p"); width = 1920; height = 1080; } const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (!strcmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) { max_size = ((width + 15) / 16) * ((height + 15) / 16) * 192; } else { max_size = width * height * 3 / 2; } mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size); } const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (!strncasecmp("video/", mime, 6)) { size_t nSamples = mLastTrack->sampleTable->countSamples(); int64_t durationUs; if (mLastTrack->meta->findInt64(kKeyDuration, &durationUs)) { if (durationUs > 0) { int32_t frameRate = (nSamples * 1000000LL + (durationUs >> 1)) / durationUs; mLastTrack->meta->setInt32(kKeyFrameRate, frameRate); } } } break; } case FOURCC('s', 't', 't', 's'): { *offset += chunk_size; status_t err = mLastTrack->sampleTable->setTimeToSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('c', 't', 't', 's'): { *offset += chunk_size; status_t err = mLastTrack->sampleTable->setCompositionTimeToSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 's'): { *offset += chunk_size; status_t err = mLastTrack->sampleTable->setSyncSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('\xA9', 'x', 'y', 'z'): { *offset += chunk_size; if (chunk_data_size < 8) { return ERROR_MALFORMED; } char buffer[18]; off64_t location_length = chunk_data_size - 5; if (location_length >= (off64_t) sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset + 4, buffer, location_length) < location_length) { return ERROR_IO; } buffer[location_length] = '\0'; mFileMetaData->setCString(kKeyLocation, buffer); break; } case FOURCC('e', 's', 'd', 's'): { *offset += chunk_size; if (chunk_data_size < 4) { return ERROR_MALFORMED; } uint8_t buffer[256]; if (chunk_data_size > (off64_t)sizeof(buffer)) { return ERROR_BUFFER_TOO_SMALL; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (U32_AT(buffer) != 0) { return ERROR_MALFORMED; } mLastTrack->meta->setData( kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4); if (mPath.size() >= 2 && mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'a')) { status_t err = updateAudioTrackInfoFromESDS_MPEG4Audio( &buffer[4], chunk_data_size - 4); if (err != OK) { return err; } } break; } case FOURCC('a', 'v', 'c', 'C'): { *offset += chunk_size; sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } mLastTrack->meta->setData( kKeyAVCC, kTypeAVCC, buffer->data(), chunk_data_size); break; } case FOURCC('h', 'v', 'c', 'C'): { sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } mLastTrack->meta->setData( kKeyHVCC, kTypeHVCC, buffer->data(), chunk_data_size); *offset += chunk_size; break; } case FOURCC('d', '2', '6', '3'): { *offset += chunk_size; /* * d263 contains a fixed 7 bytes part: * vendor - 4 bytes * version - 1 byte * level - 1 byte * profile - 1 byte * optionally, "d263" box itself may contain a 16-byte * bit rate box (bitr) * average bit rate - 4 bytes * max bit rate - 4 bytes */ char buffer[23]; if (chunk_data_size != 7 && chunk_data_size != 23) { ALOGE("Incorrect D263 box size %lld", chunk_data_size); return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } mLastTrack->meta->setData(kKeyD263, kTypeD263, buffer, chunk_data_size); break; } case FOURCC('m', 'e', 't', 'a'): { uint8_t buffer[4]; if (chunk_data_size < (off64_t)sizeof(buffer)) { *offset += chunk_size; return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, 4) < 4) { *offset += chunk_size; return ERROR_IO; } if (U32_AT(buffer) != 0) { *offset += chunk_size; return OK; } off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'e', 'a', 'n'): case FOURCC('n', 'a', 'm', 'e'): case FOURCC('d', 'a', 't', 'a'): { *offset += chunk_size; if (mPath.size() == 6 && underMetaDataPath(mPath)) { status_t err = parseITunesMetaData(data_offset, chunk_data_size); if (err != OK) { return err; } } break; } case FOURCC('m', 'v', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 32) { return ERROR_MALFORMED; } uint8_t header[32]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } uint64_t creationTime; uint64_t duration = 0; if (header[0] == 1) { creationTime = U64_AT(&header[4]); mHeaderTimescale = U32_AT(&header[20]); duration = U64_AT(&header[24]); if (duration == 0xffffffffffffffff) { duration = 0; } } else if (header[0] != 0) { return ERROR_MALFORMED; } else { creationTime = U32_AT(&header[4]); mHeaderTimescale = U32_AT(&header[12]); uint32_t d32 = U32_AT(&header[16]); if (d32 == 0xffffffff) { d32 = 0; } duration = d32; } if (duration != 0) { mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); } String8 s; convertTimeToDate(creationTime, &s); mFileMetaData->setCString(kKeyDate, s.string()); break; } case FOURCC('m', 'e', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 8) { return ERROR_MALFORMED; } uint8_t flags[4]; if (mDataSource->readAt( data_offset, flags, sizeof(flags)) < (ssize_t)sizeof(flags)) { return ERROR_IO; } uint64_t duration = 0; if (flags[0] == 1) { if (chunk_data_size < 12) { return ERROR_MALFORMED; } mDataSource->getUInt64(data_offset + 4, &duration); if (duration == 0xffffffffffffffff) { duration = 0; } } else if (flags[0] == 0) { uint32_t d32; mDataSource->getUInt32(data_offset + 4, &d32); if (d32 == 0xffffffff) { d32 = 0; } duration = d32; } else { return ERROR_MALFORMED; } if (duration != 0) { mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); } break; } case FOURCC('m', 'd', 'a', 't'): { ALOGV("mdat chunk, drm: %d", mIsDrm); if (!mIsDrm) { *offset += chunk_size; break; } if (chunk_size < 8) { return ERROR_MALFORMED; } return parseDrmSINF(offset, data_offset); } case FOURCC('h', 'd', 'l', 'r'): { *offset += chunk_size; uint32_t buffer; if (mDataSource->readAt( data_offset + 8, &buffer, 4) < 4) { return ERROR_IO; } uint32_t type = ntohl(buffer); if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) { mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP); } break; } case FOURCC('t', 'r', 'e', 'x'): { *offset += chunk_size; if (chunk_data_size < 24) { return ERROR_IO; } uint32_t duration; Trex trex; if (!mDataSource->getUInt32(data_offset + 4, &trex.track_ID) || !mDataSource->getUInt32(data_offset + 8, &trex.default_sample_description_index) || !mDataSource->getUInt32(data_offset + 12, &trex.default_sample_duration) || !mDataSource->getUInt32(data_offset + 16, &trex.default_sample_size) || !mDataSource->getUInt32(data_offset + 20, &trex.default_sample_flags)) { return ERROR_IO; } mTrex.add(trex); break; } case FOURCC('t', 'x', '3', 'g'): { uint32_t type; const void *data; size_t size = 0; if (!mLastTrack->meta->findData( kKeyTextFormatData, &type, &data, &size)) { size = 0; } uint8_t *buffer = new (std::nothrow) uint8_t[size + chunk_size]; if (buffer == NULL) { return ERROR_MALFORMED; } if (size > 0) { memcpy(buffer, data, size); } if ((size_t)(mDataSource->readAt(*offset, buffer + size, chunk_size)) < chunk_size) { delete[] buffer; buffer = NULL; *offset += chunk_size; return ERROR_IO; } mLastTrack->meta->setData( kKeyTextFormatData, 0, buffer, size + chunk_size); delete[] buffer; *offset += chunk_size; break; } case FOURCC('c', 'o', 'v', 'r'): { *offset += chunk_size; if (mFileMetaData != NULL) { ALOGV("chunk_data_size = %lld and data_offset = %lld", chunk_data_size, data_offset); sp<ABuffer> buffer = new ABuffer(chunk_data_size + 1); if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) != (ssize_t)chunk_data_size) { return ERROR_IO; } const int kSkipBytesOfDataBox = 16; mFileMetaData->setData( kKeyAlbumArt, MetaData::TYPE_NONE, buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox); } break; } case FOURCC('t', 'i', 't', 'l'): case FOURCC('p', 'e', 'r', 'f'): case FOURCC('a', 'u', 't', 'h'): case FOURCC('g', 'n', 'r', 'e'): case FOURCC('a', 'l', 'b', 'm'): case FOURCC('y', 'r', 'r', 'c'): { *offset += chunk_size; status_t err = parse3GPPMetaData(data_offset, chunk_data_size, depth); if (err != OK) { return err; } break; } case FOURCC('I', 'D', '3', '2'): { *offset += chunk_size; if (chunk_data_size < 6) { return ERROR_MALFORMED; } parseID3v2MetaData(data_offset + 6); break; } case FOURCC('-', '-', '-', '-'): { mLastCommentMean.clear(); mLastCommentName.clear(); mLastCommentData.clear(); *offset += chunk_size; break; } case FOURCC('s', 'i', 'd', 'x'): { parseSegmentIndex(data_offset, chunk_data_size); *offset += chunk_size; return UNKNOWN_ERROR; // stop parsing after sidx } default: { *offset += chunk_size; break; } } return OK; } Commit Message: Fix integer underflow in covr MPEG4 processing When the 'chunk_data_size' variable is less than 'kSkipBytesOfDataBox', an integer underflow can occur. This causes an extraordinarily large value to be passed to MetaData::setData, leading to a buffer overflow. Bug: 20923261 Change-Id: Icd28f63594ad941eabb3a12c750a4a2d5d2bf94b CWE ID: CWE-119
status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) { ALOGV("entering parseChunk %lld/%d", *offset, depth); uint32_t hdr[2]; if (mDataSource->readAt(*offset, hdr, 8) < 8) { return ERROR_IO; } uint64_t chunk_size = ntohl(hdr[0]); uint32_t chunk_type = ntohl(hdr[1]); off64_t data_offset = *offset + 8; if (chunk_size == 1) { if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) { return ERROR_IO; } chunk_size = ntoh64(chunk_size); data_offset += 8; if (chunk_size < 16) { return ERROR_MALFORMED; } } else if (chunk_size == 0) { if (depth == 0) { off64_t sourceSize; if (mDataSource->getSize(&sourceSize) == OK) { chunk_size = (sourceSize - *offset); } else { ALOGE("atom size is 0, and data source has no size"); return ERROR_MALFORMED; } } else { *offset += 4; return OK; } } else if (chunk_size < 8) { ALOGE("invalid chunk size: %" PRIu64, chunk_size); return ERROR_MALFORMED; } char chunk[5]; MakeFourCCString(chunk_type, chunk); ALOGV("chunk: %s @ %lld, %d", chunk, *offset, depth); #if 0 static const char kWhitespace[] = " "; const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth]; printf("%sfound chunk '%s' of size %" PRIu64 "\n", indent, chunk, chunk_size); char buffer[256]; size_t n = chunk_size; if (n > sizeof(buffer)) { n = sizeof(buffer); } if (mDataSource->readAt(*offset, buffer, n) < (ssize_t)n) { return ERROR_IO; } hexdump(buffer, n); #endif PathAdder autoAdder(&mPath, chunk_type); off64_t chunk_data_size = *offset + chunk_size - data_offset; if (chunk_type != FOURCC('c', 'p', 'r', 't') && chunk_type != FOURCC('c', 'o', 'v', 'r') && mPath.size() == 5 && underMetaDataPath(mPath)) { off64_t stop_offset = *offset + chunk_size; *offset = data_offset; while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } return OK; } switch(chunk_type) { case FOURCC('m', 'o', 'o', 'v'): case FOURCC('t', 'r', 'a', 'k'): case FOURCC('m', 'd', 'i', 'a'): case FOURCC('m', 'i', 'n', 'f'): case FOURCC('d', 'i', 'n', 'f'): case FOURCC('s', 't', 'b', 'l'): case FOURCC('m', 'v', 'e', 'x'): case FOURCC('m', 'o', 'o', 'f'): case FOURCC('t', 'r', 'a', 'f'): case FOURCC('m', 'f', 'r', 'a'): case FOURCC('u', 'd', 't', 'a'): case FOURCC('i', 'l', 's', 't'): case FOURCC('s', 'i', 'n', 'f'): case FOURCC('s', 'c', 'h', 'i'): case FOURCC('e', 'd', 't', 's'): { if (chunk_type == FOURCC('s', 't', 'b', 'l')) { ALOGV("sampleTable chunk is %" PRIu64 " bytes long.", chunk_size); if (mDataSource->flags() & (DataSource::kWantsPrefetching | DataSource::kIsCachingDataSource)) { sp<MPEG4DataSource> cachedSource = new MPEG4DataSource(mDataSource); if (cachedSource->setCachedRange(*offset, chunk_size) == OK) { mDataSource = cachedSource; } } mLastTrack->sampleTable = new SampleTable(mDataSource); } bool isTrack = false; if (chunk_type == FOURCC('t', 'r', 'a', 'k')) { isTrack = true; Track *track = new Track; track->next = NULL; if (mLastTrack) { mLastTrack->next = track; } else { mFirstTrack = track; } mLastTrack = track; track->meta = new MetaData; track->includes_expensive_metadata = false; track->skipTrack = false; track->timescale = 0; track->meta->setCString(kKeyMIMEType, "application/octet-stream"); } off64_t stop_offset = *offset + chunk_size; *offset = data_offset; while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } if (isTrack) { if (mLastTrack->skipTrack) { Track *cur = mFirstTrack; if (cur == mLastTrack) { delete cur; mFirstTrack = mLastTrack = NULL; } else { while (cur && cur->next != mLastTrack) { cur = cur->next; } cur->next = NULL; delete mLastTrack; mLastTrack = cur; } return OK; } status_t err = verifyTrack(mLastTrack); if (err != OK) { return err; } } else if (chunk_type == FOURCC('m', 'o', 'o', 'v')) { mInitCheck = OK; if (!mIsDrm) { return UNKNOWN_ERROR; // Return a dummy error. } else { return OK; } } break; } case FOURCC('e', 'l', 's', 't'): { *offset += chunk_size; uint8_t version; if (mDataSource->readAt(data_offset, &version, 1) < 1) { return ERROR_IO; } uint32_t entry_count; if (!mDataSource->getUInt32(data_offset + 4, &entry_count)) { return ERROR_IO; } if (entry_count != 1) { ALOGW("ignoring edit list with %d entries", entry_count); } else if (mHeaderTimescale == 0) { ALOGW("ignoring edit list because timescale is 0"); } else { off64_t entriesoffset = data_offset + 8; uint64_t segment_duration; int64_t media_time; if (version == 1) { if (!mDataSource->getUInt64(entriesoffset, &segment_duration) || !mDataSource->getUInt64(entriesoffset + 8, (uint64_t*)&media_time)) { return ERROR_IO; } } else if (version == 0) { uint32_t sd; int32_t mt; if (!mDataSource->getUInt32(entriesoffset, &sd) || !mDataSource->getUInt32(entriesoffset + 4, (uint32_t*)&mt)) { return ERROR_IO; } segment_duration = sd; media_time = mt; } else { return ERROR_IO; } uint64_t halfscale = mHeaderTimescale / 2; segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale; media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale; int64_t duration; int32_t samplerate; if (!mLastTrack) { return ERROR_MALFORMED; } if (mLastTrack->meta->findInt64(kKeyDuration, &duration) && mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) { int64_t delay = (media_time * samplerate + 500000) / 1000000; mLastTrack->meta->setInt32(kKeyEncoderDelay, delay); int64_t paddingus = duration - (segment_duration + media_time); if (paddingus < 0) { paddingus = 0; } int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000; mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples); } } break; } case FOURCC('f', 'r', 'm', 'a'): { *offset += chunk_size; uint32_t original_fourcc; if (mDataSource->readAt(data_offset, &original_fourcc, 4) < 4) { return ERROR_IO; } original_fourcc = ntohl(original_fourcc); ALOGV("read original format: %d", original_fourcc); mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(original_fourcc)); uint32_t num_channels = 0; uint32_t sample_rate = 0; if (AdjustChannelsAndRate(original_fourcc, &num_channels, &sample_rate)) { mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); } break; } case FOURCC('t', 'e', 'n', 'c'): { *offset += chunk_size; if (chunk_size < 32) { return ERROR_MALFORMED; } char buf[4]; memset(buf, 0, 4); if (mDataSource->readAt(data_offset + 4, buf + 1, 3) < 3) { return ERROR_IO; } uint32_t defaultAlgorithmId = ntohl(*((int32_t*)buf)); if (defaultAlgorithmId > 1) { return ERROR_MALFORMED; } memset(buf, 0, 4); if (mDataSource->readAt(data_offset + 7, buf + 3, 1) < 1) { return ERROR_IO; } uint32_t defaultIVSize = ntohl(*((int32_t*)buf)); if ((defaultAlgorithmId == 0 && defaultIVSize != 0) || (defaultAlgorithmId != 0 && defaultIVSize == 0)) { return ERROR_MALFORMED; } else if (defaultIVSize != 0 && defaultIVSize != 8 && defaultIVSize != 16) { return ERROR_MALFORMED; } uint8_t defaultKeyId[16]; if (mDataSource->readAt(data_offset + 8, &defaultKeyId, 16) < 16) { return ERROR_IO; } mLastTrack->meta->setInt32(kKeyCryptoMode, defaultAlgorithmId); mLastTrack->meta->setInt32(kKeyCryptoDefaultIVSize, defaultIVSize); mLastTrack->meta->setData(kKeyCryptoKey, 'tenc', defaultKeyId, 16); break; } case FOURCC('t', 'k', 'h', 'd'): { *offset += chunk_size; status_t err; if ((err = parseTrackHeader(data_offset, chunk_data_size)) != OK) { return err; } break; } case FOURCC('p', 's', 's', 'h'): { *offset += chunk_size; PsshInfo pssh; if (mDataSource->readAt(data_offset + 4, &pssh.uuid, 16) < 16) { return ERROR_IO; } uint32_t psshdatalen = 0; if (mDataSource->readAt(data_offset + 20, &psshdatalen, 4) < 4) { return ERROR_IO; } pssh.datalen = ntohl(psshdatalen); ALOGV("pssh data size: %d", pssh.datalen); if (pssh.datalen + 20 > chunk_size) { return ERROR_MALFORMED; } pssh.data = new (std::nothrow) uint8_t[pssh.datalen]; if (pssh.data == NULL) { return ERROR_MALFORMED; } ALOGV("allocated pssh @ %p", pssh.data); ssize_t requested = (ssize_t) pssh.datalen; if (mDataSource->readAt(data_offset + 24, pssh.data, requested) < requested) { return ERROR_IO; } mPssh.push_back(pssh); break; } case FOURCC('m', 'd', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 4 || mLastTrack == NULL) { return ERROR_MALFORMED; } uint8_t version; if (mDataSource->readAt( data_offset, &version, sizeof(version)) < (ssize_t)sizeof(version)) { return ERROR_IO; } off64_t timescale_offset; if (version == 1) { timescale_offset = data_offset + 4 + 16; } else if (version == 0) { timescale_offset = data_offset + 4 + 8; } else { return ERROR_IO; } uint32_t timescale; if (mDataSource->readAt( timescale_offset, &timescale, sizeof(timescale)) < (ssize_t)sizeof(timescale)) { return ERROR_IO; } mLastTrack->timescale = ntohl(timescale); int64_t duration = 0; if (version == 1) { if (mDataSource->readAt( timescale_offset + 4, &duration, sizeof(duration)) < (ssize_t)sizeof(duration)) { return ERROR_IO; } if (duration != -1) { duration = ntoh64(duration); } } else { uint32_t duration32; if (mDataSource->readAt( timescale_offset + 4, &duration32, sizeof(duration32)) < (ssize_t)sizeof(duration32)) { return ERROR_IO; } if (duration32 != 0xffffffff) { duration = ntohl(duration32); } } if (duration != 0) { mLastTrack->meta->setInt64( kKeyDuration, (duration * 1000000) / mLastTrack->timescale); } uint8_t lang[2]; off64_t lang_offset; if (version == 1) { lang_offset = timescale_offset + 4 + 8; } else if (version == 0) { lang_offset = timescale_offset + 4 + 4; } else { return ERROR_IO; } if (mDataSource->readAt(lang_offset, &lang, sizeof(lang)) < (ssize_t)sizeof(lang)) { return ERROR_IO; } char lang_code[4]; lang_code[0] = ((lang[0] >> 2) & 0x1f) + 0x60; lang_code[1] = ((lang[0] & 0x3) << 3 | (lang[1] >> 5)) + 0x60; lang_code[2] = (lang[1] & 0x1f) + 0x60; lang_code[3] = '\0'; mLastTrack->meta->setCString( kKeyMediaLanguage, lang_code); break; } case FOURCC('s', 't', 's', 'd'): { if (chunk_data_size < 8) { return ERROR_MALFORMED; } uint8_t buffer[8]; if (chunk_data_size < (off64_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, 8) < 8) { return ERROR_IO; } if (U32_AT(buffer) != 0) { return ERROR_MALFORMED; } uint32_t entry_count = U32_AT(&buffer[4]); if (entry_count > 1) { const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) && strcasecmp(mime, "application/octet-stream")) { mLastTrack->skipTrack = true; *offset += chunk_size; break; } } off64_t stop_offset = *offset + chunk_size; *offset = data_offset + 8; for (uint32_t i = 0; i < entry_count; ++i) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'p', '4', 'a'): case FOURCC('e', 'n', 'c', 'a'): case FOURCC('s', 'a', 'm', 'r'): case FOURCC('s', 'a', 'w', 'b'): { uint8_t buffer[8 + 20]; if (chunk_data_size < (ssize_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { return ERROR_IO; } uint16_t data_ref_index = U16_AT(&buffer[6]); uint32_t num_channels = U16_AT(&buffer[16]); uint16_t sample_size = U16_AT(&buffer[18]); uint32_t sample_rate = U32_AT(&buffer[24]) >> 16; if (chunk_type != FOURCC('e', 'n', 'c', 'a')) { mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); AdjustChannelsAndRate(chunk_type, &num_channels, &sample_rate); } ALOGV("*** coding='%s' %d channels, size %d, rate %d\n", chunk, num_channels, sample_size, sample_rate); mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'p', '4', 'v'): case FOURCC('e', 'n', 'c', 'v'): case FOURCC('s', '2', '6', '3'): case FOURCC('H', '2', '6', '3'): case FOURCC('h', '2', '6', '3'): case FOURCC('a', 'v', 'c', '1'): case FOURCC('h', 'v', 'c', '1'): case FOURCC('h', 'e', 'v', '1'): { mHasVideo = true; uint8_t buffer[78]; if (chunk_data_size < (ssize_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { return ERROR_IO; } uint16_t data_ref_index = U16_AT(&buffer[6]); uint16_t width = U16_AT(&buffer[6 + 18]); uint16_t height = U16_AT(&buffer[6 + 20]); if (width == 0) width = 352; if (height == 0) height = 288; if (chunk_type != FOURCC('e', 'n', 'c', 'v')) { mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); } mLastTrack->meta->setInt32(kKeyWidth, width); mLastTrack->meta->setInt32(kKeyHeight, height); off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('s', 't', 'c', 'o'): case FOURCC('c', 'o', '6', '4'): { status_t err = mLastTrack->sampleTable->setChunkOffsetParams( chunk_type, data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 'c'): { status_t err = mLastTrack->sampleTable->setSampleToChunkParams( data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 'z'): case FOURCC('s', 't', 'z', '2'): { status_t err = mLastTrack->sampleTable->setSampleSizeParams( chunk_type, data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } size_t max_size; err = mLastTrack->sampleTable->getMaxSampleSize(&max_size); if (err != OK) { return err; } if (max_size != 0) { mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2); } else { int32_t width, height; if (!mLastTrack->meta->findInt32(kKeyWidth, &width) || !mLastTrack->meta->findInt32(kKeyHeight, &height)) { ALOGE("No width or height, assuming worst case 1080p"); width = 1920; height = 1080; } const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (!strcmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) { max_size = ((width + 15) / 16) * ((height + 15) / 16) * 192; } else { max_size = width * height * 3 / 2; } mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size); } const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (!strncasecmp("video/", mime, 6)) { size_t nSamples = mLastTrack->sampleTable->countSamples(); int64_t durationUs; if (mLastTrack->meta->findInt64(kKeyDuration, &durationUs)) { if (durationUs > 0) { int32_t frameRate = (nSamples * 1000000LL + (durationUs >> 1)) / durationUs; mLastTrack->meta->setInt32(kKeyFrameRate, frameRate); } } } break; } case FOURCC('s', 't', 't', 's'): { *offset += chunk_size; status_t err = mLastTrack->sampleTable->setTimeToSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('c', 't', 't', 's'): { *offset += chunk_size; status_t err = mLastTrack->sampleTable->setCompositionTimeToSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 's'): { *offset += chunk_size; status_t err = mLastTrack->sampleTable->setSyncSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('\xA9', 'x', 'y', 'z'): { *offset += chunk_size; if (chunk_data_size < 8) { return ERROR_MALFORMED; } char buffer[18]; off64_t location_length = chunk_data_size - 5; if (location_length >= (off64_t) sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset + 4, buffer, location_length) < location_length) { return ERROR_IO; } buffer[location_length] = '\0'; mFileMetaData->setCString(kKeyLocation, buffer); break; } case FOURCC('e', 's', 'd', 's'): { *offset += chunk_size; if (chunk_data_size < 4) { return ERROR_MALFORMED; } uint8_t buffer[256]; if (chunk_data_size > (off64_t)sizeof(buffer)) { return ERROR_BUFFER_TOO_SMALL; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (U32_AT(buffer) != 0) { return ERROR_MALFORMED; } mLastTrack->meta->setData( kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4); if (mPath.size() >= 2 && mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'a')) { status_t err = updateAudioTrackInfoFromESDS_MPEG4Audio( &buffer[4], chunk_data_size - 4); if (err != OK) { return err; } } break; } case FOURCC('a', 'v', 'c', 'C'): { *offset += chunk_size; sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } mLastTrack->meta->setData( kKeyAVCC, kTypeAVCC, buffer->data(), chunk_data_size); break; } case FOURCC('h', 'v', 'c', 'C'): { sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } mLastTrack->meta->setData( kKeyHVCC, kTypeHVCC, buffer->data(), chunk_data_size); *offset += chunk_size; break; } case FOURCC('d', '2', '6', '3'): { *offset += chunk_size; /* * d263 contains a fixed 7 bytes part: * vendor - 4 bytes * version - 1 byte * level - 1 byte * profile - 1 byte * optionally, "d263" box itself may contain a 16-byte * bit rate box (bitr) * average bit rate - 4 bytes * max bit rate - 4 bytes */ char buffer[23]; if (chunk_data_size != 7 && chunk_data_size != 23) { ALOGE("Incorrect D263 box size %lld", chunk_data_size); return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } mLastTrack->meta->setData(kKeyD263, kTypeD263, buffer, chunk_data_size); break; } case FOURCC('m', 'e', 't', 'a'): { uint8_t buffer[4]; if (chunk_data_size < (off64_t)sizeof(buffer)) { *offset += chunk_size; return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, 4) < 4) { *offset += chunk_size; return ERROR_IO; } if (U32_AT(buffer) != 0) { *offset += chunk_size; return OK; } off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'e', 'a', 'n'): case FOURCC('n', 'a', 'm', 'e'): case FOURCC('d', 'a', 't', 'a'): { *offset += chunk_size; if (mPath.size() == 6 && underMetaDataPath(mPath)) { status_t err = parseITunesMetaData(data_offset, chunk_data_size); if (err != OK) { return err; } } break; } case FOURCC('m', 'v', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 32) { return ERROR_MALFORMED; } uint8_t header[32]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } uint64_t creationTime; uint64_t duration = 0; if (header[0] == 1) { creationTime = U64_AT(&header[4]); mHeaderTimescale = U32_AT(&header[20]); duration = U64_AT(&header[24]); if (duration == 0xffffffffffffffff) { duration = 0; } } else if (header[0] != 0) { return ERROR_MALFORMED; } else { creationTime = U32_AT(&header[4]); mHeaderTimescale = U32_AT(&header[12]); uint32_t d32 = U32_AT(&header[16]); if (d32 == 0xffffffff) { d32 = 0; } duration = d32; } if (duration != 0) { mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); } String8 s; convertTimeToDate(creationTime, &s); mFileMetaData->setCString(kKeyDate, s.string()); break; } case FOURCC('m', 'e', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 8) { return ERROR_MALFORMED; } uint8_t flags[4]; if (mDataSource->readAt( data_offset, flags, sizeof(flags)) < (ssize_t)sizeof(flags)) { return ERROR_IO; } uint64_t duration = 0; if (flags[0] == 1) { if (chunk_data_size < 12) { return ERROR_MALFORMED; } mDataSource->getUInt64(data_offset + 4, &duration); if (duration == 0xffffffffffffffff) { duration = 0; } } else if (flags[0] == 0) { uint32_t d32; mDataSource->getUInt32(data_offset + 4, &d32); if (d32 == 0xffffffff) { d32 = 0; } duration = d32; } else { return ERROR_MALFORMED; } if (duration != 0) { mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); } break; } case FOURCC('m', 'd', 'a', 't'): { ALOGV("mdat chunk, drm: %d", mIsDrm); if (!mIsDrm) { *offset += chunk_size; break; } if (chunk_size < 8) { return ERROR_MALFORMED; } return parseDrmSINF(offset, data_offset); } case FOURCC('h', 'd', 'l', 'r'): { *offset += chunk_size; uint32_t buffer; if (mDataSource->readAt( data_offset + 8, &buffer, 4) < 4) { return ERROR_IO; } uint32_t type = ntohl(buffer); if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) { mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP); } break; } case FOURCC('t', 'r', 'e', 'x'): { *offset += chunk_size; if (chunk_data_size < 24) { return ERROR_IO; } uint32_t duration; Trex trex; if (!mDataSource->getUInt32(data_offset + 4, &trex.track_ID) || !mDataSource->getUInt32(data_offset + 8, &trex.default_sample_description_index) || !mDataSource->getUInt32(data_offset + 12, &trex.default_sample_duration) || !mDataSource->getUInt32(data_offset + 16, &trex.default_sample_size) || !mDataSource->getUInt32(data_offset + 20, &trex.default_sample_flags)) { return ERROR_IO; } mTrex.add(trex); break; } case FOURCC('t', 'x', '3', 'g'): { uint32_t type; const void *data; size_t size = 0; if (!mLastTrack->meta->findData( kKeyTextFormatData, &type, &data, &size)) { size = 0; } uint8_t *buffer = new (std::nothrow) uint8_t[size + chunk_size]; if (buffer == NULL) { return ERROR_MALFORMED; } if (size > 0) { memcpy(buffer, data, size); } if ((size_t)(mDataSource->readAt(*offset, buffer + size, chunk_size)) < chunk_size) { delete[] buffer; buffer = NULL; *offset += chunk_size; return ERROR_IO; } mLastTrack->meta->setData( kKeyTextFormatData, 0, buffer, size + chunk_size); delete[] buffer; *offset += chunk_size; break; } case FOURCC('c', 'o', 'v', 'r'): { *offset += chunk_size; if (mFileMetaData != NULL) { ALOGV("chunk_data_size = %lld and data_offset = %lld", chunk_data_size, data_offset); sp<ABuffer> buffer = new ABuffer(chunk_data_size + 1); if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) != (ssize_t)chunk_data_size) { return ERROR_IO; } const int kSkipBytesOfDataBox = 16; if (chunk_data_size <= kSkipBytesOfDataBox) { return ERROR_MALFORMED; } mFileMetaData->setData( kKeyAlbumArt, MetaData::TYPE_NONE, buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox); } break; } case FOURCC('t', 'i', 't', 'l'): case FOURCC('p', 'e', 'r', 'f'): case FOURCC('a', 'u', 't', 'h'): case FOURCC('g', 'n', 'r', 'e'): case FOURCC('a', 'l', 'b', 'm'): case FOURCC('y', 'r', 'r', 'c'): { *offset += chunk_size; status_t err = parse3GPPMetaData(data_offset, chunk_data_size, depth); if (err != OK) { return err; } break; } case FOURCC('I', 'D', '3', '2'): { *offset += chunk_size; if (chunk_data_size < 6) { return ERROR_MALFORMED; } parseID3v2MetaData(data_offset + 6); break; } case FOURCC('-', '-', '-', '-'): { mLastCommentMean.clear(); mLastCommentName.clear(); mLastCommentData.clear(); *offset += chunk_size; break; } case FOURCC('s', 'i', 'd', 'x'): { parseSegmentIndex(data_offset, chunk_data_size); *offset += chunk_size; return UNKNOWN_ERROR; // stop parsing after sidx } default: { *offset += chunk_size; break; } } return OK; }
173,368
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltNumber(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemNumberPtr comp = (xsltStyleItemNumberPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif if (comp == NULL) { xsltTransformError(ctxt, NULL, inst, "xsl:number : compilation failed\n"); return; } if ((ctxt == NULL) || (node == NULL) || (inst == NULL) || (comp == NULL)) return; comp->numdata.doc = inst->doc; comp->numdata.node = inst; xsltNumberFormat(ctxt, &comp->numdata, node); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltNumber(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemNumberPtr comp = (xsltStyleItemNumberPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif xmlXPathContextPtr xpctxt; xmlNsPtr *oldXPNamespaces; int oldXPNsNr; if (comp == NULL) { xsltTransformError(ctxt, NULL, inst, "xsl:number : compilation failed\n"); return; } if ((ctxt == NULL) || (node == NULL) || (inst == NULL) || (comp == NULL)) return; comp->numdata.doc = inst->doc; comp->numdata.node = inst; xpctxt = ctxt->xpathCtxt; oldXPNsNr = xpctxt->nsNr; oldXPNamespaces = xpctxt->namespaces; #ifdef XSLT_REFACTORED if (comp->inScopeNs != NULL) { xpctxt->namespaces = comp->inScopeNs->list; xpctxt->nsNr = comp->inScopeNs->xpathNumber; } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } #else xpctxt->namespaces = comp->nsList; xpctxt->nsNr = comp->nsNr; #endif xsltNumberFormat(ctxt, &comp->numdata, node); xpctxt->nsNr = oldXPNsNr; xpctxt->namespaces = oldXPNamespaces; }
173,329
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t MPEG4Source::fragmentedRead( MediaBuffer **out, const ReadOptions *options) { ALOGV("MPEG4Source::fragmentedRead"); CHECK(mStarted); *out = NULL; int64_t targetSampleTimeUs = -1; int64_t seekTimeUs; ReadOptions::SeekMode mode; if (options && options->getSeekTo(&seekTimeUs, &mode)) { int numSidxEntries = mSegments.size(); if (numSidxEntries != 0) { int64_t totalTime = 0; off64_t totalOffset = mFirstMoofOffset; for (int i = 0; i < numSidxEntries; i++) { const SidxEntry *se = &mSegments[i]; if (totalTime + se->mDurationUs > seekTimeUs) { if ((mode == ReadOptions::SEEK_NEXT_SYNC) || (mode == ReadOptions::SEEK_CLOSEST_SYNC && (seekTimeUs - totalTime) > (totalTime + se->mDurationUs - seekTimeUs))) { totalTime += se->mDurationUs; totalOffset += se->mSize; } break; } totalTime += se->mDurationUs; totalOffset += se->mSize; } mCurrentMoofOffset = totalOffset; mCurrentSamples.clear(); mCurrentSampleIndex = 0; parseChunk(&totalOffset); mCurrentTime = totalTime * mTimescale / 1000000ll; } if (mBuffer != NULL) { mBuffer->release(); mBuffer = NULL; } } off64_t offset = 0; size_t size; uint32_t cts = 0; bool isSyncSample = false; bool newBuffer = false; if (mBuffer == NULL) { newBuffer = true; if (mCurrentSampleIndex >= mCurrentSamples.size()) { Sample lastSample = mCurrentSamples[mCurrentSamples.size() - 1]; off64_t nextMoof = mNextMoofOffset; // lastSample.offset + lastSample.size; mCurrentMoofOffset = nextMoof; mCurrentSamples.clear(); mCurrentSampleIndex = 0; parseChunk(&nextMoof); if (mCurrentSampleIndex >= mCurrentSamples.size()) { return ERROR_END_OF_STREAM; } } const Sample *smpl = &mCurrentSamples[mCurrentSampleIndex]; offset = smpl->offset; size = smpl->size; cts = mCurrentTime; mCurrentTime += smpl->duration; isSyncSample = (mCurrentSampleIndex == 0); // XXX status_t err = mGroup->acquire_buffer(&mBuffer); if (err != OK) { CHECK(mBuffer == NULL); ALOGV("acquire_buffer returned %d", err); return err; } if (size > mBuffer->size()) { ALOGE("buffer too small: %zu > %zu", size, mBuffer->size()); return ERROR_BUFFER_TOO_SMALL; } } const Sample *smpl = &mCurrentSamples[mCurrentSampleIndex]; const sp<MetaData> bufmeta = mBuffer->meta_data(); bufmeta->clear(); if (smpl->encryptedsizes.size()) { bufmeta->setData(kKeyPlainSizes, 0, smpl->clearsizes.array(), smpl->clearsizes.size() * 4); bufmeta->setData(kKeyEncryptedSizes, 0, smpl->encryptedsizes.array(), smpl->encryptedsizes.size() * 4); bufmeta->setData(kKeyCryptoIV, 0, smpl->iv, 16); // use 16 or the actual size? bufmeta->setInt32(kKeyCryptoDefaultIVSize, mDefaultIVSize); bufmeta->setInt32(kKeyCryptoMode, mCryptoMode); bufmeta->setData(kKeyCryptoKey, 0, mCryptoKey, 16); } if (!mIsAVC || mWantsNALFragments) { if (newBuffer) { if (!isInRange((size_t)0u, mBuffer->size(), size)) { mBuffer->release(); mBuffer = NULL; ALOGE("fragmentedRead ERROR_MALFORMED size %zu", size); return ERROR_MALFORMED; } ssize_t num_bytes_read = mDataSource->readAt(offset, (uint8_t *)mBuffer->data(), size); if (num_bytes_read < (ssize_t)size) { mBuffer->release(); mBuffer = NULL; ALOGE("i/o error"); return ERROR_IO; } CHECK(mBuffer != NULL); mBuffer->set_range(0, size); mBuffer->meta_data()->setInt64( kKeyTime, ((int64_t)cts * 1000000) / mTimescale); if (targetSampleTimeUs >= 0) { mBuffer->meta_data()->setInt64( kKeyTargetTime, targetSampleTimeUs); } if (isSyncSample) { mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1); } ++mCurrentSampleIndex; } if (!mIsAVC) { *out = mBuffer; mBuffer = NULL; return OK; } CHECK(mBuffer->range_length() >= mNALLengthSize); const uint8_t *src = (const uint8_t *)mBuffer->data() + mBuffer->range_offset(); size_t nal_size = parseNALSize(src); if (mNALLengthSize > SIZE_MAX - nal_size) { ALOGE("b/24441553, b/24445122"); } if (mBuffer->range_length() - mNALLengthSize < nal_size) { ALOGE("incomplete NAL unit."); mBuffer->release(); mBuffer = NULL; return ERROR_MALFORMED; } MediaBuffer *clone = mBuffer->clone(); CHECK(clone != NULL); clone->set_range(mBuffer->range_offset() + mNALLengthSize, nal_size); CHECK(mBuffer != NULL); mBuffer->set_range( mBuffer->range_offset() + mNALLengthSize + nal_size, mBuffer->range_length() - mNALLengthSize - nal_size); if (mBuffer->range_length() == 0) { mBuffer->release(); mBuffer = NULL; } *out = clone; return OK; } else { ALOGV("whole NAL"); ssize_t num_bytes_read = 0; int32_t drm = 0; bool usesDRM = (mFormat->findInt32(kKeyIsDRM, &drm) && drm != 0); void *data = NULL; bool isMalFormed = false; if (usesDRM) { if (mBuffer == NULL || !isInRange((size_t)0u, mBuffer->size(), size)) { isMalFormed = true; } else { data = mBuffer->data(); } } else { int32_t max_size; if (mFormat == NULL || !mFormat->findInt32(kKeyMaxInputSize, &max_size) || !isInRange((size_t)0u, (size_t)max_size, size)) { isMalFormed = true; } else { data = mSrcBuffer; } } if (isMalFormed || data == NULL) { ALOGE("isMalFormed size %zu", size); if (mBuffer != NULL) { mBuffer->release(); mBuffer = NULL; } return ERROR_MALFORMED; } num_bytes_read = mDataSource->readAt(offset, data, size); if (num_bytes_read < (ssize_t)size) { mBuffer->release(); mBuffer = NULL; ALOGE("i/o error"); return ERROR_IO; } if (usesDRM) { CHECK(mBuffer != NULL); mBuffer->set_range(0, size); } else { uint8_t *dstData = (uint8_t *)mBuffer->data(); size_t srcOffset = 0; size_t dstOffset = 0; while (srcOffset < size) { isMalFormed = !isInRange((size_t)0u, size, srcOffset, mNALLengthSize); size_t nalLength = 0; if (!isMalFormed) { nalLength = parseNALSize(&mSrcBuffer[srcOffset]); srcOffset += mNALLengthSize; isMalFormed = !isInRange((size_t)0u, size, srcOffset, nalLength) || !isInRange((size_t)0u, mBuffer->size(), dstOffset, (size_t)4u) || !isInRange((size_t)0u, mBuffer->size(), dstOffset + 4, nalLength); } if (isMalFormed) { ALOGE("Video is malformed; nalLength %zu", nalLength); mBuffer->release(); mBuffer = NULL; return ERROR_MALFORMED; } if (nalLength == 0) { continue; } CHECK(dstOffset + 4 <= mBuffer->size()); dstData[dstOffset++] = 0; dstData[dstOffset++] = 0; dstData[dstOffset++] = 0; dstData[dstOffset++] = 1; memcpy(&dstData[dstOffset], &mSrcBuffer[srcOffset], nalLength); srcOffset += nalLength; dstOffset += nalLength; } CHECK_EQ(srcOffset, size); CHECK(mBuffer != NULL); mBuffer->set_range(0, dstOffset); } mBuffer->meta_data()->setInt64( kKeyTime, ((int64_t)cts * 1000000) / mTimescale); if (targetSampleTimeUs >= 0) { mBuffer->meta_data()->setInt64( kKeyTargetTime, targetSampleTimeUs); } if (isSyncSample) { mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1); } ++mCurrentSampleIndex; *out = mBuffer; mBuffer = NULL; return OK; } } Commit Message: Fix out-of-bounds write Bug: 26365349 Change-Id: Ia363d9f8c231cf255dea852e0bbf5ca466c7990b CWE ID: CWE-20
status_t MPEG4Source::fragmentedRead( MediaBuffer **out, const ReadOptions *options) { ALOGV("MPEG4Source::fragmentedRead"); CHECK(mStarted); *out = NULL; int64_t targetSampleTimeUs = -1; int64_t seekTimeUs; ReadOptions::SeekMode mode; if (options && options->getSeekTo(&seekTimeUs, &mode)) { int numSidxEntries = mSegments.size(); if (numSidxEntries != 0) { int64_t totalTime = 0; off64_t totalOffset = mFirstMoofOffset; for (int i = 0; i < numSidxEntries; i++) { const SidxEntry *se = &mSegments[i]; if (totalTime + se->mDurationUs > seekTimeUs) { if ((mode == ReadOptions::SEEK_NEXT_SYNC) || (mode == ReadOptions::SEEK_CLOSEST_SYNC && (seekTimeUs - totalTime) > (totalTime + se->mDurationUs - seekTimeUs))) { totalTime += se->mDurationUs; totalOffset += se->mSize; } break; } totalTime += se->mDurationUs; totalOffset += se->mSize; } mCurrentMoofOffset = totalOffset; mCurrentSamples.clear(); mCurrentSampleIndex = 0; parseChunk(&totalOffset); mCurrentTime = totalTime * mTimescale / 1000000ll; } if (mBuffer != NULL) { mBuffer->release(); mBuffer = NULL; } } off64_t offset = 0; size_t size; uint32_t cts = 0; bool isSyncSample = false; bool newBuffer = false; if (mBuffer == NULL) { newBuffer = true; if (mCurrentSampleIndex >= mCurrentSamples.size()) { Sample lastSample = mCurrentSamples[mCurrentSamples.size() - 1]; off64_t nextMoof = mNextMoofOffset; // lastSample.offset + lastSample.size; mCurrentMoofOffset = nextMoof; mCurrentSamples.clear(); mCurrentSampleIndex = 0; parseChunk(&nextMoof); if (mCurrentSampleIndex >= mCurrentSamples.size()) { return ERROR_END_OF_STREAM; } } const Sample *smpl = &mCurrentSamples[mCurrentSampleIndex]; offset = smpl->offset; size = smpl->size; cts = mCurrentTime; mCurrentTime += smpl->duration; isSyncSample = (mCurrentSampleIndex == 0); // XXX status_t err = mGroup->acquire_buffer(&mBuffer); if (err != OK) { CHECK(mBuffer == NULL); ALOGV("acquire_buffer returned %d", err); return err; } if (size > mBuffer->size()) { ALOGE("buffer too small: %zu > %zu", size, mBuffer->size()); return ERROR_BUFFER_TOO_SMALL; } } const Sample *smpl = &mCurrentSamples[mCurrentSampleIndex]; const sp<MetaData> bufmeta = mBuffer->meta_data(); bufmeta->clear(); if (smpl->encryptedsizes.size()) { bufmeta->setData(kKeyPlainSizes, 0, smpl->clearsizes.array(), smpl->clearsizes.size() * 4); bufmeta->setData(kKeyEncryptedSizes, 0, smpl->encryptedsizes.array(), smpl->encryptedsizes.size() * 4); bufmeta->setData(kKeyCryptoIV, 0, smpl->iv, 16); // use 16 or the actual size? bufmeta->setInt32(kKeyCryptoDefaultIVSize, mDefaultIVSize); bufmeta->setInt32(kKeyCryptoMode, mCryptoMode); bufmeta->setData(kKeyCryptoKey, 0, mCryptoKey, 16); } if (!mIsAVC || mWantsNALFragments) { if (newBuffer) { if (!isInRange((size_t)0u, mBuffer->size(), size)) { mBuffer->release(); mBuffer = NULL; ALOGE("fragmentedRead ERROR_MALFORMED size %zu", size); return ERROR_MALFORMED; } ssize_t num_bytes_read = mDataSource->readAt(offset, (uint8_t *)mBuffer->data(), size); if (num_bytes_read < (ssize_t)size) { mBuffer->release(); mBuffer = NULL; ALOGE("i/o error"); return ERROR_IO; } CHECK(mBuffer != NULL); mBuffer->set_range(0, size); mBuffer->meta_data()->setInt64( kKeyTime, ((int64_t)cts * 1000000) / mTimescale); if (targetSampleTimeUs >= 0) { mBuffer->meta_data()->setInt64( kKeyTargetTime, targetSampleTimeUs); } if (isSyncSample) { mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1); } ++mCurrentSampleIndex; } if (!mIsAVC) { *out = mBuffer; mBuffer = NULL; return OK; } CHECK(mBuffer->range_length() >= mNALLengthSize); const uint8_t *src = (const uint8_t *)mBuffer->data() + mBuffer->range_offset(); size_t nal_size = parseNALSize(src); if (mNALLengthSize > SIZE_MAX - nal_size) { ALOGE("b/24441553, b/24445122"); } if (mBuffer->range_length() - mNALLengthSize < nal_size) { ALOGE("incomplete NAL unit."); mBuffer->release(); mBuffer = NULL; return ERROR_MALFORMED; } MediaBuffer *clone = mBuffer->clone(); CHECK(clone != NULL); clone->set_range(mBuffer->range_offset() + mNALLengthSize, nal_size); CHECK(mBuffer != NULL); mBuffer->set_range( mBuffer->range_offset() + mNALLengthSize + nal_size, mBuffer->range_length() - mNALLengthSize - nal_size); if (mBuffer->range_length() == 0) { mBuffer->release(); mBuffer = NULL; } *out = clone; return OK; } else { ALOGV("whole NAL"); ssize_t num_bytes_read = 0; int32_t drm = 0; bool usesDRM = (mFormat->findInt32(kKeyIsDRM, &drm) && drm != 0); void *data = NULL; bool isMalFormed = false; if (usesDRM) { if (mBuffer == NULL || !isInRange((size_t)0u, mBuffer->size(), size)) { isMalFormed = true; } else { data = mBuffer->data(); } } else { int32_t max_size; if (mFormat == NULL || !mFormat->findInt32(kKeyMaxInputSize, &max_size) || !isInRange((size_t)0u, (size_t)max_size, size)) { isMalFormed = true; } else { data = mSrcBuffer; } } if (isMalFormed || data == NULL) { ALOGE("isMalFormed size %zu", size); if (mBuffer != NULL) { mBuffer->release(); mBuffer = NULL; } return ERROR_MALFORMED; } num_bytes_read = mDataSource->readAt(offset, data, size); if (num_bytes_read < (ssize_t)size) { mBuffer->release(); mBuffer = NULL; ALOGE("i/o error"); return ERROR_IO; } if (usesDRM) { CHECK(mBuffer != NULL); mBuffer->set_range(0, size); } else { uint8_t *dstData = (uint8_t *)mBuffer->data(); size_t srcOffset = 0; size_t dstOffset = 0; while (srcOffset < size) { isMalFormed = !isInRange((size_t)0u, size, srcOffset, mNALLengthSize); size_t nalLength = 0; if (!isMalFormed) { nalLength = parseNALSize(&mSrcBuffer[srcOffset]); srcOffset += mNALLengthSize; isMalFormed = !isInRange((size_t)0u, size, srcOffset, nalLength) || !isInRange((size_t)0u, mBuffer->size(), dstOffset, (size_t)4u) || !isInRange((size_t)0u, mBuffer->size(), dstOffset + 4, nalLength); } if (isMalFormed) { ALOGE("Video is malformed; nalLength %zu", nalLength); mBuffer->release(); mBuffer = NULL; return ERROR_MALFORMED; } if (nalLength == 0) { continue; } if (dstOffset > SIZE_MAX - 4 || dstOffset + 4 > SIZE_MAX - nalLength || dstOffset + 4 + nalLength > mBuffer->size()) { ALOGE("b/26365349 : %zu %zu", dstOffset, mBuffer->size()); android_errorWriteLog(0x534e4554, "26365349"); mBuffer->release(); mBuffer = NULL; return ERROR_MALFORMED; } dstData[dstOffset++] = 0; dstData[dstOffset++] = 0; dstData[dstOffset++] = 0; dstData[dstOffset++] = 1; memcpy(&dstData[dstOffset], &mSrcBuffer[srcOffset], nalLength); srcOffset += nalLength; dstOffset += nalLength; } CHECK_EQ(srcOffset, size); CHECK(mBuffer != NULL); mBuffer->set_range(0, dstOffset); } mBuffer->meta_data()->setInt64( kKeyTime, ((int64_t)cts * 1000000) / mTimescale); if (targetSampleTimeUs >= 0) { mBuffer->meta_data()->setInt64( kKeyTargetTime, targetSampleTimeUs); } if (isSyncSample) { mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1); } ++mCurrentSampleIndex; *out = mBuffer; mBuffer = NULL; return OK; } }
173,958
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: CuePoint::~CuePoint() { delete[] m_track_positions; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
CuePoint::~CuePoint()
174,462
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url, AVDictionary *opts, AVDictionary *opts2, int *is_http) { HLSContext *c = s->priv_data; AVDictionary *tmp = NULL; const char *proto_name = NULL; int ret; av_dict_copy(&tmp, opts, 0); av_dict_copy(&tmp, opts2, 0); if (av_strstart(url, "crypto", NULL)) { if (url[6] == '+' || url[6] == ':') proto_name = avio_find_protocol_name(url + 7); } if (!proto_name) proto_name = avio_find_protocol_name(url); if (!proto_name) return AVERROR_INVALIDDATA; if (!av_strstart(proto_name, "http", NULL) && !av_strstart(proto_name, "file", NULL)) return AVERROR_INVALIDDATA; if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':') ; else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':') ; else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5)) return AVERROR_INVALIDDATA; ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp); if (ret >= 0) { char *new_cookies = NULL; if (!(s->flags & AVFMT_FLAG_CUSTOM_IO)) av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies); if (new_cookies) { av_free(c->cookies); c->cookies = new_cookies; } av_dict_set(&opts, "cookies", c->cookies, 0); } av_dict_free(&tmp); if (is_http) *is_http = av_strstart(proto_name, "http", NULL); return ret; } Commit Message: avformat/hls: Check local file extensions This reduces the attack surface of local file-system information leaking. It prevents the existing exploit leading to an information leak. As well as similar hypothetical attacks. Leaks of information from files and symlinks ending in common multimedia extensions are still possible. But files with sensitive information like private keys and passwords generally do not use common multimedia filename extensions. It does not stop leaks via remote addresses in the LAN. The existing exploit depends on a specific decoder as well. It does appear though that the exploit should be possible with any decoder. The problem is that as long as sensitive information gets into the decoder, the output of the decoder becomes sensitive as well. The only obvious solution is to prevent access to sensitive information. Or to disable hls or possibly some of its feature. More complex solutions like checking the path to limit access to only subdirectories of the hls path may work as an alternative. But such solutions are fragile and tricky to implement portably and would not stop every possible attack nor would they work with all valid hls files. Developers have expressed their dislike / objected to disabling hls by default as well as disabling hls with local files. There also where objections against restricting remote url file extensions. This here is a less robust but also lower inconvenience solution. It can be applied stand alone or together with other solutions. limiting the check to local files was suggested by nevcairiel This recommits the security fix without the author name joke which was originally requested by Nicolas. Found-by: Emil Lerner and Pavel Cheremushkin Reported-by: Thierry Foucu <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-200
static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url, AVDictionary *opts, AVDictionary *opts2, int *is_http) { HLSContext *c = s->priv_data; AVDictionary *tmp = NULL; const char *proto_name = NULL; int ret; av_dict_copy(&tmp, opts, 0); av_dict_copy(&tmp, opts2, 0); if (av_strstart(url, "crypto", NULL)) { if (url[6] == '+' || url[6] == ':') proto_name = avio_find_protocol_name(url + 7); } if (!proto_name) proto_name = avio_find_protocol_name(url); if (!proto_name) return AVERROR_INVALIDDATA; if (av_strstart(proto_name, "file", NULL)) { if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) { av_log(s, AV_LOG_ERROR, "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n" "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n", url); return AVERROR_INVALIDDATA; } } else if (av_strstart(proto_name, "http", NULL)) { ; } else return AVERROR_INVALIDDATA; if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':') ; else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':') ; else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5)) return AVERROR_INVALIDDATA; ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp); if (ret >= 0) { char *new_cookies = NULL; if (!(s->flags & AVFMT_FLAG_CUSTOM_IO)) av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies); if (new_cookies) { av_free(c->cookies); c->cookies = new_cookies; } av_dict_set(&opts, "cookies", c->cookies, 0); } av_dict_free(&tmp); if (is_http) *is_http = av_strstart(proto_name, "http", NULL); return ret; }
170,044
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bgp_capabilities_print(netdissect_options *ndo, const u_char *opt, int caps_len) { int cap_type, cap_len, tcap_len, cap_offset; int i = 0; while (i < caps_len) { ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); cap_type=opt[i]; cap_len=opt[i+1]; tcap_len=cap_len; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_capcode_values, "Unknown", cap_type), cap_type, cap_len)); ND_TCHECK2(opt[i+2], cap_len); switch (cap_type) { case BGP_CAPCODE_MP: ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)", tok2str(af_values, "Unknown", EXTRACT_16BITS(opt+i+2)), EXTRACT_16BITS(opt+i+2), tok2str(bgp_safi_values, "Unknown", opt[i+5]), opt[i+5])); break; case BGP_CAPCODE_RESTART: /* Restart Flags (4 bits), Restart Time in seconds (12 bits) */ ND_TCHECK_16BITS(opt + i + 2); ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us", ((opt[i+2])&0x80) ? "R" : "none", EXTRACT_16BITS(opt+i+2)&0xfff)); tcap_len-=2; cap_offset=4; while(tcap_len>=4) { ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s", tok2str(af_values,"Unknown", EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown", opt[i+cap_offset+2]), opt[i+cap_offset+2], ((opt[i+cap_offset+3])&0x80) ? "yes" : "no" )); tcap_len-=4; cap_offset+=4; } break; case BGP_CAPCODE_RR: case BGP_CAPCODE_RR_CISCO: break; case BGP_CAPCODE_AS_NEW: /* * Extract the 4 byte AS number encoded. */ if (cap_len == 4) { ND_PRINT((ndo, "\n\t\t 4 Byte AS %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(opt + i + 2)))); } break; case BGP_CAPCODE_ADD_PATH: cap_offset=2; if (tcap_len == 0) { ND_PRINT((ndo, " (bogus)")); /* length */ break; } while (tcap_len > 0) { if (tcap_len < 4) { ND_PRINT((ndo, "\n\t\t(invalid)")); break; } ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s", tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]), opt[i+cap_offset+2], tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3]) )); tcap_len-=4; cap_offset+=4; } break; default: ND_PRINT((ndo, "\n\t\tno decoder for Capability %u", cap_type)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); break; } if (ndo->ndo_vflag > 1 && cap_len > 0) { print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); } i += BGP_CAP_HEADER_SIZE + cap_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } Commit Message: (for 4.9.3) CVE-2018-14467/BGP: Fix BGP_CAPCODE_MP. Add a bounds check and a comment to bgp_capabilities_print(). This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
bgp_capabilities_print(netdissect_options *ndo, const u_char *opt, int caps_len) { int cap_type, cap_len, tcap_len, cap_offset; int i = 0; while (i < caps_len) { ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); cap_type=opt[i]; cap_len=opt[i+1]; tcap_len=cap_len; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_capcode_values, "Unknown", cap_type), cap_type, cap_len)); ND_TCHECK2(opt[i+2], cap_len); switch (cap_type) { case BGP_CAPCODE_MP: /* AFI (16 bits), Reserved (8 bits), SAFI (8 bits) */ ND_TCHECK_8BITS(opt + i + 5); ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)", tok2str(af_values, "Unknown", EXTRACT_16BITS(opt+i+2)), EXTRACT_16BITS(opt+i+2), tok2str(bgp_safi_values, "Unknown", opt[i+5]), opt[i+5])); break; case BGP_CAPCODE_RESTART: /* Restart Flags (4 bits), Restart Time in seconds (12 bits) */ ND_TCHECK_16BITS(opt + i + 2); ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us", ((opt[i+2])&0x80) ? "R" : "none", EXTRACT_16BITS(opt+i+2)&0xfff)); tcap_len-=2; cap_offset=4; while(tcap_len>=4) { ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s", tok2str(af_values,"Unknown", EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown", opt[i+cap_offset+2]), opt[i+cap_offset+2], ((opt[i+cap_offset+3])&0x80) ? "yes" : "no" )); tcap_len-=4; cap_offset+=4; } break; case BGP_CAPCODE_RR: case BGP_CAPCODE_RR_CISCO: break; case BGP_CAPCODE_AS_NEW: /* * Extract the 4 byte AS number encoded. */ if (cap_len == 4) { ND_PRINT((ndo, "\n\t\t 4 Byte AS %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(opt + i + 2)))); } break; case BGP_CAPCODE_ADD_PATH: cap_offset=2; if (tcap_len == 0) { ND_PRINT((ndo, " (bogus)")); /* length */ break; } while (tcap_len > 0) { if (tcap_len < 4) { ND_PRINT((ndo, "\n\t\t(invalid)")); break; } ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s", tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]), opt[i+cap_offset+2], tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3]) )); tcap_len-=4; cap_offset+=4; } break; default: ND_PRINT((ndo, "\n\t\tno decoder for Capability %u", cap_type)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); break; } if (ndo->ndo_vflag > 1 && cap_len > 0) { print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); } i += BGP_CAP_HEADER_SIZE + cap_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); }
169,844
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image, *next_image, *pwp_image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; register Image *p; register ssize_t i; size_t filesize, length; ssize_t count; unsigned char magick[MagickPathExtent]; /* 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,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImage(image); return((Image *) NULL); } pwp_image=image; memset(magick,0,sizeof(magick)); count=ReadBlob(pwp_image,5,magick); if ((count != 5) || (LocaleNCompare((char *) magick,"SFW95",5) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); read_info=CloneImageInfo(image_info); (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL, (void *) NULL); SetImageInfoBlob(read_info,(void *) NULL,0); unique_file=AcquireUniqueFileResource(filename); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"sfw:%s", filename); for ( ; ; ) { (void) memset(magick,0,sizeof(magick)); for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image)) { for (i=0; i < 17; i++) magick[i]=magick[i+1]; magick[17]=(unsigned char) c; if (LocaleNCompare((char *) (magick+12),"SFW94A",6) == 0) break; } if (c == EOF) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } if (LocaleNCompare((char *) (magick+12),"SFW94A",6) != 0) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } /* Dump SFW image to a temporary file. */ file=(FILE *) NULL; if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowFileException(exception,FileOpenError,"UnableToWriteFile", image->filename); image=DestroyImageList(image); return((Image *) NULL); } length=fwrite("SFW94A",1,6,file); (void) length; filesize=65535UL*magick[2]+256L*magick[1]+magick[0]; for (i=0; i < (ssize_t) filesize; i++) { c=ReadBlobByte(pwp_image); if (c == EOF) break; (void) fputc(c,file); } (void) fclose(file); if (c == EOF) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } next_image=ReadImage(read_info,exception); if (next_image == (Image *) NULL) break; (void) FormatLocaleString(next_image->filename,MagickPathExtent, "slide_%02ld.sfw",(long) next_image->scene); if (image == (Image *) NULL) image=next_image; else { /* Link image into image list. */ for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ; next_image->previous=p; next_image->scene=p->scene+1; p->next=next_image; } if (image_info->number_scenes != 0) if (next_image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image), GetBlobSize(pwp_image)); if (status == MagickFalse) break; } if (unique_file != -1) (void) close(unique_file); (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { if (EOFBlob(image) != MagickFalse) { char *message; message=GetExceptionMessage(errno); (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s': %s",image->filename, message); message=DestroyString(message); } (void) CloseBlob(image); } return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1199 CWE ID: CWE-20
static Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image, *next_image, *pwp_image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; register Image *p; register ssize_t i; size_t filesize, length; ssize_t count; unsigned char magick[MagickPathExtent]; /* 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,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImage(image); return((Image *) NULL); } pwp_image=image; memset(magick,0,sizeof(magick)); count=ReadBlob(pwp_image,5,magick); if ((count != 5) || (LocaleNCompare((char *) magick,"SFW95",5) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); read_info=CloneImageInfo(image_info); (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL, (void *) NULL); SetImageInfoBlob(read_info,(void *) NULL,0); unique_file=AcquireUniqueFileResource(filename); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"sfw:%s", filename); for ( ; ; ) { (void) memset(magick,0,sizeof(magick)); for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image)) { for (i=0; i < 17; i++) magick[i]=magick[i+1]; magick[17]=(unsigned char) c; if (LocaleNCompare((char *) (magick+12),"SFW94A",6) == 0) break; } if (c == EOF) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } if (LocaleNCompare((char *) (magick+12),"SFW94A",6) != 0) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } /* Dump SFW image to a temporary file. */ file=(FILE *) NULL; if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowFileException(exception,FileOpenError,"UnableToWriteFile", image->filename); image=DestroyImageList(image); return((Image *) NULL); } length=fwrite("SFW94A",1,6,file); (void) length; filesize=65535UL*magick[2]+256L*magick[1]+magick[0]; for (i=0; i < (ssize_t) filesize; i++) { c=ReadBlobByte(pwp_image); if (c == EOF) break; if (fputc(c,file) != c) break; } (void) fclose(file); if (c == EOF) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } next_image=ReadImage(read_info,exception); if (next_image == (Image *) NULL) break; (void) FormatLocaleString(next_image->filename,MagickPathExtent, "slide_%02ld.sfw",(long) next_image->scene); if (image == (Image *) NULL) image=next_image; else { /* Link image into image list. */ for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ; next_image->previous=p; next_image->scene=p->scene+1; p->next=next_image; } if (image_info->number_scenes != 0) if (next_image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image), GetBlobSize(pwp_image)); if (status == MagickFalse) break; } if (unique_file != -1) (void) close(unique_file); (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { if (EOFBlob(image) != MagickFalse) { char *message; message=GetExceptionMessage(errno); (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s': %s",image->filename, message); message=DestroyString(message); } (void) CloseBlob(image); } return(GetFirstImageInList(image)); }
169,041
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: CreateDataReductionProxyChromeIOData( Profile* profile, const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner, const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(profile); DCHECK(profile->GetPrefs()); data_reduction_proxy::DataReductionProxySettings* data_reduction_proxy_settings = DataReductionProxyChromeSettingsFactory::GetForBrowserContext( profile); bool enabled = data_reduction_proxy_settings && data_reduction_proxy_settings->IsDataSaverEnabledByUser(); std::unique_ptr<data_reduction_proxy::DataReductionProxyIOData> data_reduction_proxy_io_data( new data_reduction_proxy::DataReductionProxyIOData( DataReductionProxyChromeSettings::GetClient(), profile->GetPrefs(), content::GetNetworkConnectionTracker(), io_task_runner, ui_task_runner, enabled, GetUserAgent(), version_info::GetChannelString(chrome::GetChannel()))); data_reduction_proxy_io_data->set_lofi_decider( std::make_unique<data_reduction_proxy::ContentLoFiDecider>()); data_reduction_proxy_io_data->set_resource_type_provider( std::make_unique<data_reduction_proxy::ContentResourceTypeProvider>()); data_reduction_proxy_io_data->set_lofi_ui_service( std::make_unique<data_reduction_proxy::ContentLoFiUIService>( ui_task_runner, base::Bind(&OnLoFiResponseReceivedOnUI))); return data_reduction_proxy_io_data; } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
CreateDataReductionProxyChromeIOData( Profile* profile, const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner, const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(profile); DCHECK(profile->GetPrefs()); bool enabled = data_reduction_proxy::DataReductionProxySettings:: IsDataSaverEnabledByUser(profile->GetPrefs()); std::unique_ptr<data_reduction_proxy::DataReductionProxyIOData> data_reduction_proxy_io_data( new data_reduction_proxy::DataReductionProxyIOData( DataReductionProxyChromeSettings::GetClient(), profile->GetPrefs(), content::GetNetworkConnectionTracker(), io_task_runner, ui_task_runner, enabled, GetUserAgent(), version_info::GetChannelString(chrome::GetChannel()))); data_reduction_proxy_io_data->set_lofi_decider( std::make_unique<data_reduction_proxy::ContentLoFiDecider>()); data_reduction_proxy_io_data->set_resource_type_provider( std::make_unique<data_reduction_proxy::ContentResourceTypeProvider>()); data_reduction_proxy_io_data->set_lofi_ui_service( std::make_unique<data_reduction_proxy::ContentLoFiUIService>( ui_task_runner, base::Bind(&OnLoFiResponseReceivedOnUI))); return data_reduction_proxy_io_data; }
172,549
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DiceTurnSyncOnHelper::AbortAndDelete() { if (signin_aborted_mode_ == SigninAbortedMode::REMOVE_ACCOUNT) { token_service_->RevokeCredentials(account_info_.account_id); } delete this; } Commit Message: [signin] Add metrics to track the source for refresh token updated events This CL add a source for update and revoke credentials operations. It then surfaces the source in the chrome://signin-internals page. This CL also records the following histograms that track refresh token events: * Signin.RefreshTokenUpdated.ToValidToken.Source * Signin.RefreshTokenUpdated.ToInvalidToken.Source * Signin.RefreshTokenRevoked.Source These histograms are needed to validate the assumptions of how often tokens are revoked by the browser and the sources for the token revocations. Bug: 896182 Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90 Reviewed-on: https://chromium-review.googlesource.com/c/1286464 Reviewed-by: Jochen Eisinger <[email protected]> Reviewed-by: David Roger <[email protected]> Reviewed-by: Ilya Sherman <[email protected]> Commit-Queue: Mihai Sardarescu <[email protected]> Cr-Commit-Position: refs/heads/master@{#606181} CWE ID: CWE-20
void DiceTurnSyncOnHelper::AbortAndDelete() { if (signin_aborted_mode_ == SigninAbortedMode::REMOVE_ACCOUNT) { token_service_->RevokeCredentials( account_info_.account_id, signin_metrics::SourceForRefreshTokenOperation:: kDiceTurnOnSyncHelper_Abort); } delete this; }
172,574
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) { int r, len; switch (node->type) { case BAG_MEMORY: r = compile_bag_memory_node(node, reg, env); break; case BAG_OPTION: r = compile_option_node(node, reg, env); break; case BAG_STOP_BACKTRACK: if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) { QuantNode* qn = QUANT_(NODE_BAG_BODY(node)); r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); if (r != 0) return r; len = compile_length_tree(NODE_QUANT_BODY(qn), reg); if (len < 0) return len; r = add_op(reg, OP_PUSH); if (r != 0) return r; COP(reg)->push.addr = SIZE_INC_OP + len + SIZE_OP_POP_OUT + SIZE_OP_JUMP; r = compile_tree(NODE_QUANT_BODY(qn), reg, env); if (r != 0) return r; r = add_op(reg, OP_POP_OUT); if (r != 0) return r; r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = -((int )SIZE_OP_PUSH + len + (int )SIZE_OP_POP_OUT); } else { r = add_op(reg, OP_ATOMIC_START); if (r != 0) return r; r = compile_tree(NODE_BAG_BODY(node), reg, env); if (r != 0) return r; r = add_op(reg, OP_ATOMIC_END); } break; case BAG_IF_ELSE: { int cond_len, then_len, jump_len; Node* cond = NODE_BAG_BODY(node); Node* Then = node->te.Then; Node* Else = node->te.Else; r = add_op(reg, OP_ATOMIC_START); if (r != 0) return r; cond_len = compile_length_tree(cond, reg); if (cond_len < 0) return cond_len; if (IS_NOT_NULL(Then)) { then_len = compile_length_tree(Then, reg); if (then_len < 0) return then_len; } else then_len = 0; jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END; if (IS_NOT_NULL(Else)) jump_len += SIZE_OP_JUMP; r = add_op(reg, OP_PUSH); if (r != 0) return r; COP(reg)->push.addr = SIZE_INC_OP + jump_len; r = compile_tree(cond, reg, env); if (r != 0) return r; r = add_op(reg, OP_ATOMIC_END); if (r != 0) return r; if (IS_NOT_NULL(Then)) { r = compile_tree(Then, reg, env); if (r != 0) return r; } if (IS_NOT_NULL(Else)) { int else_len = compile_length_tree(Else, reg); r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = else_len + SIZE_INC_OP; r = compile_tree(Else, reg, env); } } break; } return r; } Commit Message: Fix CVE-2019-13225: problem in converting if-then-else pattern to bytecode. CWE ID: CWE-476
compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) { int r, len; switch (node->type) { case BAG_MEMORY: r = compile_bag_memory_node(node, reg, env); break; case BAG_OPTION: r = compile_option_node(node, reg, env); break; case BAG_STOP_BACKTRACK: if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) { QuantNode* qn = QUANT_(NODE_BAG_BODY(node)); r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); if (r != 0) return r; len = compile_length_tree(NODE_QUANT_BODY(qn), reg); if (len < 0) return len; r = add_op(reg, OP_PUSH); if (r != 0) return r; COP(reg)->push.addr = SIZE_INC_OP + len + SIZE_OP_POP_OUT + SIZE_OP_JUMP; r = compile_tree(NODE_QUANT_BODY(qn), reg, env); if (r != 0) return r; r = add_op(reg, OP_POP_OUT); if (r != 0) return r; r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = -((int )SIZE_OP_PUSH + len + (int )SIZE_OP_POP_OUT); } else { r = add_op(reg, OP_ATOMIC_START); if (r != 0) return r; r = compile_tree(NODE_BAG_BODY(node), reg, env); if (r != 0) return r; r = add_op(reg, OP_ATOMIC_END); } break; case BAG_IF_ELSE: { int cond_len, then_len, else_len, jump_len; Node* cond = NODE_BAG_BODY(node); Node* Then = node->te.Then; Node* Else = node->te.Else; r = add_op(reg, OP_ATOMIC_START); if (r != 0) return r; cond_len = compile_length_tree(cond, reg); if (cond_len < 0) return cond_len; if (IS_NOT_NULL(Then)) { then_len = compile_length_tree(Then, reg); if (then_len < 0) return then_len; } else then_len = 0; jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END + SIZE_OP_JUMP; r = add_op(reg, OP_PUSH); if (r != 0) return r; COP(reg)->push.addr = SIZE_INC_OP + jump_len; r = compile_tree(cond, reg, env); if (r != 0) return r; r = add_op(reg, OP_ATOMIC_END); if (r != 0) return r; if (IS_NOT_NULL(Then)) { r = compile_tree(Then, reg, env); if (r != 0) return r; } if (IS_NOT_NULL(Else)) { else_len = compile_length_tree(Else, reg); if (else_len < 0) return else_len; } else else_len = 0; r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = SIZE_OP_ATOMIC_END + else_len + SIZE_INC_OP; r = add_op(reg, OP_ATOMIC_END); if (r != 0) return r; if (IS_NOT_NULL(Else)) { r = compile_tree(Else, reg, env); } } break; } return r; }
169,611
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ, edge_connection_t *conn, crypt_path_t *layer_hint) { static int num_seen=0; relay_header_t rh; unsigned domain = layer_hint?LD_APP:LD_EXIT; int reason; int optimistic_data = 0; /* Set to 1 if we receive data on a stream * that's in the EXIT_CONN_STATE_RESOLVING * or EXIT_CONN_STATE_CONNECTING states. */ tor_assert(cell); tor_assert(circ); relay_header_unpack(&rh, cell->payload); num_seen++; log_debug(domain, "Now seen %d relay cells here (command %d, stream %d).", num_seen, rh.command, rh.stream_id); if (rh.length > RELAY_PAYLOAD_SIZE) { log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay cell length field too long. Closing circuit."); return - END_CIRC_REASON_TORPROTOCOL; } if (rh.stream_id == 0) { switch (rh.command) { case RELAY_COMMAND_BEGIN: case RELAY_COMMAND_CONNECTED: case RELAY_COMMAND_DATA: case RELAY_COMMAND_END: case RELAY_COMMAND_RESOLVE: case RELAY_COMMAND_RESOLVED: case RELAY_COMMAND_BEGIN_DIR: log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay command %d with zero " "stream_id. Dropping.", (int)rh.command); return 0; default: ; } } /* either conn is NULL, in which case we've got a control cell, or else * conn points to the recognized stream. */ if (conn && !connection_state_is_open(TO_CONN(conn))) { if (conn->base_.type == CONN_TYPE_EXIT && (conn->base_.state == EXIT_CONN_STATE_CONNECTING || conn->base_.state == EXIT_CONN_STATE_RESOLVING) && rh.command == RELAY_COMMAND_DATA) { /* Allow DATA cells to be delivered to an exit node in state * EXIT_CONN_STATE_CONNECTING or EXIT_CONN_STATE_RESOLVING. * This speeds up HTTP, for example. */ optimistic_data = 1; } else { return connection_edge_process_relay_cell_not_open( &rh, cell, circ, conn, layer_hint); } } switch (rh.command) { case RELAY_COMMAND_DROP: return 0; case RELAY_COMMAND_BEGIN: case RELAY_COMMAND_BEGIN_DIR: if (layer_hint && circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) { log_fn(LOG_PROTOCOL_WARN, LD_APP, "Relay begin request unsupported at AP. Dropping."); return 0; } if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED && layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) { log_fn(LOG_PROTOCOL_WARN, LD_APP, "Relay begin request to Hidden Service " "from intermediary node. Dropping."); return 0; } if (conn) { log_fn(LOG_PROTOCOL_WARN, domain, "Begin cell for known stream. Dropping."); return 0; } if (rh.command == RELAY_COMMAND_BEGIN_DIR) { /* Assign this circuit and its app-ward OR connection a unique ID, * so that we can measure download times. The local edge and dir * connection will be assigned the same ID when they are created * and linked. */ static uint64_t next_id = 0; circ->dirreq_id = ++next_id; TO_OR_CIRCUIT(circ)->p_chan->dirreq_id = circ->dirreq_id; } return connection_exit_begin_conn(cell, circ); case RELAY_COMMAND_DATA: ++stats_n_data_cells_received; if (( layer_hint && --layer_hint->deliver_window < 0) || (!layer_hint && --circ->deliver_window < 0)) { log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "(relay data) circ deliver_window below 0. Killing."); if (conn) { /* XXXX Do we actually need to do this? Will killing the circuit * not send an END and mark the stream for close as appropriate? */ connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL); connection_mark_for_close(TO_CONN(conn)); } return -END_CIRC_REASON_TORPROTOCOL; } log_debug(domain,"circ deliver_window now %d.", layer_hint ? layer_hint->deliver_window : circ->deliver_window); circuit_consider_sending_sendme(circ, layer_hint); if (!conn) { log_info(domain,"data cell dropped, unknown stream (streamid %d).", rh.stream_id); return 0; } if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */ log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "(relay data) conn deliver_window below 0. Killing."); return -END_CIRC_REASON_TORPROTOCOL; } stats_n_data_bytes_received += rh.length; connection_write_to_buf((char*)(cell->payload + RELAY_HEADER_SIZE), rh.length, TO_CONN(conn)); if (!optimistic_data) { /* Only send a SENDME if we're not getting optimistic data; otherwise * a SENDME could arrive before the CONNECTED. */ connection_edge_consider_sending_sendme(conn); } return 0; case RELAY_COMMAND_END: reason = rh.length > 0 ? get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC; if (!conn) { log_info(domain,"end cell (%s) dropped, unknown stream.", stream_end_reason_to_string(reason)); return 0; } /* XXX add to this log_fn the exit node's nickname? */ log_info(domain,TOR_SOCKET_T_FORMAT": end cell (%s) for stream %d. " "Removing stream.", conn->base_.s, stream_end_reason_to_string(reason), conn->stream_id); if (conn->base_.type == CONN_TYPE_AP) { entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn); if (entry_conn->socks_request && !entry_conn->socks_request->has_finished) log_warn(LD_BUG, "open stream hasn't sent socks answer yet? Closing."); } /* We just *got* an end; no reason to send one. */ conn->edge_has_sent_end = 1; if (!conn->end_reason) conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE; if (!conn->base_.marked_for_close) { /* only mark it if not already marked. it's possible to * get the 'end' right around when the client hangs up on us. */ connection_mark_and_flush(TO_CONN(conn)); } return 0; case RELAY_COMMAND_EXTEND: case RELAY_COMMAND_EXTEND2: { static uint64_t total_n_extend=0, total_nonearly=0; total_n_extend++; if (rh.stream_id) { log_fn(LOG_PROTOCOL_WARN, domain, "'extend' cell received for non-zero stream. Dropping."); return 0; } if (cell->command != CELL_RELAY_EARLY && !networkstatus_get_param(NULL,"AllowNonearlyExtend",0,0,1)) { #define EARLY_WARNING_INTERVAL 3600 static ratelim_t early_warning_limit = RATELIM_INIT(EARLY_WARNING_INTERVAL); char *m; if (cell->command == CELL_RELAY) { ++total_nonearly; if ((m = rate_limit_log(&early_warning_limit, approx_time()))) { double percentage = ((double)total_nonearly)/total_n_extend; percentage *= 100; log_fn(LOG_PROTOCOL_WARN, domain, "EXTEND cell received, " "but not via RELAY_EARLY. Dropping.%s", m); log_fn(LOG_PROTOCOL_WARN, domain, " (We have dropped %.02f%% of " "all EXTEND cells for this reason)", percentage); tor_free(m); } } else { log_fn(LOG_WARN, domain, "EXTEND cell received, in a cell with type %d! Dropping.", cell->command); } return 0; } return circuit_extend(cell, circ); } case RELAY_COMMAND_EXTENDED: case RELAY_COMMAND_EXTENDED2: if (!layer_hint) { log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "'extended' unsupported at non-origin. Dropping."); return 0; } log_debug(domain,"Got an extended cell! Yay."); { extended_cell_t extended_cell; if (extended_cell_parse(&extended_cell, rh.command, (const uint8_t*)cell->payload+RELAY_HEADER_SIZE, rh.length)<0) { log_warn(LD_PROTOCOL, "Can't parse EXTENDED cell; killing circuit."); return -END_CIRC_REASON_TORPROTOCOL; } if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ), &extended_cell.created_cell)) < 0) { log_warn(domain,"circuit_finish_handshake failed."); return reason; } } if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) { log_info(domain,"circuit_send_next_onion_skin() failed."); return reason; } return 0; case RELAY_COMMAND_TRUNCATE: if (layer_hint) { log_fn(LOG_PROTOCOL_WARN, LD_APP, "'truncate' unsupported at origin. Dropping."); return 0; } if (circ->n_hop) { if (circ->n_chan) log_warn(LD_BUG, "n_chan and n_hop set on the same circuit!"); extend_info_free(circ->n_hop); circ->n_hop = NULL; tor_free(circ->n_chan_create_cell); circuit_set_state(circ, CIRCUIT_STATE_OPEN); } if (circ->n_chan) { uint8_t trunc_reason = get_uint8(cell->payload + RELAY_HEADER_SIZE); circuit_clear_cell_queue(circ, circ->n_chan); channel_send_destroy(circ->n_circ_id, circ->n_chan, trunc_reason); circuit_set_n_circid_chan(circ, 0, NULL); } log_debug(LD_EXIT, "Processed 'truncate', replying."); { char payload[1]; payload[0] = (char)END_CIRC_REASON_REQUESTED; relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED, payload, sizeof(payload), NULL); } return 0; case RELAY_COMMAND_TRUNCATED: if (!layer_hint) { log_fn(LOG_PROTOCOL_WARN, LD_EXIT, "'truncated' unsupported at non-origin. Dropping."); return 0; } circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint, get_uint8(cell->payload + RELAY_HEADER_SIZE)); return 0; case RELAY_COMMAND_CONNECTED: if (conn) { log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "'connected' unsupported while open. Closing circ."); return -END_CIRC_REASON_TORPROTOCOL; } log_info(domain, "'connected' received, no conn attached anymore. Ignoring."); return 0; case RELAY_COMMAND_SENDME: if (!rh.stream_id) { if (layer_hint) { if (layer_hint->package_window + CIRCWINDOW_INCREMENT > CIRCWINDOW_START_MAX) { log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Unexpected sendme cell from exit relay. " "Closing circ."); return -END_CIRC_REASON_TORPROTOCOL; } layer_hint->package_window += CIRCWINDOW_INCREMENT; log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.", layer_hint->package_window); circuit_resume_edge_reading(circ, layer_hint); } else { if (circ->package_window + CIRCWINDOW_INCREMENT > CIRCWINDOW_START_MAX) { log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Unexpected sendme cell from client. " "Closing circ (window %d).", circ->package_window); return -END_CIRC_REASON_TORPROTOCOL; } circ->package_window += CIRCWINDOW_INCREMENT; log_debug(LD_APP, "circ-level sendme at non-origin, packagewindow %d.", circ->package_window); circuit_resume_edge_reading(circ, layer_hint); } return 0; } if (!conn) { log_info(domain,"sendme cell dropped, unknown stream (streamid %d).", rh.stream_id); return 0; } conn->package_window += STREAMWINDOW_INCREMENT; log_debug(domain,"stream-level sendme, packagewindow now %d.", conn->package_window); if (circuit_queue_streams_are_blocked(circ)) { /* Still waiting for queue to flush; don't touch conn */ return 0; } connection_start_reading(TO_CONN(conn)); /* handle whatever might still be on the inbuf */ if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) { /* (We already sent an end cell if possible) */ connection_mark_for_close(TO_CONN(conn)); return 0; } return 0; case RELAY_COMMAND_RESOLVE: if (layer_hint) { log_fn(LOG_PROTOCOL_WARN, LD_APP, "resolve request unsupported at AP; dropping."); return 0; } else if (conn) { log_fn(LOG_PROTOCOL_WARN, domain, "resolve request for known stream; dropping."); return 0; } else if (circ->purpose != CIRCUIT_PURPOSE_OR) { log_fn(LOG_PROTOCOL_WARN, domain, "resolve request on circ with purpose %d; dropping", circ->purpose); return 0; } connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ)); return 0; case RELAY_COMMAND_RESOLVED: if (conn) { log_fn(LOG_PROTOCOL_WARN, domain, "'resolved' unsupported while open. Closing circ."); return -END_CIRC_REASON_TORPROTOCOL; } log_info(domain, "'resolved' received, no conn attached anymore. Ignoring."); return 0; case RELAY_COMMAND_ESTABLISH_INTRO: case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: case RELAY_COMMAND_INTRODUCE1: case RELAY_COMMAND_INTRODUCE2: case RELAY_COMMAND_INTRODUCE_ACK: case RELAY_COMMAND_RENDEZVOUS1: case RELAY_COMMAND_RENDEZVOUS2: case RELAY_COMMAND_INTRO_ESTABLISHED: case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED: rend_process_relay_cell(circ, layer_hint, rh.command, rh.length, cell->payload+RELAY_HEADER_SIZE); return 0; } log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Received unknown relay command %d. Perhaps the other side is using " "a newer version of Tor? Dropping.", rh.command); return 0; /* for forward compatibility, don't kill the circuit */ } Commit Message: TROVE-2017-005: Fix assertion failure in connection_edge_process_relay_cell On an hidden service rendezvous circuit, a BEGIN_DIR could be sent (maliciously) which would trigger a tor_assert() because connection_edge_process_relay_cell() thought that the circuit is an or_circuit_t but is an origin circuit in reality. Fixes #22494 Reported-by: Roger Dingledine <[email protected]> Signed-off-by: David Goulet <[email protected]> CWE ID: CWE-617
connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ, edge_connection_t *conn, crypt_path_t *layer_hint) { static int num_seen=0; relay_header_t rh; unsigned domain = layer_hint?LD_APP:LD_EXIT; int reason; int optimistic_data = 0; /* Set to 1 if we receive data on a stream * that's in the EXIT_CONN_STATE_RESOLVING * or EXIT_CONN_STATE_CONNECTING states. */ tor_assert(cell); tor_assert(circ); relay_header_unpack(&rh, cell->payload); num_seen++; log_debug(domain, "Now seen %d relay cells here (command %d, stream %d).", num_seen, rh.command, rh.stream_id); if (rh.length > RELAY_PAYLOAD_SIZE) { log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay cell length field too long. Closing circuit."); return - END_CIRC_REASON_TORPROTOCOL; } if (rh.stream_id == 0) { switch (rh.command) { case RELAY_COMMAND_BEGIN: case RELAY_COMMAND_CONNECTED: case RELAY_COMMAND_DATA: case RELAY_COMMAND_END: case RELAY_COMMAND_RESOLVE: case RELAY_COMMAND_RESOLVED: case RELAY_COMMAND_BEGIN_DIR: log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay command %d with zero " "stream_id. Dropping.", (int)rh.command); return 0; default: ; } } /* either conn is NULL, in which case we've got a control cell, or else * conn points to the recognized stream. */ if (conn && !connection_state_is_open(TO_CONN(conn))) { if (conn->base_.type == CONN_TYPE_EXIT && (conn->base_.state == EXIT_CONN_STATE_CONNECTING || conn->base_.state == EXIT_CONN_STATE_RESOLVING) && rh.command == RELAY_COMMAND_DATA) { /* Allow DATA cells to be delivered to an exit node in state * EXIT_CONN_STATE_CONNECTING or EXIT_CONN_STATE_RESOLVING. * This speeds up HTTP, for example. */ optimistic_data = 1; } else { return connection_edge_process_relay_cell_not_open( &rh, cell, circ, conn, layer_hint); } } switch (rh.command) { case RELAY_COMMAND_DROP: return 0; case RELAY_COMMAND_BEGIN: case RELAY_COMMAND_BEGIN_DIR: if (layer_hint && circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) { log_fn(LOG_PROTOCOL_WARN, LD_APP, "Relay begin request unsupported at AP. Dropping."); return 0; } if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED && layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) { log_fn(LOG_PROTOCOL_WARN, LD_APP, "Relay begin request to Hidden Service " "from intermediary node. Dropping."); return 0; } if (conn) { log_fn(LOG_PROTOCOL_WARN, domain, "Begin cell for known stream. Dropping."); return 0; } if (rh.command == RELAY_COMMAND_BEGIN_DIR && circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) { /* Assign this circuit and its app-ward OR connection a unique ID, * so that we can measure download times. The local edge and dir * connection will be assigned the same ID when they are created * and linked. */ static uint64_t next_id = 0; circ->dirreq_id = ++next_id; TO_OR_CIRCUIT(circ)->p_chan->dirreq_id = circ->dirreq_id; } return connection_exit_begin_conn(cell, circ); case RELAY_COMMAND_DATA: ++stats_n_data_cells_received; if (( layer_hint && --layer_hint->deliver_window < 0) || (!layer_hint && --circ->deliver_window < 0)) { log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "(relay data) circ deliver_window below 0. Killing."); if (conn) { /* XXXX Do we actually need to do this? Will killing the circuit * not send an END and mark the stream for close as appropriate? */ connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL); connection_mark_for_close(TO_CONN(conn)); } return -END_CIRC_REASON_TORPROTOCOL; } log_debug(domain,"circ deliver_window now %d.", layer_hint ? layer_hint->deliver_window : circ->deliver_window); circuit_consider_sending_sendme(circ, layer_hint); if (!conn) { log_info(domain,"data cell dropped, unknown stream (streamid %d).", rh.stream_id); return 0; } if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */ log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "(relay data) conn deliver_window below 0. Killing."); return -END_CIRC_REASON_TORPROTOCOL; } stats_n_data_bytes_received += rh.length; connection_write_to_buf((char*)(cell->payload + RELAY_HEADER_SIZE), rh.length, TO_CONN(conn)); if (!optimistic_data) { /* Only send a SENDME if we're not getting optimistic data; otherwise * a SENDME could arrive before the CONNECTED. */ connection_edge_consider_sending_sendme(conn); } return 0; case RELAY_COMMAND_END: reason = rh.length > 0 ? get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC; if (!conn) { log_info(domain,"end cell (%s) dropped, unknown stream.", stream_end_reason_to_string(reason)); return 0; } /* XXX add to this log_fn the exit node's nickname? */ log_info(domain,TOR_SOCKET_T_FORMAT": end cell (%s) for stream %d. " "Removing stream.", conn->base_.s, stream_end_reason_to_string(reason), conn->stream_id); if (conn->base_.type == CONN_TYPE_AP) { entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn); if (entry_conn->socks_request && !entry_conn->socks_request->has_finished) log_warn(LD_BUG, "open stream hasn't sent socks answer yet? Closing."); } /* We just *got* an end; no reason to send one. */ conn->edge_has_sent_end = 1; if (!conn->end_reason) conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE; if (!conn->base_.marked_for_close) { /* only mark it if not already marked. it's possible to * get the 'end' right around when the client hangs up on us. */ connection_mark_and_flush(TO_CONN(conn)); } return 0; case RELAY_COMMAND_EXTEND: case RELAY_COMMAND_EXTEND2: { static uint64_t total_n_extend=0, total_nonearly=0; total_n_extend++; if (rh.stream_id) { log_fn(LOG_PROTOCOL_WARN, domain, "'extend' cell received for non-zero stream. Dropping."); return 0; } if (cell->command != CELL_RELAY_EARLY && !networkstatus_get_param(NULL,"AllowNonearlyExtend",0,0,1)) { #define EARLY_WARNING_INTERVAL 3600 static ratelim_t early_warning_limit = RATELIM_INIT(EARLY_WARNING_INTERVAL); char *m; if (cell->command == CELL_RELAY) { ++total_nonearly; if ((m = rate_limit_log(&early_warning_limit, approx_time()))) { double percentage = ((double)total_nonearly)/total_n_extend; percentage *= 100; log_fn(LOG_PROTOCOL_WARN, domain, "EXTEND cell received, " "but not via RELAY_EARLY. Dropping.%s", m); log_fn(LOG_PROTOCOL_WARN, domain, " (We have dropped %.02f%% of " "all EXTEND cells for this reason)", percentage); tor_free(m); } } else { log_fn(LOG_WARN, domain, "EXTEND cell received, in a cell with type %d! Dropping.", cell->command); } return 0; } return circuit_extend(cell, circ); } case RELAY_COMMAND_EXTENDED: case RELAY_COMMAND_EXTENDED2: if (!layer_hint) { log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "'extended' unsupported at non-origin. Dropping."); return 0; } log_debug(domain,"Got an extended cell! Yay."); { extended_cell_t extended_cell; if (extended_cell_parse(&extended_cell, rh.command, (const uint8_t*)cell->payload+RELAY_HEADER_SIZE, rh.length)<0) { log_warn(LD_PROTOCOL, "Can't parse EXTENDED cell; killing circuit."); return -END_CIRC_REASON_TORPROTOCOL; } if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ), &extended_cell.created_cell)) < 0) { log_warn(domain,"circuit_finish_handshake failed."); return reason; } } if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) { log_info(domain,"circuit_send_next_onion_skin() failed."); return reason; } return 0; case RELAY_COMMAND_TRUNCATE: if (layer_hint) { log_fn(LOG_PROTOCOL_WARN, LD_APP, "'truncate' unsupported at origin. Dropping."); return 0; } if (circ->n_hop) { if (circ->n_chan) log_warn(LD_BUG, "n_chan and n_hop set on the same circuit!"); extend_info_free(circ->n_hop); circ->n_hop = NULL; tor_free(circ->n_chan_create_cell); circuit_set_state(circ, CIRCUIT_STATE_OPEN); } if (circ->n_chan) { uint8_t trunc_reason = get_uint8(cell->payload + RELAY_HEADER_SIZE); circuit_clear_cell_queue(circ, circ->n_chan); channel_send_destroy(circ->n_circ_id, circ->n_chan, trunc_reason); circuit_set_n_circid_chan(circ, 0, NULL); } log_debug(LD_EXIT, "Processed 'truncate', replying."); { char payload[1]; payload[0] = (char)END_CIRC_REASON_REQUESTED; relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED, payload, sizeof(payload), NULL); } return 0; case RELAY_COMMAND_TRUNCATED: if (!layer_hint) { log_fn(LOG_PROTOCOL_WARN, LD_EXIT, "'truncated' unsupported at non-origin. Dropping."); return 0; } circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint, get_uint8(cell->payload + RELAY_HEADER_SIZE)); return 0; case RELAY_COMMAND_CONNECTED: if (conn) { log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "'connected' unsupported while open. Closing circ."); return -END_CIRC_REASON_TORPROTOCOL; } log_info(domain, "'connected' received, no conn attached anymore. Ignoring."); return 0; case RELAY_COMMAND_SENDME: if (!rh.stream_id) { if (layer_hint) { if (layer_hint->package_window + CIRCWINDOW_INCREMENT > CIRCWINDOW_START_MAX) { log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Unexpected sendme cell from exit relay. " "Closing circ."); return -END_CIRC_REASON_TORPROTOCOL; } layer_hint->package_window += CIRCWINDOW_INCREMENT; log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.", layer_hint->package_window); circuit_resume_edge_reading(circ, layer_hint); } else { if (circ->package_window + CIRCWINDOW_INCREMENT > CIRCWINDOW_START_MAX) { log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Unexpected sendme cell from client. " "Closing circ (window %d).", circ->package_window); return -END_CIRC_REASON_TORPROTOCOL; } circ->package_window += CIRCWINDOW_INCREMENT; log_debug(LD_APP, "circ-level sendme at non-origin, packagewindow %d.", circ->package_window); circuit_resume_edge_reading(circ, layer_hint); } return 0; } if (!conn) { log_info(domain,"sendme cell dropped, unknown stream (streamid %d).", rh.stream_id); return 0; } conn->package_window += STREAMWINDOW_INCREMENT; log_debug(domain,"stream-level sendme, packagewindow now %d.", conn->package_window); if (circuit_queue_streams_are_blocked(circ)) { /* Still waiting for queue to flush; don't touch conn */ return 0; } connection_start_reading(TO_CONN(conn)); /* handle whatever might still be on the inbuf */ if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) { /* (We already sent an end cell if possible) */ connection_mark_for_close(TO_CONN(conn)); return 0; } return 0; case RELAY_COMMAND_RESOLVE: if (layer_hint) { log_fn(LOG_PROTOCOL_WARN, LD_APP, "resolve request unsupported at AP; dropping."); return 0; } else if (conn) { log_fn(LOG_PROTOCOL_WARN, domain, "resolve request for known stream; dropping."); return 0; } else if (circ->purpose != CIRCUIT_PURPOSE_OR) { log_fn(LOG_PROTOCOL_WARN, domain, "resolve request on circ with purpose %d; dropping", circ->purpose); return 0; } connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ)); return 0; case RELAY_COMMAND_RESOLVED: if (conn) { log_fn(LOG_PROTOCOL_WARN, domain, "'resolved' unsupported while open. Closing circ."); return -END_CIRC_REASON_TORPROTOCOL; } log_info(domain, "'resolved' received, no conn attached anymore. Ignoring."); return 0; case RELAY_COMMAND_ESTABLISH_INTRO: case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: case RELAY_COMMAND_INTRODUCE1: case RELAY_COMMAND_INTRODUCE2: case RELAY_COMMAND_INTRODUCE_ACK: case RELAY_COMMAND_RENDEZVOUS1: case RELAY_COMMAND_RENDEZVOUS2: case RELAY_COMMAND_INTRO_ESTABLISHED: case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED: rend_process_relay_cell(circ, layer_hint, rh.command, rh.length, cell->payload+RELAY_HEADER_SIZE); return 0; } log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Received unknown relay command %d. Perhaps the other side is using " "a newer version of Tor? Dropping.", rh.command); return 0; /* for forward compatibility, don't kill the circuit */ }
168,451
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void __nfs4_close(struct path *path, struct nfs4_state *state, mode_t mode, int wait) { struct nfs4_state_owner *owner = state->owner; int call_close = 0; int newstate; atomic_inc(&owner->so_count); /* Protect against nfs4_find_state() */ spin_lock(&owner->so_lock); switch (mode & (FMODE_READ | FMODE_WRITE)) { case FMODE_READ: state->n_rdonly--; break; case FMODE_WRITE: state->n_wronly--; break; case FMODE_READ|FMODE_WRITE: state->n_rdwr--; } newstate = FMODE_READ|FMODE_WRITE; if (state->n_rdwr == 0) { if (state->n_rdonly == 0) { newstate &= ~FMODE_READ; call_close |= test_bit(NFS_O_RDONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (state->n_wronly == 0) { newstate &= ~FMODE_WRITE; call_close |= test_bit(NFS_O_WRONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (newstate == 0) clear_bit(NFS_DELEGATED_STATE, &state->flags); } nfs4_state_set_mode_locked(state, newstate); spin_unlock(&owner->so_lock); if (!call_close) { nfs4_put_open_state(state); nfs4_put_state_owner(owner); } else nfs4_do_close(path, state, wait); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static void __nfs4_close(struct path *path, struct nfs4_state *state, mode_t mode, int wait) static void __nfs4_close(struct path *path, struct nfs4_state *state, fmode_t fmode, int wait) { struct nfs4_state_owner *owner = state->owner; int call_close = 0; fmode_t newstate; atomic_inc(&owner->so_count); /* Protect against nfs4_find_state() */ spin_lock(&owner->so_lock); switch (fmode & (FMODE_READ | FMODE_WRITE)) { case FMODE_READ: state->n_rdonly--; break; case FMODE_WRITE: state->n_wronly--; break; case FMODE_READ|FMODE_WRITE: state->n_rdwr--; } newstate = FMODE_READ|FMODE_WRITE; if (state->n_rdwr == 0) { if (state->n_rdonly == 0) { newstate &= ~FMODE_READ; call_close |= test_bit(NFS_O_RDONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (state->n_wronly == 0) { newstate &= ~FMODE_WRITE; call_close |= test_bit(NFS_O_WRONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (newstate == 0) clear_bit(NFS_DELEGATED_STATE, &state->flags); } nfs4_state_set_mode_locked(state, newstate); spin_unlock(&owner->so_lock); if (!call_close) { nfs4_put_open_state(state); nfs4_put_state_owner(owner); } else nfs4_do_close(path, state, wait); }
165,709
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PreconnectRequest::PreconnectRequest( const GURL& origin, int num_sockets, const net::NetworkIsolationKey& network_isolation_key) : origin(origin), num_sockets(num_sockets), network_isolation_key(network_isolation_key) { DCHECK_GE(num_sockets, 0); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
PreconnectRequest::PreconnectRequest( const url::Origin& origin, int num_sockets, const net::NetworkIsolationKey& network_isolation_key) : origin(origin), num_sockets(num_sockets), network_isolation_key(network_isolation_key) { DCHECK_GE(num_sockets, 0); }
172,381
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int atl2_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *netdev; struct atl2_adapter *adapter; static int cards_found; unsigned long mmio_start; int mmio_len; int err; cards_found = 0; err = pci_enable_device(pdev); if (err) return err; /* * atl2 is a shared-high-32-bit device, so we're stuck with 32-bit DMA * until the kernel has the proper infrastructure to support 64-bit DMA * on these devices. */ if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) && pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) { printk(KERN_ERR "atl2: No usable DMA configuration, aborting\n"); goto err_dma; } /* Mark all PCI regions associated with PCI device * pdev as being reserved by owner atl2_driver_name */ err = pci_request_regions(pdev, atl2_driver_name); if (err) goto err_pci_reg; /* Enables bus-mastering on the device and calls * pcibios_set_master to do the needed arch specific settings */ pci_set_master(pdev); err = -ENOMEM; netdev = alloc_etherdev(sizeof(struct atl2_adapter)); if (!netdev) goto err_alloc_etherdev; SET_NETDEV_DEV(netdev, &pdev->dev); pci_set_drvdata(pdev, netdev); adapter = netdev_priv(netdev); adapter->netdev = netdev; adapter->pdev = pdev; adapter->hw.back = adapter; mmio_start = pci_resource_start(pdev, 0x0); mmio_len = pci_resource_len(pdev, 0x0); adapter->hw.mem_rang = (u32)mmio_len; adapter->hw.hw_addr = ioremap(mmio_start, mmio_len); if (!adapter->hw.hw_addr) { err = -EIO; goto err_ioremap; } atl2_setup_pcicmd(pdev); netdev->netdev_ops = &atl2_netdev_ops; netdev->ethtool_ops = &atl2_ethtool_ops; netdev->watchdog_timeo = 5 * HZ; strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1); netdev->mem_start = mmio_start; netdev->mem_end = mmio_start + mmio_len; adapter->bd_number = cards_found; adapter->pci_using_64 = false; /* setup the private structure */ err = atl2_sw_init(adapter); if (err) goto err_sw_init; err = -EIO; netdev->hw_features = NETIF_F_SG | NETIF_F_HW_VLAN_CTAG_RX; netdev->features |= (NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX); /* Init PHY as early as possible due to power saving issue */ atl2_phy_init(&adapter->hw); /* reset the controller to * put the device in a known good starting state */ if (atl2_reset_hw(&adapter->hw)) { err = -EIO; goto err_reset; } /* copy the MAC address out of the EEPROM */ atl2_read_mac_addr(&adapter->hw); memcpy(netdev->dev_addr, adapter->hw.mac_addr, netdev->addr_len); if (!is_valid_ether_addr(netdev->dev_addr)) { err = -EIO; goto err_eeprom; } atl2_check_options(adapter); setup_timer(&adapter->watchdog_timer, atl2_watchdog, (unsigned long)adapter); setup_timer(&adapter->phy_config_timer, atl2_phy_config, (unsigned long)adapter); INIT_WORK(&adapter->reset_task, atl2_reset_task); INIT_WORK(&adapter->link_chg_task, atl2_link_chg_task); strcpy(netdev->name, "eth%d"); /* ?? */ err = register_netdev(netdev); if (err) goto err_register; /* assume we have no link for now */ netif_carrier_off(netdev); netif_stop_queue(netdev); cards_found++; return 0; err_reset: err_register: err_sw_init: err_eeprom: iounmap(adapter->hw.hw_addr); err_ioremap: free_netdev(netdev); err_alloc_etherdev: pci_release_regions(pdev); err_pci_reg: err_dma: pci_disable_device(pdev); return err; } Commit Message: atl2: Disable unimplemented scatter/gather feature atl2 includes NETIF_F_SG in hw_features even though it has no support for non-linear skbs. This bug was originally harmless since the driver does not claim to implement checksum offload and that used to be a requirement for SG. Now that SG and checksum offload are independent features, if you explicitly enable SG *and* use one of the rare protocols that can use SG without checkusm offload, this potentially leaks sensitive information (before you notice that it just isn't working). Therefore this obscure bug has been designated CVE-2016-2117. Reported-by: Justin Yackoski <[email protected]> Signed-off-by: Ben Hutchings <[email protected]> Fixes: ec5f06156423 ("net: Kill link between CSUM and SG features.") Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int atl2_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *netdev; struct atl2_adapter *adapter; static int cards_found; unsigned long mmio_start; int mmio_len; int err; cards_found = 0; err = pci_enable_device(pdev); if (err) return err; /* * atl2 is a shared-high-32-bit device, so we're stuck with 32-bit DMA * until the kernel has the proper infrastructure to support 64-bit DMA * on these devices. */ if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) && pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) { printk(KERN_ERR "atl2: No usable DMA configuration, aborting\n"); goto err_dma; } /* Mark all PCI regions associated with PCI device * pdev as being reserved by owner atl2_driver_name */ err = pci_request_regions(pdev, atl2_driver_name); if (err) goto err_pci_reg; /* Enables bus-mastering on the device and calls * pcibios_set_master to do the needed arch specific settings */ pci_set_master(pdev); err = -ENOMEM; netdev = alloc_etherdev(sizeof(struct atl2_adapter)); if (!netdev) goto err_alloc_etherdev; SET_NETDEV_DEV(netdev, &pdev->dev); pci_set_drvdata(pdev, netdev); adapter = netdev_priv(netdev); adapter->netdev = netdev; adapter->pdev = pdev; adapter->hw.back = adapter; mmio_start = pci_resource_start(pdev, 0x0); mmio_len = pci_resource_len(pdev, 0x0); adapter->hw.mem_rang = (u32)mmio_len; adapter->hw.hw_addr = ioremap(mmio_start, mmio_len); if (!adapter->hw.hw_addr) { err = -EIO; goto err_ioremap; } atl2_setup_pcicmd(pdev); netdev->netdev_ops = &atl2_netdev_ops; netdev->ethtool_ops = &atl2_ethtool_ops; netdev->watchdog_timeo = 5 * HZ; strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1); netdev->mem_start = mmio_start; netdev->mem_end = mmio_start + mmio_len; adapter->bd_number = cards_found; adapter->pci_using_64 = false; /* setup the private structure */ err = atl2_sw_init(adapter); if (err) goto err_sw_init; err = -EIO; netdev->hw_features = NETIF_F_HW_VLAN_CTAG_RX; netdev->features |= (NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX); /* Init PHY as early as possible due to power saving issue */ atl2_phy_init(&adapter->hw); /* reset the controller to * put the device in a known good starting state */ if (atl2_reset_hw(&adapter->hw)) { err = -EIO; goto err_reset; } /* copy the MAC address out of the EEPROM */ atl2_read_mac_addr(&adapter->hw); memcpy(netdev->dev_addr, adapter->hw.mac_addr, netdev->addr_len); if (!is_valid_ether_addr(netdev->dev_addr)) { err = -EIO; goto err_eeprom; } atl2_check_options(adapter); setup_timer(&adapter->watchdog_timer, atl2_watchdog, (unsigned long)adapter); setup_timer(&adapter->phy_config_timer, atl2_phy_config, (unsigned long)adapter); INIT_WORK(&adapter->reset_task, atl2_reset_task); INIT_WORK(&adapter->link_chg_task, atl2_link_chg_task); strcpy(netdev->name, "eth%d"); /* ?? */ err = register_netdev(netdev); if (err) goto err_register; /* assume we have no link for now */ netif_carrier_off(netdev); netif_stop_queue(netdev); cards_found++; return 0; err_reset: err_register: err_sw_init: err_eeprom: iounmap(adapter->hw.hw_addr); err_ioremap: free_netdev(netdev); err_alloc_etherdev: pci_release_regions(pdev); err_pci_reg: err_dma: pci_disable_device(pdev); return err; }
167,436
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MediaControlsProgressView::HandleSeeking( const gfx::Point& location_in_bar) { double seek_to_progress = static_cast<double>(location_in_bar.x()) / progress_bar_->width(); seek_callback_.Run(seek_to_progress); } Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks This CL rearranges the different components of the CrOS lock screen media controls based on the newest mocks. This involves resizing most of the child views and their spacings. The artwork was also resized and re-positioned. Additionally, the close button was moved from the main view to the header row child view. Artist and title data about the current session will eventually be placed to the right of the artwork, but right now this space is empty. See the bug for before and after pictures. Bug: 991647 Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554 Reviewed-by: Xiyuan Xia <[email protected]> Reviewed-by: Becca Hughes <[email protected]> Commit-Queue: Mia Bergeron <[email protected]> Cr-Commit-Position: refs/heads/master@{#686253} CWE ID: CWE-200
void MediaControlsProgressView::HandleSeeking( void MediaControlsProgressView::HandleSeeking(const gfx::Point& location) { gfx::Point location_in_bar(location); ConvertPointToTarget(this, progress_bar_, &location_in_bar); double seek_to_progress = static_cast<double>(location_in_bar.x()) / progress_bar_->width(); seek_callback_.Run(seek_to_progress); }
172,345
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void runTest() { if (m_settings.enableCompositorThread) CCLayerTreeHostTest::runTest(); } Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests https://bugs.webkit.org/show_bug.cgi?id=70161 Reviewed by David Levin. Source/WebCore: Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was destroyed. This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the CCThreadProxy have been drained. Covered by the now-enabled CCLayerTreeHostTest* unit tests. * WebCore.gypi: * platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added. (WebCore::CCScopedMainThreadProxy::create): (WebCore::CCScopedMainThreadProxy::postTask): (WebCore::CCScopedMainThreadProxy::shutdown): (WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy): (WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown): * platform/graphics/chromium/cc/CCThreadProxy.cpp: (WebCore::CCThreadProxy::CCThreadProxy): (WebCore::CCThreadProxy::~CCThreadProxy): (WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread): * platform/graphics/chromium/cc/CCThreadProxy.h: Source/WebKit/chromium: Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor thread scheduling draws by itself. * tests/CCLayerTreeHostTest.cpp: (::CCLayerTreeHostTest::timeout): (::CCLayerTreeHostTest::clearTimeout): (::CCLayerTreeHostTest::CCLayerTreeHostTest): (::CCLayerTreeHostTest::onEndTest): (::CCLayerTreeHostTest::TimeoutTask::TimeoutTask): (::CCLayerTreeHostTest::TimeoutTask::clearTest): (::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask): (::CCLayerTreeHostTest::TimeoutTask::Run): (::CCLayerTreeHostTest::runTest): (::CCLayerTreeHostTest::doBeginTest): (::CCLayerTreeHostTestThreadOnly::runTest): (::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread): git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
virtual void runTest() void runTest() { CCLayerTreeHostTest::runTest(true); }
170,296
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info) { union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header; char line[TOSHIBA_LINE_LENGTH]; int num_items_scanned; guint pkt_len; int pktnum, hr, min, sec, csec; char channel[10], direction[10]; int i, hex_lines; guint8 *pd; /* Our file pointer should be on the line containing the * summary information for a packet. Read in that line and * extract the useful information */ if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } /* Find text in line after "[No.". Limit the length of the * two strings since we have fixed buffers for channel[] and * direction[] */ num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s", &pktnum, &hr, &min, &sec, &csec, channel, direction); if (num_items_scanned != 7) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("toshiba: record header isn't valid"); return FALSE; } /* Scan lines until we find the OFFSET line. In a "telnet" trace, * this will be the next line. But if you save your telnet session * to a file from within a Windows-based telnet client, it may * put in line breaks at 80 columns (or however big your "telnet" box * is). CRT (a Windows telnet app from VanDyke) does this. * Here we assume that 80 columns will be the minimum size, and that * the OFFSET line is not broken in the middle. It's the previous * line that is normally long and can thus be broken at column 80. */ do { if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } /* Check for "OFFSET 0001-0203" at beginning of line */ line[16] = '\0'; } while (strcmp(line, "OFFSET 0001-0203") != 0); num_items_scanned = sscanf(line+64, "LEN=%9u", &pkt_len); if (num_items_scanned != 1) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item"); return FALSE; } if (pkt_len > WTAP_MAX_PACKET_SIZE) { /* * Probably a corrupt capture file; don't blow up trying * to allocate space for an immensely-large packet. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("toshiba: File has %u-byte packet, bigger than maximum of %u", pkt_len, WTAP_MAX_PACKET_SIZE); return FALSE; } phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; phdr->ts.secs = hr * 3600 + min * 60 + sec; phdr->ts.nsecs = csec * 10000000; phdr->caplen = pkt_len; phdr->len = pkt_len; switch (channel[0]) { case 'B': phdr->pkt_encap = WTAP_ENCAP_ISDN; pseudo_header->isdn.uton = (direction[0] == 'T'); pseudo_header->isdn.channel = (guint8) strtol(&channel[1], NULL, 10); break; case 'D': phdr->pkt_encap = WTAP_ENCAP_ISDN; pseudo_header->isdn.uton = (direction[0] == 'T'); pseudo_header->isdn.channel = 0; break; default: phdr->pkt_encap = WTAP_ENCAP_ETHERNET; /* XXX - is there an FCS in the frame? */ pseudo_header->eth.fcs_len = -1; break; } /* Make sure we have enough room for the packet */ ws_buffer_assure_space(buf, pkt_len); pd = ws_buffer_start_ptr(buf); /* Calculate the number of hex dump lines, each * containing 16 bytes of data */ hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0); for (i = 0; i < hex_lines; i++) { if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } if (!parse_single_hex_dump_line(line, pd, i * 16)) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("toshiba: hex dump not valid"); return FALSE; } } return TRUE; } Commit Message: Don't treat the packet length as unsigned. The scanf family of functions are as annoyingly bad at handling unsigned numbers as strtoul() is - both of them are perfectly willing to accept a value beginning with a negative sign as an unsigned value. When using strtoul(), you can compensate for this by explicitly checking for a '-' as the first character of the string, but you can't do that with sscanf(). So revert to having pkt_len be signed, and scanning it with %d, but check for a negative value and fail if we see a negative value. Bug: 12394 Change-Id: I4b19b95f2e1ffc96dac5c91bff6698c246f52007 Reviewed-on: https://code.wireshark.org/review/15230 Reviewed-by: Guy Harris <[email protected]> CWE ID: CWE-20
parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info) { union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header; char line[TOSHIBA_LINE_LENGTH]; int num_items_scanned; int pkt_len, pktnum, hr, min, sec, csec; char channel[10], direction[10]; int i, hex_lines; guint8 *pd; /* Our file pointer should be on the line containing the * summary information for a packet. Read in that line and * extract the useful information */ if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } /* Find text in line after "[No.". Limit the length of the * two strings since we have fixed buffers for channel[] and * direction[] */ num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s", &pktnum, &hr, &min, &sec, &csec, channel, direction); if (num_items_scanned != 7) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("toshiba: record header isn't valid"); return FALSE; } /* Scan lines until we find the OFFSET line. In a "telnet" trace, * this will be the next line. But if you save your telnet session * to a file from within a Windows-based telnet client, it may * put in line breaks at 80 columns (or however big your "telnet" box * is). CRT (a Windows telnet app from VanDyke) does this. * Here we assume that 80 columns will be the minimum size, and that * the OFFSET line is not broken in the middle. It's the previous * line that is normally long and can thus be broken at column 80. */ do { if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } /* Check for "OFFSET 0001-0203" at beginning of line */ line[16] = '\0'; } while (strcmp(line, "OFFSET 0001-0203") != 0); num_items_scanned = sscanf(line+64, "LEN=%9d", &pkt_len); if (num_items_scanned != 1) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item"); return FALSE; } if (pkt_len < 0) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("toshiba: packet header has a negative packet length"); return FALSE; } if (pkt_len > WTAP_MAX_PACKET_SIZE) { /* * Probably a corrupt capture file; don't blow up trying * to allocate space for an immensely-large packet. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("toshiba: File has %u-byte packet, bigger than maximum of %u", pkt_len, WTAP_MAX_PACKET_SIZE); return FALSE; } phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; phdr->ts.secs = hr * 3600 + min * 60 + sec; phdr->ts.nsecs = csec * 10000000; phdr->caplen = pkt_len; phdr->len = pkt_len; switch (channel[0]) { case 'B': phdr->pkt_encap = WTAP_ENCAP_ISDN; pseudo_header->isdn.uton = (direction[0] == 'T'); pseudo_header->isdn.channel = (guint8) strtol(&channel[1], NULL, 10); break; case 'D': phdr->pkt_encap = WTAP_ENCAP_ISDN; pseudo_header->isdn.uton = (direction[0] == 'T'); pseudo_header->isdn.channel = 0; break; default: phdr->pkt_encap = WTAP_ENCAP_ETHERNET; /* XXX - is there an FCS in the frame? */ pseudo_header->eth.fcs_len = -1; break; } /* Make sure we have enough room for the packet */ ws_buffer_assure_space(buf, pkt_len); pd = ws_buffer_start_ptr(buf); /* Calculate the number of hex dump lines, each * containing 16 bytes of data */ hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0); for (i = 0; i < hex_lines; i++) { if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } if (!parse_single_hex_dump_line(line, pd, i * 16)) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("toshiba: hex dump not valid"); return FALSE; } } return TRUE; }
167,151
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HeapObjectHeader::zapMagic() { ASSERT(checkHeader()); m_magic = zappedMagic; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
void HeapObjectHeader::zapMagic() { checkHeader(); m_magic = zappedMagic; }
172,716
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int br_parse_ip_options(struct sk_buff *skb) { struct ip_options *opt; struct iphdr *iph; struct net_device *dev = skb->dev; u32 len; iph = ip_hdr(skb); opt = &(IPCB(skb)->opt); /* Basic sanity checks */ if (iph->ihl < 5 || iph->version != 4) goto inhdr_error; if (!pskb_may_pull(skb, iph->ihl*4)) goto inhdr_error; iph = ip_hdr(skb); if (unlikely(ip_fast_csum((u8 *)iph, iph->ihl))) goto inhdr_error; len = ntohs(iph->tot_len); if (skb->len < len) { IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INTRUNCATEDPKTS); goto drop; } else if (len < (iph->ihl*4)) goto inhdr_error; if (pskb_trim_rcsum(skb, len)) { IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INDISCARDS); goto drop; } /* Zero out the CB buffer if no options present */ if (iph->ihl == 5) { memset(IPCB(skb), 0, sizeof(struct inet_skb_parm)); return 0; } opt->optlen = iph->ihl*4 - sizeof(struct iphdr); if (ip_options_compile(dev_net(dev), opt, skb)) goto inhdr_error; /* Check correct handling of SRR option */ if (unlikely(opt->srr)) { struct in_device *in_dev = __in_dev_get_rcu(dev); if (in_dev && !IN_DEV_SOURCE_ROUTE(in_dev)) goto drop; if (ip_options_rcv_srr(skb)) goto drop; } return 0; inhdr_error: IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INHDRERRORS); drop: return -1; } Commit Message: bridge: reset IPCB in br_parse_ip_options Commit 462fb2af9788a82 (bridge : Sanitize skb before it enters the IP stack), missed one IPCB init before calling ip_options_compile() Thanks to Scot Doyle for his tests and bug reports. Reported-by: Scot Doyle <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Cc: Hiroaki SHIMODA <[email protected]> Acked-by: Bandan Das <[email protected]> Acked-by: Stephen Hemminger <[email protected]> Cc: Jan Lübbe <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
static int br_parse_ip_options(struct sk_buff *skb) { struct ip_options *opt; struct iphdr *iph; struct net_device *dev = skb->dev; u32 len; iph = ip_hdr(skb); opt = &(IPCB(skb)->opt); /* Basic sanity checks */ if (iph->ihl < 5 || iph->version != 4) goto inhdr_error; if (!pskb_may_pull(skb, iph->ihl*4)) goto inhdr_error; iph = ip_hdr(skb); if (unlikely(ip_fast_csum((u8 *)iph, iph->ihl))) goto inhdr_error; len = ntohs(iph->tot_len); if (skb->len < len) { IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INTRUNCATEDPKTS); goto drop; } else if (len < (iph->ihl*4)) goto inhdr_error; if (pskb_trim_rcsum(skb, len)) { IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INDISCARDS); goto drop; } memset(IPCB(skb), 0, sizeof(struct inet_skb_parm)); if (iph->ihl == 5) return 0; opt->optlen = iph->ihl*4 - sizeof(struct iphdr); if (ip_options_compile(dev_net(dev), opt, skb)) goto inhdr_error; /* Check correct handling of SRR option */ if (unlikely(opt->srr)) { struct in_device *in_dev = __in_dev_get_rcu(dev); if (in_dev && !IN_DEV_SOURCE_ROUTE(in_dev)) goto drop; if (ip_options_rcv_srr(skb)) goto drop; } return 0; inhdr_error: IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INHDRERRORS); drop: return -1; }
166,216
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothDeviceChromeOS::OnPairError( const ConnectErrorCallback& error_callback, const std::string& error_name, const std::string& error_message) { if (--num_connecting_calls_ == 0) adapter_->NotifyDeviceChanged(this); DCHECK(num_connecting_calls_ >= 0); LOG(WARNING) << object_path_.value() << ": Failed to pair device: " << error_name << ": " << error_message; VLOG(1) << object_path_.value() << ": " << num_connecting_calls_ << " still in progress"; UnregisterAgent(); ConnectErrorCode error_code = ERROR_UNKNOWN; if (error_name == bluetooth_device::kErrorConnectionAttemptFailed) { error_code = ERROR_FAILED; } else if (error_name == bluetooth_device::kErrorFailed) { error_code = ERROR_FAILED; } else if (error_name == bluetooth_device::kErrorAuthenticationFailed) { error_code = ERROR_AUTH_FAILED; } else if (error_name == bluetooth_device::kErrorAuthenticationCanceled) { error_code = ERROR_AUTH_CANCELED; } else if (error_name == bluetooth_device::kErrorAuthenticationRejected) { error_code = ERROR_AUTH_REJECTED; } else if (error_name == bluetooth_device::kErrorAuthenticationTimeout) { error_code = ERROR_AUTH_TIMEOUT; } RecordPairingResult(error_code); error_callback.Run(error_code); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::OnPairError( const ConnectErrorCallback& error_callback, const std::string& error_name, const std::string& error_message) { if (--num_connecting_calls_ == 0) adapter_->NotifyDeviceChanged(this); DCHECK(num_connecting_calls_ >= 0); LOG(WARNING) << object_path_.value() << ": Failed to pair device: " << error_name << ": " << error_message; VLOG(1) << object_path_.value() << ": " << num_connecting_calls_ << " still in progress"; pairing_context_.reset(); ConnectErrorCode error_code = ERROR_UNKNOWN; if (error_name == bluetooth_device::kErrorConnectionAttemptFailed) { error_code = ERROR_FAILED; } else if (error_name == bluetooth_device::kErrorFailed) { error_code = ERROR_FAILED; } else if (error_name == bluetooth_device::kErrorAuthenticationFailed) { error_code = ERROR_AUTH_FAILED; } else if (error_name == bluetooth_device::kErrorAuthenticationCanceled) { error_code = ERROR_AUTH_CANCELED; } else if (error_name == bluetooth_device::kErrorAuthenticationRejected) { error_code = ERROR_AUTH_REJECTED; } else if (error_name == bluetooth_device::kErrorAuthenticationTimeout) { error_code = ERROR_AUTH_TIMEOUT; } RecordPairingResult(error_code); error_callback.Run(error_code); }
171,228
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void *_zend_shared_memdup(void *source, size_t size, zend_bool free_source) { void *old_p, *retval; if ((old_p = zend_hash_index_find_ptr(&xlat_table, (zend_ulong)source)) != NULL) { /* we already duplicated this pointer */ return old_p; } retval = ZCG(mem); ZCG(mem) = (void*)(((char*)ZCG(mem)) + ZEND_ALIGNED_SIZE(size)); memcpy(retval, source, size); if (free_source) { efree(source); } zend_shared_alloc_register_xlat_entry(source, retval); return retval; } Commit Message: CWE ID: CWE-416
void *_zend_shared_memdup(void *source, size_t size, zend_bool free_source) { void *old_p, *retval; if ((old_p = zend_hash_index_find_ptr(&xlat_table, (zend_ulong)source)) != NULL) { /* we already duplicated this pointer */ return old_p; } retval = ZCG(mem); ZCG(mem) = (void*)(((char*)ZCG(mem)) + ZEND_ALIGNED_SIZE(size)); memcpy(retval, source, size); zend_shared_alloc_register_xlat_entry(source, retval); if (free_source) { efree(source); } return retval; }
164,770
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static UINT32 nsc_rle_encode(BYTE* in, BYTE* out, UINT32 originalSize) { UINT32 left; UINT32 runlength = 1; UINT32 planeSize = 0; left = originalSize; /** * We quit the loop if the running compressed size is larger than the original. * In such cases data will be sent uncompressed. */ while (left > 4 && planeSize < originalSize - 4) { if (left > 5 && *in == *(in + 1)) { runlength++; } else if (runlength == 1) { *out++ = *in; planeSize++; } else if (runlength < 256) { *out++ = *in; *out++ = *in; *out++ = runlength - 2; runlength = 1; planeSize += 3; } else { *out++ = *in; *out++ = *in; *out++ = 0xFF; *out++ = (runlength & 0x000000FF); *out++ = (runlength & 0x0000FF00) >> 8; *out++ = (runlength & 0x00FF0000) >> 16; *out++ = (runlength & 0xFF000000) >> 24; runlength = 1; planeSize += 7; } in++; left--; } if (planeSize < originalSize - 4) CopyMemory(out, in, 4); planeSize += 4; return planeSize; } Commit Message: Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-787
static UINT32 nsc_rle_encode(BYTE* in, BYTE* out, UINT32 originalSize) static UINT32 nsc_rle_encode(const BYTE* in, BYTE* out, UINT32 originalSize) { UINT32 left; UINT32 runlength = 1; UINT32 planeSize = 0; left = originalSize; /** * We quit the loop if the running compressed size is larger than the original. * In such cases data will be sent uncompressed. */ while (left > 4 && planeSize < originalSize - 4) { if (left > 5 && *in == *(in + 1)) { runlength++; } else if (runlength == 1) { *out++ = *in; planeSize++; } else if (runlength < 256) { *out++ = *in; *out++ = *in; *out++ = runlength - 2; runlength = 1; planeSize += 3; } else { *out++ = *in; *out++ = *in; *out++ = 0xFF; *out++ = (runlength & 0x000000FF); *out++ = (runlength & 0x0000FF00) >> 8; *out++ = (runlength & 0x00FF0000) >> 16; *out++ = (runlength & 0xFF000000) >> 24; runlength = 1; planeSize += 7; } in++; left--; } if (planeSize < originalSize - 4) CopyMemory(out, in, 4); planeSize += 4; return planeSize; }
169,290
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void set_roi_map(const vpx_codec_enc_cfg_t *cfg, vpx_codec_ctx_t *codec) { unsigned int i; vpx_roi_map_t roi = {0}; roi.rows = (cfg->g_h + 15) / 16; roi.cols = (cfg->g_w + 15) / 16; roi.delta_q[0] = 0; roi.delta_q[1] = -2; roi.delta_q[2] = -4; roi.delta_q[3] = -6; roi.delta_lf[0] = 0; roi.delta_lf[1] = 1; roi.delta_lf[2] = 2; roi.delta_lf[3] = 3; roi.static_threshold[0] = 1500; roi.static_threshold[1] = 1000; roi.static_threshold[2] = 500; roi.static_threshold[3] = 0; roi.roi_map = (uint8_t *)malloc(roi.rows * roi.cols); for (i = 0; i < roi.rows * roi.cols; ++i) roi.roi_map[i] = i % 4; if (vpx_codec_control(codec, VP8E_SET_ROI_MAP, &roi)) die_codec(codec, "Failed to set ROI map"); free(roi.roi_map); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static void set_roi_map(const vpx_codec_enc_cfg_t *cfg, vpx_codec_ctx_t *codec) { unsigned int i; vpx_roi_map_t roi; memset(&roi, 0, sizeof(roi)); roi.rows = (cfg->g_h + 15) / 16; roi.cols = (cfg->g_w + 15) / 16; roi.delta_q[0] = 0; roi.delta_q[1] = -2; roi.delta_q[2] = -4; roi.delta_q[3] = -6; roi.delta_lf[0] = 0; roi.delta_lf[1] = 1; roi.delta_lf[2] = 2; roi.delta_lf[3] = 3; roi.static_threshold[0] = 1500; roi.static_threshold[1] = 1000; roi.static_threshold[2] = 500; roi.static_threshold[3] = 0; roi.roi_map = (uint8_t *)malloc(roi.rows * roi.cols); for (i = 0; i < roi.rows * roi.cols; ++i) roi.roi_map[i] = i % 4; if (vpx_codec_control(codec, VP8E_SET_ROI_MAP, &roi)) die_codec(codec, "Failed to set ROI map"); free(roi.roi_map); }
174,484
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: vsock_stream_recvmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk; struct vsock_sock *vsk; int err; size_t target; ssize_t copied; long timeout; struct vsock_transport_recv_notify_data recv_data; DEFINE_WAIT(wait); sk = sock->sk; vsk = vsock_sk(sk); err = 0; lock_sock(sk); if (sk->sk_state != SS_CONNECTED) { /* Recvmsg is supposed to return 0 if a peer performs an * orderly shutdown. Differentiate between that case and when a * peer has not connected or a local shutdown occured with the * SOCK_DONE flag. */ if (sock_flag(sk, SOCK_DONE)) err = 0; else err = -ENOTCONN; goto out; } if (flags & MSG_OOB) { err = -EOPNOTSUPP; goto out; } /* We don't check peer_shutdown flag here since peer may actually shut * down, but there can be data in the queue that a local socket can * receive. */ if (sk->sk_shutdown & RCV_SHUTDOWN) { err = 0; goto out; } /* It is valid on Linux to pass in a zero-length receive buffer. This * is not an error. We may as well bail out now. */ if (!len) { err = 0; goto out; } /* We must not copy less than target bytes into the user's buffer * before returning successfully, so we wait for the consume queue to * have that much data to consume before dequeueing. Note that this * makes it impossible to handle cases where target is greater than the * queue size. */ target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); if (target >= transport->stream_rcvhiwat(vsk)) { err = -ENOMEM; goto out; } timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); copied = 0; err = transport->notify_recv_init(vsk, target, &recv_data); if (err < 0) goto out; prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); while (1) { s64 ready = vsock_stream_has_data(vsk); if (ready < 0) { /* Invalid queue pair content. XXX This should be * changed to a connection reset in a later change. */ err = -ENOMEM; goto out_wait; } else if (ready > 0) { ssize_t read; err = transport->notify_recv_pre_dequeue( vsk, target, &recv_data); if (err < 0) break; read = transport->stream_dequeue( vsk, msg->msg_iov, len - copied, flags); if (read < 0) { err = -ENOMEM; break; } copied += read; err = transport->notify_recv_post_dequeue( vsk, target, read, !(flags & MSG_PEEK), &recv_data); if (err < 0) goto out_wait; if (read >= target || flags & MSG_PEEK) break; target -= read; } else { if (sk->sk_err != 0 || (sk->sk_shutdown & RCV_SHUTDOWN) || (vsk->peer_shutdown & SEND_SHUTDOWN)) { break; } /* Don't wait for non-blocking sockets. */ if (timeout == 0) { err = -EAGAIN; break; } err = transport->notify_recv_pre_block( vsk, target, &recv_data); if (err < 0) break; release_sock(sk); timeout = schedule_timeout(timeout); lock_sock(sk); if (signal_pending(current)) { err = sock_intr_errno(timeout); break; } else if (timeout == 0) { err = -EAGAIN; break; } prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); } } if (sk->sk_err) err = -sk->sk_err; else if (sk->sk_shutdown & RCV_SHUTDOWN) err = 0; if (copied > 0) { /* We only do these additional bookkeeping/notification steps * if we actually copied something out of the queue pair * instead of just peeking ahead. */ if (!(flags & MSG_PEEK)) { /* If the other side has shutdown for sending and there * is nothing more to read, then modify the socket * state. */ if (vsk->peer_shutdown & SEND_SHUTDOWN) { if (vsock_stream_has_data(vsk) <= 0) { sk->sk_state = SS_UNCONNECTED; sock_set_flag(sk, SOCK_DONE); sk->sk_state_change(sk); } } } err = copied; } out_wait: finish_wait(sk_sleep(sk), &wait); out: release_sock(sk); return err; } Commit Message: VSOCK: Fix missing msg_namelen update in vsock_stream_recvmsg() The code misses to update the msg_namelen member to 0 and therefore makes net/socket.c leak the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Cc: Andy King <[email protected]> Cc: Dmitry Torokhov <[email protected]> Cc: George Zhang <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
vsock_stream_recvmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk; struct vsock_sock *vsk; int err; size_t target; ssize_t copied; long timeout; struct vsock_transport_recv_notify_data recv_data; DEFINE_WAIT(wait); sk = sock->sk; vsk = vsock_sk(sk); err = 0; msg->msg_namelen = 0; lock_sock(sk); if (sk->sk_state != SS_CONNECTED) { /* Recvmsg is supposed to return 0 if a peer performs an * orderly shutdown. Differentiate between that case and when a * peer has not connected or a local shutdown occured with the * SOCK_DONE flag. */ if (sock_flag(sk, SOCK_DONE)) err = 0; else err = -ENOTCONN; goto out; } if (flags & MSG_OOB) { err = -EOPNOTSUPP; goto out; } /* We don't check peer_shutdown flag here since peer may actually shut * down, but there can be data in the queue that a local socket can * receive. */ if (sk->sk_shutdown & RCV_SHUTDOWN) { err = 0; goto out; } /* It is valid on Linux to pass in a zero-length receive buffer. This * is not an error. We may as well bail out now. */ if (!len) { err = 0; goto out; } /* We must not copy less than target bytes into the user's buffer * before returning successfully, so we wait for the consume queue to * have that much data to consume before dequeueing. Note that this * makes it impossible to handle cases where target is greater than the * queue size. */ target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); if (target >= transport->stream_rcvhiwat(vsk)) { err = -ENOMEM; goto out; } timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); copied = 0; err = transport->notify_recv_init(vsk, target, &recv_data); if (err < 0) goto out; prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); while (1) { s64 ready = vsock_stream_has_data(vsk); if (ready < 0) { /* Invalid queue pair content. XXX This should be * changed to a connection reset in a later change. */ err = -ENOMEM; goto out_wait; } else if (ready > 0) { ssize_t read; err = transport->notify_recv_pre_dequeue( vsk, target, &recv_data); if (err < 0) break; read = transport->stream_dequeue( vsk, msg->msg_iov, len - copied, flags); if (read < 0) { err = -ENOMEM; break; } copied += read; err = transport->notify_recv_post_dequeue( vsk, target, read, !(flags & MSG_PEEK), &recv_data); if (err < 0) goto out_wait; if (read >= target || flags & MSG_PEEK) break; target -= read; } else { if (sk->sk_err != 0 || (sk->sk_shutdown & RCV_SHUTDOWN) || (vsk->peer_shutdown & SEND_SHUTDOWN)) { break; } /* Don't wait for non-blocking sockets. */ if (timeout == 0) { err = -EAGAIN; break; } err = transport->notify_recv_pre_block( vsk, target, &recv_data); if (err < 0) break; release_sock(sk); timeout = schedule_timeout(timeout); lock_sock(sk); if (signal_pending(current)) { err = sock_intr_errno(timeout); break; } else if (timeout == 0) { err = -EAGAIN; break; } prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); } } if (sk->sk_err) err = -sk->sk_err; else if (sk->sk_shutdown & RCV_SHUTDOWN) err = 0; if (copied > 0) { /* We only do these additional bookkeeping/notification steps * if we actually copied something out of the queue pair * instead of just peeking ahead. */ if (!(flags & MSG_PEEK)) { /* If the other side has shutdown for sending and there * is nothing more to read, then modify the socket * state. */ if (vsk->peer_shutdown & SEND_SHUTDOWN) { if (vsock_stream_has_data(vsk) <= 0) { sk->sk_state = SS_UNCONNECTED; sock_set_flag(sk, SOCK_DONE); sk->sk_state_change(sk); } } } err = copied; } out_wait: finish_wait(sk_sleep(sk), &wait); out: release_sock(sk); return err; }
166,028
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: dump_keywords(vector_t *keydump, int level, FILE *fp) { unsigned int i; keyword_t *keyword_vec; char file_name[21]; if (!level) { snprintf(file_name, sizeof(file_name), "/tmp/keywords.%d", getpid()); fp = fopen(file_name, "w"); if (!fp) return; } for (i = 0; i < vector_size(keydump); i++) { keyword_vec = vector_slot(keydump, i); fprintf(fp, "%*sKeyword : %s (%s)\n", level * 2, "", keyword_vec->string, keyword_vec->active ? "active": "disabled"); if (keyword_vec->sub) dump_keywords(keyword_vec->sub, level + 1, fp); } if (!level) fclose(fp); } Commit Message: When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-59
dump_keywords(vector_t *keydump, int level, FILE *fp) { unsigned int i; keyword_t *keyword_vec; char file_name[22]; if (!level) { snprintf(file_name, sizeof(file_name), "/tmp/keywords.%d", getpid()); fp = fopen_safe(file_name, "w"); if (!fp) return; } for (i = 0; i < vector_size(keydump); i++) { keyword_vec = vector_slot(keydump, i); fprintf(fp, "%*sKeyword : %s (%s)\n", level * 2, "", keyword_vec->string, keyword_vec->active ? "active": "disabled"); if (keyword_vec->sub) dump_keywords(keyword_vec->sub, level + 1, fp); } if (!level) fclose(fp); }
168,997
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int test(char *URL) { int errors = 0; (void)URL; /* not used */ errors += test_weird_arguments(); errors += test_unsigned_short_formatting(); errors += test_signed_short_formatting(); errors += test_unsigned_int_formatting(); errors += test_signed_int_formatting(); errors += test_unsigned_long_formatting(); errors += test_signed_long_formatting(); errors += test_curl_off_t_formatting(); errors += test_string_formatting(); if(errors) return TEST_ERR_MAJOR_BAD; else return 0; } Commit Message: printf: fix floating point buffer overflow issues ... and add a bunch of floating point printf tests CWE ID: CWE-119
int test(char *URL) { int errors = 0; (void)URL; /* not used */ errors += test_weird_arguments(); errors += test_unsigned_short_formatting(); errors += test_signed_short_formatting(); errors += test_unsigned_int_formatting(); errors += test_signed_int_formatting(); errors += test_unsigned_long_formatting(); errors += test_signed_long_formatting(); errors += test_curl_off_t_formatting(); errors += test_string_formatting(); errors += test_float_formatting(); if(errors) return TEST_ERR_MAJOR_BAD; else return 0; }
169,438
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int netlink_dump(struct sock *sk) { struct netlink_sock *nlk = nlk_sk(sk); struct netlink_callback *cb; struct sk_buff *skb = NULL; struct nlmsghdr *nlh; int len, err = -ENOBUFS; int alloc_min_size; int alloc_size; mutex_lock(nlk->cb_mutex); if (!nlk->cb_running) { err = -EINVAL; goto errout_skb; } if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) goto errout_skb; /* NLMSG_GOODSIZE is small to avoid high order allocations being * required, but it makes sense to _attempt_ a 16K bytes allocation * to reduce number of system calls on dump operations, if user * ever provided a big enough buffer. */ cb = &nlk->cb; alloc_min_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE); if (alloc_min_size < nlk->max_recvmsg_len) { alloc_size = nlk->max_recvmsg_len; skb = alloc_skb(alloc_size, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY); } if (!skb) { alloc_size = alloc_min_size; skb = alloc_skb(alloc_size, GFP_KERNEL); } if (!skb) goto errout_skb; /* Trim skb to allocated size. User is expected to provide buffer as * large as max(min_dump_alloc, 16KiB (mac_recvmsg_len capped at * netlink_recvmsg())). dump will pack as many smaller messages as * could fit within the allocated skb. skb is typically allocated * with larger space than required (could be as much as near 2x the * requested size with align to next power of 2 approach). Allowing * dump to use the excess space makes it difficult for a user to have a * reasonable static buffer based on the expected largest dump of a * single netdev. The outcome is MSG_TRUNC error. */ skb_reserve(skb, skb_tailroom(skb) - alloc_size); netlink_skb_set_owner_r(skb, sk); len = cb->dump(skb, cb); if (len > 0) { mutex_unlock(nlk->cb_mutex); if (sk_filter(sk, skb)) kfree_skb(skb); else __netlink_sendskb(sk, skb); return 0; } nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE, sizeof(len), NLM_F_MULTI); if (!nlh) goto errout_skb; nl_dump_check_consistent(cb, nlh); memcpy(nlmsg_data(nlh), &len, sizeof(len)); if (sk_filter(sk, skb)) kfree_skb(skb); else __netlink_sendskb(sk, skb); if (cb->done) cb->done(cb); nlk->cb_running = false; mutex_unlock(nlk->cb_mutex); module_put(cb->module); consume_skb(cb->skb); return 0; errout_skb: mutex_unlock(nlk->cb_mutex); kfree_skb(skb); return err; } Commit Message: netlink: Fix dump skb leak/double free When we free cb->skb after a dump, we do it after releasing the lock. This means that a new dump could have started in the time being and we'll end up freeing their skb instead of ours. This patch saves the skb and module before we unlock so we free the right memory. Fixes: 16b304f3404f ("netlink: Eliminate kmalloc in netlink dump operation.") Reported-by: Baozeng Ding <[email protected]> Signed-off-by: Herbert Xu <[email protected]> Acked-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-415
static int netlink_dump(struct sock *sk) { struct netlink_sock *nlk = nlk_sk(sk); struct netlink_callback *cb; struct sk_buff *skb = NULL; struct nlmsghdr *nlh; struct module *module; int len, err = -ENOBUFS; int alloc_min_size; int alloc_size; mutex_lock(nlk->cb_mutex); if (!nlk->cb_running) { err = -EINVAL; goto errout_skb; } if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) goto errout_skb; /* NLMSG_GOODSIZE is small to avoid high order allocations being * required, but it makes sense to _attempt_ a 16K bytes allocation * to reduce number of system calls on dump operations, if user * ever provided a big enough buffer. */ cb = &nlk->cb; alloc_min_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE); if (alloc_min_size < nlk->max_recvmsg_len) { alloc_size = nlk->max_recvmsg_len; skb = alloc_skb(alloc_size, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY); } if (!skb) { alloc_size = alloc_min_size; skb = alloc_skb(alloc_size, GFP_KERNEL); } if (!skb) goto errout_skb; /* Trim skb to allocated size. User is expected to provide buffer as * large as max(min_dump_alloc, 16KiB (mac_recvmsg_len capped at * netlink_recvmsg())). dump will pack as many smaller messages as * could fit within the allocated skb. skb is typically allocated * with larger space than required (could be as much as near 2x the * requested size with align to next power of 2 approach). Allowing * dump to use the excess space makes it difficult for a user to have a * reasonable static buffer based on the expected largest dump of a * single netdev. The outcome is MSG_TRUNC error. */ skb_reserve(skb, skb_tailroom(skb) - alloc_size); netlink_skb_set_owner_r(skb, sk); len = cb->dump(skb, cb); if (len > 0) { mutex_unlock(nlk->cb_mutex); if (sk_filter(sk, skb)) kfree_skb(skb); else __netlink_sendskb(sk, skb); return 0; } nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE, sizeof(len), NLM_F_MULTI); if (!nlh) goto errout_skb; nl_dump_check_consistent(cb, nlh); memcpy(nlmsg_data(nlh), &len, sizeof(len)); if (sk_filter(sk, skb)) kfree_skb(skb); else __netlink_sendskb(sk, skb); if (cb->done) cb->done(cb); nlk->cb_running = false; module = cb->module; skb = cb->skb; mutex_unlock(nlk->cb_mutex); module_put(module); consume_skb(skb); return 0; errout_skb: mutex_unlock(nlk->cb_mutex); kfree_skb(skb); return err; }
166,844
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AXNodeObject::isModal() const { if (roleValue() != DialogRole && roleValue() != AlertDialogRole) return false; if (hasAttribute(aria_modalAttr)) { const AtomicString& modal = getAttribute(aria_modalAttr); if (equalIgnoringCase(modal, "true")) return true; if (equalIgnoringCase(modal, "false")) return false; } if (getNode() && isHTMLDialogElement(*getNode())) return toElement(getNode())->isInTopLayer(); return false; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
bool AXNodeObject::isModal() const { if (roleValue() != DialogRole && roleValue() != AlertDialogRole) return false; if (hasAttribute(aria_modalAttr)) { const AtomicString& modal = getAttribute(aria_modalAttr); if (equalIgnoringASCIICase(modal, "true")) return true; if (equalIgnoringASCIICase(modal, "false")) return false; } if (getNode() && isHTMLDialogElement(*getNode())) return toElement(getNode())->isInTopLayer(); return false; }
171,916
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PlatformSensorLinux::PlatformSensorLinux( mojom::SensorType type, mojo::ScopedSharedBufferMapping mapping, PlatformSensorProvider* provider, const SensorInfoLinux* sensor_device, scoped_refptr<base::SingleThreadTaskRunner> polling_thread_task_runner) : PlatformSensor(type, std::move(mapping), provider), default_configuration_( PlatformSensorConfiguration(sensor_device->device_frequency)), reporting_mode_(sensor_device->reporting_mode), polling_thread_task_runner_(std::move(polling_thread_task_runner)), weak_factory_(this) { sensor_reader_ = SensorReader::Create( sensor_device, weak_factory_.GetWeakPtr(), task_runner_); } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732
PlatformSensorLinux::PlatformSensorLinux( mojom::SensorType type, SensorReadingSharedBuffer* reading_buffer, PlatformSensorProvider* provider, const SensorInfoLinux* sensor_device, scoped_refptr<base::SingleThreadTaskRunner> polling_thread_task_runner) : PlatformSensor(type, reading_buffer, provider), default_configuration_( PlatformSensorConfiguration(sensor_device->device_frequency)), reporting_mode_(sensor_device->reporting_mode), polling_thread_task_runner_(std::move(polling_thread_task_runner)), weak_factory_(this) { sensor_reader_ = SensorReader::Create( sensor_device, weak_factory_.GetWeakPtr(), task_runner_); }
172,833
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LoginHtmlDialog::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type.value == NotificationType::LOAD_COMPLETED_MAIN_FRAME); if (bubble_frame_view_) bubble_frame_view_->StopThrobber(); } Commit Message: cros: The next 100 clang plugin errors. BUG=none TEST=none TBR=dpolukhin Review URL: http://codereview.chromium.org/7022008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85418 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void LoginHtmlDialog::Observe(NotificationType type,
170,616