instruction
stringclasses
1 value
input
stringlengths
90
9.34k
output
stringlengths
16
15.4k
__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. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Init() { DCHECK(!initialized_successfully_) << "Already initialized"; if (!CrosLibrary::Get()->EnsureLoaded()) return false; input_method_status_connection_ = chromeos::MonitorInputMethodStatus( this, &InputMethodChangedHandler, &RegisterPropertiesHandler, &UpdatePropertyHandler, &ConnectionChangeHandler); if (!input_method_status_connection_) return false; initialized_successfully_ = true; return true; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool Init() { DCHECK(!initialized_successfully_) << "Already initialized"; ibus_controller_ = input_method::IBusController::Create(); // The observer should be added before Connect() so we can capture the // initial connection change. ibus_controller_->AddObserver(this); ibus_controller_->Connect(); initialized_successfully_ = true; return true; }
170,494
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppModalDialog::CompleteDialog() { AppModalDialogQueue::GetInstance()->ShowNextDialog(); } Commit Message: Fix a Windows crash bug with javascript alerts from extension popups. BUG=137707 Review URL: https://chromiumcodereview.appspot.com/10828423 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152716 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void AppModalDialog::CompleteDialog() { if (!completed_) { completed_ = true; AppModalDialogQueue::GetInstance()->ShowNextDialog(); } }
170,754
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppControllerImpl::OnAppUpdate(const apps::AppUpdate& update) { if (!update.StateIsNull() && !update.NameChanged() && !update.ReadinessChanged()) { return; } if (client_) { client_->OnAppChanged(CreateAppPtr(update)); } } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <[email protected]> Commit-Queue: Lucas Tenório <[email protected]> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416
void AppControllerImpl::OnAppUpdate(const apps::AppUpdate& update) { void AppControllerService::OnAppUpdate(const apps::AppUpdate& update) { if (!update.StateIsNull() && !update.NameChanged() && !update.ReadinessChanged()) { return; } if (client_) { client_->OnAppChanged(CreateAppPtr(update)); } }
172,087
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: parse_file (FILE* input_file, char* directory, char *body_filename, char *body_pref, int flags) { uint32 d; uint16 key; Attr *attr = NULL; File *file = NULL; int rtf_size = 0, html_size = 0; MessageBody body; memset (&body, '\0', sizeof (MessageBody)); /* store the program options in our file global variables */ g_flags = flags; /* check that this is in fact a TNEF file */ d = geti32(input_file); if (d != TNEF_SIGNATURE) { fprintf (stdout, "Seems not to be a TNEF file\n"); return 1; } /* Get the key */ key = geti16(input_file); debug_print ("TNEF Key: %hx\n", key); /* The rest of the file is a series of 'messages' and 'attachments' */ while ( data_left( input_file ) ) { attr = read_object( input_file ); if ( attr == NULL ) break; /* This signals the beginning of a file */ if (attr->name == attATTACHRENDDATA) { if (file) { file_write (file, directory); file_free (file); } else { file = CHECKED_XCALLOC (File, 1); } } /* Add the data to our lists. */ switch (attr->lvl_type) { case LVL_MESSAGE: if (attr->name == attBODY) { body.text_body = get_text_data (attr); } else if (attr->name == attMAPIPROPS) { MAPI_Attr **mapi_attrs = mapi_attr_read (attr->len, attr->buf); if (mapi_attrs) { int i; for (i = 0; mapi_attrs[i]; i++) { MAPI_Attr *a = mapi_attrs[i]; if (a->name == MAPI_BODY_HTML) { body.html_bodies = get_html_data (a); html_size = a->num_values; } else if (a->name == MAPI_RTF_COMPRESSED) { body.rtf_bodies = get_rtf_data (a); rtf_size = a->num_values; } } /* cannot save attributes to file, since they * are not attachment attributes */ /* file_add_mapi_attrs (file, mapi_attrs); */ mapi_attr_free_list (mapi_attrs); XFREE (mapi_attrs); } } break; case LVL_ATTACHMENT: file_add_attr (file, attr); break; default: fprintf (stderr, "Invalid lvl type on attribute: %d\n", attr->lvl_type); return 1; break; } attr_free (attr); XFREE (attr); } if (file) { file_write (file, directory); file_free (file); XFREE (file); } /* Write the message body */ if (flags & SAVEBODY) { int i = 0; int all_flag = 0; if (strcmp (body_pref, "all") == 0) { all_flag = 1; body_pref = "rht"; } for (; i < 3; i++) { File **files = get_body_files (body_filename, body_pref[i], &body); if (files) { int j = 0; for (; files[j]; j++) { file_write(files[j], directory); file_free (files[j]); XFREE(files[j]); } XFREE(files); if (!all_flag) break; } } } if (body.text_body) { free_bodies(body.text_body, 1); XFREE(body.text_body); } if (rtf_size > 0) { free_bodies(body.rtf_bodies, rtf_size); XFREE(body.rtf_bodies); } if (html_size > 0) { free_bodies(body.html_bodies, html_size); XFREE(body.html_bodies); } return 0; } Commit Message: Check types to avoid invalid reads/writes. CWE ID: CWE-125
parse_file (FILE* input_file, char* directory, char *body_filename, char *body_pref, int flags) { uint32 d; uint16 key; Attr *attr = NULL; File *file = NULL; int rtf_size = 0, html_size = 0; MessageBody body; memset (&body, '\0', sizeof (MessageBody)); /* store the program options in our file global variables */ g_flags = flags; /* check that this is in fact a TNEF file */ d = geti32(input_file); if (d != TNEF_SIGNATURE) { fprintf (stdout, "Seems not to be a TNEF file\n"); return 1; } /* Get the key */ key = geti16(input_file); debug_print ("TNEF Key: %hx\n", key); /* The rest of the file is a series of 'messages' and 'attachments' */ while ( data_left( input_file ) ) { attr = read_object( input_file ); if ( attr == NULL ) break; /* This signals the beginning of a file */ if (attr->name == attATTACHRENDDATA) { if (file) { file_write (file, directory); file_free (file); } else { file = CHECKED_XCALLOC (File, 1); } } /* Add the data to our lists. */ switch (attr->lvl_type) { case LVL_MESSAGE: if (attr->name == attBODY) { body.text_body = get_text_data (attr); } else if (attr->name == attMAPIPROPS) { MAPI_Attr **mapi_attrs = mapi_attr_read (attr->len, attr->buf); if (mapi_attrs) { int i; for (i = 0; mapi_attrs[i]; i++) { MAPI_Attr *a = mapi_attrs[i]; if (a->type == szMAPI_BINARY && a->name == MAPI_BODY_HTML) { body.html_bodies = get_html_data (a); html_size = a->num_values; } else if (a->type == szMAPI_BINARY && a->name == MAPI_RTF_COMPRESSED) { body.rtf_bodies = get_rtf_data (a); rtf_size = a->num_values; } } /* cannot save attributes to file, since they * are not attachment attributes */ /* file_add_mapi_attrs (file, mapi_attrs); */ mapi_attr_free_list (mapi_attrs); XFREE (mapi_attrs); } } break; case LVL_ATTACHMENT: file_add_attr (file, attr); break; default: fprintf (stderr, "Invalid lvl type on attribute: %d\n", attr->lvl_type); return 1; break; } attr_free (attr); XFREE (attr); } if (file) { file_write (file, directory); file_free (file); XFREE (file); } /* Write the message body */ if (flags & SAVEBODY) { int i = 0; int all_flag = 0; if (strcmp (body_pref, "all") == 0) { all_flag = 1; body_pref = "rht"; } for (; i < 3; i++) { File **files = get_body_files (body_filename, body_pref[i], &body); if (files) { int j = 0; for (; files[j]; j++) { file_write(files[j], directory); file_free (files[j]); XFREE(files[j]); } XFREE(files); if (!all_flag) break; } } } if (body.text_body) { free_bodies(body.text_body, 1); XFREE(body.text_body); } if (rtf_size > 0) { free_bodies(body.rtf_bodies, rtf_size); XFREE(body.rtf_bodies); } if (html_size > 0) { free_bodies(body.html_bodies, html_size); XFREE(body.html_bodies); } return 0; }
168,353
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: XGetModifierMapping(register Display *dpy) { xGetModifierMappingReply rep; register xReq *req; unsigned long nbytes; XModifierKeymap *res; LockDisplay(dpy); GetEmptyReq(GetModifierMapping, req); (void) _XReply (dpy, (xReply *)&rep, 0, xFalse); if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long)rep.length << 2; res = Xmalloc(sizeof (XModifierKeymap)); if (res) } else res = NULL; if ((! res) || (! res->modifiermap)) { Xfree(res); res = (XModifierKeymap *) NULL; _XEatDataWords(dpy, rep.length); } else { _XReadPad(dpy, (char *) res->modifiermap, (long) nbytes); res->max_keypermod = rep.numKeyPerModifier; } UnlockDisplay(dpy); SyncHandle(); return (res); } Commit Message: CWE ID: CWE-787
XGetModifierMapping(register Display *dpy) { xGetModifierMappingReply rep; register xReq *req; unsigned long nbytes; XModifierKeymap *res; LockDisplay(dpy); GetEmptyReq(GetModifierMapping, req); (void) _XReply (dpy, (xReply *)&rep, 0, xFalse); if (rep.length < (INT_MAX >> 2) && (rep.length >> 1) == rep.numKeyPerModifier) { nbytes = (unsigned long)rep.length << 2; res = Xmalloc(sizeof (XModifierKeymap)); if (res) } else res = NULL; if ((! res) || (! res->modifiermap)) { Xfree(res); res = (XModifierKeymap *) NULL; _XEatDataWords(dpy, rep.length); } else { _XReadPad(dpy, (char *) res->modifiermap, (long) nbytes); res->max_keypermod = rep.numKeyPerModifier; } UnlockDisplay(dpy); SyncHandle(); return (res); }
164,924
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int _yr_scan_verify_re_match( YR_SCAN_CONTEXT* context, YR_AC_MATCH* ac_match, uint8_t* data, size_t data_size, size_t data_base, size_t offset) { CALLBACK_ARGS callback_args; RE_EXEC_FUNC exec; int forward_matches = -1; int backward_matches = -1; int flags = 0; if (STRING_IS_GREEDY_REGEXP(ac_match->string)) flags |= RE_FLAGS_GREEDY; if (STRING_IS_NO_CASE(ac_match->string)) flags |= RE_FLAGS_NO_CASE; if (STRING_IS_DOT_ALL(ac_match->string)) flags |= RE_FLAGS_DOT_ALL; if (STRING_IS_FAST_REGEXP(ac_match->string)) exec = yr_re_fast_exec; else exec = yr_re_exec; if (STRING_IS_ASCII(ac_match->string)) { forward_matches = exec( ac_match->forward_code, data + offset, data_size - offset, offset > 0 ? flags | RE_FLAGS_NOT_AT_START : flags, NULL, NULL); } if (STRING_IS_WIDE(ac_match->string) && forward_matches == -1) { flags |= RE_FLAGS_WIDE; forward_matches = exec( ac_match->forward_code, data + offset, data_size - offset, offset > 0 ? flags | RE_FLAGS_NOT_AT_START : flags, NULL, NULL); } switch(forward_matches) { case -1: return ERROR_SUCCESS; case -2: return ERROR_INSUFFICIENT_MEMORY; case -3: return ERROR_TOO_MANY_MATCHES; case -4: return ERROR_TOO_MANY_RE_FIBERS; case -5: return ERROR_INTERNAL_FATAL_ERROR; } if (forward_matches == 0 && ac_match->backward_code == NULL) return ERROR_SUCCESS; callback_args.string = ac_match->string; callback_args.context = context; callback_args.data = data; callback_args.data_size = data_size; callback_args.data_base = data_base; callback_args.forward_matches = forward_matches; callback_args.full_word = STRING_IS_FULL_WORD(ac_match->string); if (ac_match->backward_code != NULL) { backward_matches = exec( ac_match->backward_code, data + offset, offset, flags | RE_FLAGS_BACKWARDS | RE_FLAGS_EXHAUSTIVE, _yr_scan_match_callback, (void*) &callback_args); switch(backward_matches) { case -2: return ERROR_INSUFFICIENT_MEMORY; case -3: return ERROR_TOO_MANY_MATCHES; case -4: return ERROR_TOO_MANY_RE_FIBERS; case -5: return ERROR_INTERNAL_FATAL_ERROR; } } else { FAIL_ON_ERROR(_yr_scan_match_callback( data + offset, 0, flags, &callback_args)); } return ERROR_SUCCESS; } Commit Message: Fix issue #646 (#648) * Fix issue #646 and some edge cases with wide regexps using \b and \B * Rename function IS_WORD_CHAR to _yr_re_is_word_char CWE ID: CWE-125
int _yr_scan_verify_re_match( YR_SCAN_CONTEXT* context, YR_AC_MATCH* ac_match, uint8_t* data, size_t data_size, size_t data_base, size_t offset) { CALLBACK_ARGS callback_args; RE_EXEC_FUNC exec; int forward_matches = -1; int backward_matches = -1; int flags = 0; if (STRING_IS_GREEDY_REGEXP(ac_match->string)) flags |= RE_FLAGS_GREEDY; if (STRING_IS_NO_CASE(ac_match->string)) flags |= RE_FLAGS_NO_CASE; if (STRING_IS_DOT_ALL(ac_match->string)) flags |= RE_FLAGS_DOT_ALL; if (STRING_IS_FAST_REGEXP(ac_match->string)) exec = yr_re_fast_exec; else exec = yr_re_exec; if (STRING_IS_ASCII(ac_match->string)) { forward_matches = exec( ac_match->forward_code, data + offset, data_size - offset, offset, flags, NULL, NULL); } if (STRING_IS_WIDE(ac_match->string) && forward_matches == -1) { flags |= RE_FLAGS_WIDE; forward_matches = exec( ac_match->forward_code, data + offset, data_size - offset, offset, flags, NULL, NULL); } switch(forward_matches) { case -1: return ERROR_SUCCESS; case -2: return ERROR_INSUFFICIENT_MEMORY; case -3: return ERROR_TOO_MANY_MATCHES; case -4: return ERROR_TOO_MANY_RE_FIBERS; case -5: return ERROR_INTERNAL_FATAL_ERROR; } if (forward_matches == 0 && ac_match->backward_code == NULL) return ERROR_SUCCESS; callback_args.string = ac_match->string; callback_args.context = context; callback_args.data = data; callback_args.data_size = data_size; callback_args.data_base = data_base; callback_args.forward_matches = forward_matches; callback_args.full_word = STRING_IS_FULL_WORD(ac_match->string); if (ac_match->backward_code != NULL) { backward_matches = exec( ac_match->backward_code, data + offset, data_size - offset, offset, flags | RE_FLAGS_BACKWARDS | RE_FLAGS_EXHAUSTIVE, _yr_scan_match_callback, (void*) &callback_args); switch(backward_matches) { case -2: return ERROR_INSUFFICIENT_MEMORY; case -3: return ERROR_TOO_MANY_MATCHES; case -4: return ERROR_TOO_MANY_RE_FIBERS; case -5: return ERROR_INTERNAL_FATAL_ERROR; } } else { FAIL_ON_ERROR(_yr_scan_match_callback( data + offset, 0, flags, &callback_args)); } return ERROR_SUCCESS; }
168,204
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderFrameHostImpl::OnDidAddMessageToConsole( int32_t level, const base::string16& message, int32_t line_no, const base::string16& source_id) { if (level < logging::LOG_VERBOSE || level > logging::LOG_FATAL) { bad_message::ReceivedBadMessage( GetProcess(), bad_message::RFH_DID_ADD_CONSOLE_MESSAGE_BAD_SEVERITY); return; } if (delegate_->DidAddMessageToConsole(level, message, line_no, source_id)) return; const bool is_builtin_component = HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL()) || GetContentClient()->browser()->IsBuiltinComponent( GetProcess()->GetBrowserContext(), GetLastCommittedOrigin()); const bool is_off_the_record = GetSiteInstance()->GetBrowserContext()->IsOffTheRecord(); LogConsoleMessage(level, message, line_no, is_builtin_component, is_off_the_record, source_id); } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416
void RenderFrameHostImpl::OnDidAddMessageToConsole( void RenderFrameHostImpl::DidAddMessageToConsole( blink::mojom::ConsoleMessageLevel log_level, const base::string16& message, int32_t line_no, const base::string16& source_id) { // TODO(https://crbug.com/786836): Update downstream code to use // ConsoleMessageLevel everywhere to avoid this conversion. logging::LogSeverity log_severity = logging::LOG_VERBOSE; switch (log_level) { case blink::mojom::ConsoleMessageLevel::kVerbose: log_severity = logging::LOG_VERBOSE; break; case blink::mojom::ConsoleMessageLevel::kInfo: log_severity = logging::LOG_INFO; break; case blink::mojom::ConsoleMessageLevel::kWarning: log_severity = logging::LOG_WARNING; break; case blink::mojom::ConsoleMessageLevel::kError: log_severity = logging::LOG_ERROR; break; } if (delegate_->DidAddMessageToConsole(log_severity, message, line_no, source_id)) { return; } // Pass through log severity only on builtin components pages to limit console const bool is_builtin_component = HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL()) || GetContentClient()->browser()->IsBuiltinComponent( GetProcess()->GetBrowserContext(), GetLastCommittedOrigin()); const bool is_off_the_record = GetSiteInstance()->GetBrowserContext()->IsOffTheRecord(); LogConsoleMessage(log_severity, message, line_no, is_builtin_component, is_off_the_record, source_id); }
172,485
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void xml_parser_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) { xml_parser *parser = (xml_parser *)rsrc->ptr; if (parser->parser) { XML_ParserFree(parser->parser); } if (parser->ltags) { int inx; for (inx = 0; ((inx < parser->level) && (inx < XML_MAXLEVEL)); inx++) efree(parser->ltags[ inx ]); efree(parser->ltags); } if (parser->startElementHandler) { zval_ptr_dtor(&parser->startElementHandler); } if (parser->endElementHandler) { zval_ptr_dtor(&parser->endElementHandler); } if (parser->characterDataHandler) { zval_ptr_dtor(&parser->characterDataHandler); } if (parser->processingInstructionHandler) { zval_ptr_dtor(&parser->processingInstructionHandler); } if (parser->defaultHandler) { zval_ptr_dtor(&parser->defaultHandler); } if (parser->unparsedEntityDeclHandler) { zval_ptr_dtor(&parser->unparsedEntityDeclHandler); } if (parser->notationDeclHandler) { zval_ptr_dtor(&parser->notationDeclHandler); } if (parser->externalEntityRefHandler) { zval_ptr_dtor(&parser->externalEntityRefHandler); } if (parser->unknownEncodingHandler) { zval_ptr_dtor(&parser->unknownEncodingHandler); } if (parser->startNamespaceDeclHandler) { zval_ptr_dtor(&parser->startNamespaceDeclHandler); } if (parser->endNamespaceDeclHandler) { zval_ptr_dtor(&parser->endNamespaceDeclHandler); } if (parser->baseURI) { efree(parser->baseURI); } if (parser->object) { zval_ptr_dtor(&parser->object); } efree(parser); } Commit Message: CWE ID: CWE-119
static void xml_parser_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) { xml_parser *parser = (xml_parser *)rsrc->ptr; if (parser->parser) { XML_ParserFree(parser->parser); } if (parser->ltags) { int inx; for (inx = 0; ((inx < parser->level) && (inx < XML_MAXLEVEL)); inx++) efree(parser->ltags[ inx ]); efree(parser->ltags); } if (parser->startElementHandler) { zval_ptr_dtor(&parser->startElementHandler); } if (parser->endElementHandler) { zval_ptr_dtor(&parser->endElementHandler); } if (parser->characterDataHandler) { zval_ptr_dtor(&parser->characterDataHandler); } if (parser->processingInstructionHandler) { zval_ptr_dtor(&parser->processingInstructionHandler); } if (parser->defaultHandler) { zval_ptr_dtor(&parser->defaultHandler); } if (parser->unparsedEntityDeclHandler) { zval_ptr_dtor(&parser->unparsedEntityDeclHandler); } if (parser->notationDeclHandler) { zval_ptr_dtor(&parser->notationDeclHandler); } if (parser->externalEntityRefHandler) { zval_ptr_dtor(&parser->externalEntityRefHandler); } if (parser->unknownEncodingHandler) { zval_ptr_dtor(&parser->unknownEncodingHandler); } if (parser->startNamespaceDeclHandler) { zval_ptr_dtor(&parser->startNamespaceDeclHandler); } if (parser->endNamespaceDeclHandler) { zval_ptr_dtor(&parser->endNamespaceDeclHandler); } if (parser->baseURI) { efree(parser->baseURI); } if (parser->object) { zval_ptr_dtor(&parser->object); } efree(parser); }
165,047
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const Tracks* Segment::GetTracks() const { return m_pTracks; } 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
const Tracks* Segment::GetTracks() const const SegmentInfo* Segment::GetInfo() const { return m_pInfo; } const Cues* Segment::GetCues() const { return m_pCues; } const Chapters* Segment::GetChapters() const { return m_pChapters; } const SeekHead* Segment::GetSeekHead() const { return m_pSeekHead; } long long Segment::GetDuration() const { assert(m_pInfo); return m_pInfo->GetDuration(); }
174,373
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppControllerImpl::LaunchHomeUrl(const std::string& suffix, LaunchHomeUrlCallback callback) { if (url_prefix_.empty()) { std::move(callback).Run(false, "No URL prefix."); return; } GURL url(url_prefix_ + suffix); if (!url.is_valid()) { std::move(callback).Run(false, "Invalid URL."); return; } arc::mojom::AppInstance* app_instance = arc::ArcServiceManager::Get() ? ARC_GET_INSTANCE_FOR_METHOD( arc::ArcServiceManager::Get()->arc_bridge_service()->app(), LaunchIntent) : nullptr; if (!app_instance) { std::move(callback).Run(false, "ARC bridge not available."); return; } app_instance->LaunchIntent(url.spec(), display::kDefaultDisplayId); std::move(callback).Run(true, base::nullopt); } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <[email protected]> Commit-Queue: Lucas Tenório <[email protected]> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416
void AppControllerImpl::LaunchHomeUrl(const std::string& suffix, void AppControllerService::LaunchHomeUrl(const std::string& suffix, LaunchHomeUrlCallback callback) { if (url_prefix_.empty()) { std::move(callback).Run(false, "No URL prefix."); return; } GURL url(url_prefix_ + suffix); if (!url.is_valid()) { std::move(callback).Run(false, "Invalid URL."); return; } arc::mojom::AppInstance* app_instance = arc::ArcServiceManager::Get() ? ARC_GET_INSTANCE_FOR_METHOD( arc::ArcServiceManager::Get()->arc_bridge_service()->app(), LaunchIntent) : nullptr; if (!app_instance) { std::move(callback).Run(false, "ARC bridge not available."); return; } app_instance->LaunchIntent(url.spec(), display::kDefaultDisplayId); std::move(callback).Run(true, base::nullopt); }
172,085
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct sk_buff *nf_ct_frag6_gather(struct sk_buff *skb, u32 user) { struct sk_buff *clone; struct net_device *dev = skb->dev; struct frag_hdr *fhdr; struct nf_ct_frag6_queue *fq; struct ipv6hdr *hdr; int fhoff, nhoff; u8 prevhdr; struct sk_buff *ret_skb = NULL; /* Jumbo payload inhibits frag. header */ if (ipv6_hdr(skb)->payload_len == 0) { pr_debug("payload len = 0\n"); return skb; } if (find_prev_fhdr(skb, &prevhdr, &nhoff, &fhoff) < 0) return skb; clone = skb_clone(skb, GFP_ATOMIC); if (clone == NULL) { pr_debug("Can't clone skb\n"); return skb; } NFCT_FRAG6_CB(clone)->orig = skb; if (!pskb_may_pull(clone, fhoff + sizeof(*fhdr))) { pr_debug("message is too short.\n"); goto ret_orig; } skb_set_transport_header(clone, fhoff); hdr = ipv6_hdr(clone); fhdr = (struct frag_hdr *)skb_transport_header(clone); if (!(fhdr->frag_off & htons(0xFFF9))) { pr_debug("Invalid fragment offset\n"); /* It is not a fragmented frame */ goto ret_orig; } if (atomic_read(&nf_init_frags.mem) > nf_init_frags.high_thresh) nf_ct_frag6_evictor(); fq = fq_find(fhdr->identification, user, &hdr->saddr, &hdr->daddr); if (fq == NULL) { pr_debug("Can't find and can't create new queue\n"); goto ret_orig; } spin_lock_bh(&fq->q.lock); if (nf_ct_frag6_queue(fq, clone, fhdr, nhoff) < 0) { spin_unlock_bh(&fq->q.lock); pr_debug("Can't insert skb to queue\n"); fq_put(fq); goto ret_orig; } if (fq->q.last_in == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) && fq->q.meat == fq->q.len) { ret_skb = nf_ct_frag6_reasm(fq, dev); if (ret_skb == NULL) pr_debug("Can't reassemble fragmented packets\n"); } spin_unlock_bh(&fq->q.lock); fq_put(fq); return ret_skb; ret_orig: kfree_skb(clone); return skb; } Commit Message: netfilter: nf_conntrack_reasm: properly handle packets fragmented into a single fragment When an ICMPV6_PKT_TOOBIG message is received with a MTU below 1280, all further packets include a fragment header. Unlike regular defragmentation, conntrack also needs to "reassemble" those fragments in order to obtain a packet without the fragment header for connection tracking. Currently nf_conntrack_reasm checks whether a fragment has either IP6_MF set or an offset != 0, which makes it ignore those fragments. Remove the invalid check and make reassembly handle fragment queues containing only a single fragment. Reported-and-tested-by: Ulrich Weber <[email protected]> Signed-off-by: Patrick McHardy <[email protected]> CWE ID:
struct sk_buff *nf_ct_frag6_gather(struct sk_buff *skb, u32 user) { struct sk_buff *clone; struct net_device *dev = skb->dev; struct frag_hdr *fhdr; struct nf_ct_frag6_queue *fq; struct ipv6hdr *hdr; int fhoff, nhoff; u8 prevhdr; struct sk_buff *ret_skb = NULL; /* Jumbo payload inhibits frag. header */ if (ipv6_hdr(skb)->payload_len == 0) { pr_debug("payload len = 0\n"); return skb; } if (find_prev_fhdr(skb, &prevhdr, &nhoff, &fhoff) < 0) return skb; clone = skb_clone(skb, GFP_ATOMIC); if (clone == NULL) { pr_debug("Can't clone skb\n"); return skb; } NFCT_FRAG6_CB(clone)->orig = skb; if (!pskb_may_pull(clone, fhoff + sizeof(*fhdr))) { pr_debug("message is too short.\n"); goto ret_orig; } skb_set_transport_header(clone, fhoff); hdr = ipv6_hdr(clone); fhdr = (struct frag_hdr *)skb_transport_header(clone); if (atomic_read(&nf_init_frags.mem) > nf_init_frags.high_thresh) nf_ct_frag6_evictor(); fq = fq_find(fhdr->identification, user, &hdr->saddr, &hdr->daddr); if (fq == NULL) { pr_debug("Can't find and can't create new queue\n"); goto ret_orig; } spin_lock_bh(&fq->q.lock); if (nf_ct_frag6_queue(fq, clone, fhdr, nhoff) < 0) { spin_unlock_bh(&fq->q.lock); pr_debug("Can't insert skb to queue\n"); fq_put(fq); goto ret_orig; } if (fq->q.last_in == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) && fq->q.meat == fq->q.len) { ret_skb = nf_ct_frag6_reasm(fq, dev); if (ret_skb == NULL) pr_debug("Can't reassemble fragmented packets\n"); } spin_unlock_bh(&fq->q.lock); fq_put(fq); return ret_skb; ret_orig: kfree_skb(clone); return skb; }
165,590
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RegisterOptimizationHintsComponent(ComponentUpdateService* cus, PrefService* profile_prefs) { if (!previews::params::IsOptimizationHintsEnabled()) { return; } bool data_saver_enabled = base::CommandLine::ForCurrentProcess()->HasSwitch( data_reduction_proxy::switches::kEnableDataReductionProxy) || (profile_prefs && profile_prefs->GetBoolean( data_reduction_proxy::prefs::kDataSaverEnabled)); if (!data_saver_enabled) return; auto installer = base::MakeRefCounted<ComponentInstaller>( std::make_unique<OptimizationHintsComponentInstallerPolicy>()); installer->Register(cus, base::OnceClosure()); } 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
void RegisterOptimizationHintsComponent(ComponentUpdateService* cus, PrefService* profile_prefs) { if (!previews::params::IsOptimizationHintsEnabled()) { return; } if (!data_reduction_proxy::DataReductionProxySettings:: IsDataSaverEnabledByUser(profile_prefs)) { return; } auto installer = base::MakeRefCounted<ComponentInstaller>( std::make_unique<OptimizationHintsComponentInstallerPolicy>()); installer->Register(cus, base::OnceClosure()); }
172,548
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { DDSColors colors; ssize_t j, y; MagickSizeType alpha_bits; PixelPacket *q; register ssize_t i, x; unsigned char a0, a1; size_t alpha, bits, code, alpha_code; unsigned short c0, c1; for (y = 0; y < (ssize_t) dds_info->height; y += 4) { for (x = 0; x < (ssize_t) dds_info->width; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x), Min(4, dds_info->height - y),exception); if (q == (PixelPacket *) NULL) return MagickFalse; /* Read alpha values (8 bytes) */ a0 = (unsigned char) ReadBlobByte(image); a1 = (unsigned char) ReadBlobByte(image); alpha_bits = (MagickSizeType)ReadBlobLSBLong(image); alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32); /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickTrue); /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height) { code = (bits >> ((4*j+i)*2)) & 0x3; SetPixelRed(q,ScaleCharToQuantum(colors.r[code])); SetPixelGreen(q,ScaleCharToQuantum(colors.g[code])); SetPixelBlue(q,ScaleCharToQuantum(colors.b[code])); /* Extract alpha value */ alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7; if (alpha_code == 0) alpha = a0; else if (alpha_code == 1) alpha = a1; else if (a0 > a1) alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7; else if (alpha_code == 6) alpha = 0; else if (alpha_code == 7) alpha = 255; else alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) alpha)); q++; } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } } SkipDXTMipmaps(image, dds_info, 16); return MagickTrue; } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20
static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { DDSColors colors; ssize_t j, y; MagickSizeType alpha_bits; PixelPacket *q; register ssize_t i, x; unsigned char a0, a1; size_t alpha, bits, code, alpha_code; unsigned short c0, c1; for (y = 0; y < (ssize_t) dds_info->height; y += 4) { for (x = 0; x < (ssize_t) dds_info->width; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x), MagickMin(4, dds_info->height - y),exception); if (q == (PixelPacket *) NULL) return MagickFalse; /* Read alpha values (8 bytes) */ a0 = (unsigned char) ReadBlobByte(image); a1 = (unsigned char) ReadBlobByte(image); alpha_bits = (MagickSizeType)ReadBlobLSBLong(image); alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32); /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickTrue); /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height) { code = (bits >> ((4*j+i)*2)) & 0x3; SetPixelRed(q,ScaleCharToQuantum(colors.r[code])); SetPixelGreen(q,ScaleCharToQuantum(colors.g[code])); SetPixelBlue(q,ScaleCharToQuantum(colors.b[code])); /* Extract alpha value */ alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7; if (alpha_code == 0) alpha = a0; else if (alpha_code == 1) alpha = a1; else if (a0 > a1) alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7; else if (alpha_code == 6) alpha = 0; else if (alpha_code == 7) alpha = 255; else alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) alpha)); q++; } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } } return(SkipDXTMipmaps(image,dds_info,16,exception)); }
168,901
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Gfx::Gfx(XRef *xrefA, OutputDev *outA, Dict *resDict, Catalog *catalogA, PDFRectangle *box, PDFRectangle *cropBox, GBool (*abortCheckCbkA)(void *data), void *abortCheckCbkDataA) #ifdef USE_CMS : iccColorSpaceCache(5) #endif { int i; xref = xrefA; catalog = catalogA; subPage = gTrue; printCommands = globalParams->getPrintCommands(); profileCommands = globalParams->getProfileCommands(); textHaveCSPattern = gFalse; drawText = gFalse; drawText = gFalse; maskHaveCSPattern = gFalse; mcStack = NULL; res = new GfxResources(xref, resDict, NULL); out = outA; state = new GfxState(72, 72, box, 0, gFalse); stackHeight = 1; pushStateGuard(); fontChanged = gFalse; clip = clipNone; ignoreUndef = 0; for (i = 0; i < 6; ++i) { baseMatrix[i] = state->getCTM()[i]; } formDepth = 0; abortCheckCbk = abortCheckCbkA; abortCheckCbkData = abortCheckCbkDataA; if (cropBox) { state->moveTo(cropBox->x1, cropBox->y1); state->lineTo(cropBox->x2, cropBox->y1); state->lineTo(cropBox->x2, cropBox->y2); state->lineTo(cropBox->x1, cropBox->y2); state->closePath(); state->clip(); out->clip(state); state->clearPath(); } } Commit Message: CWE ID: CWE-20
Gfx::Gfx(XRef *xrefA, OutputDev *outA, Dict *resDict, Catalog *catalogA, PDFRectangle *box, PDFRectangle *cropBox, GBool (*abortCheckCbkA)(void *data), void *abortCheckCbkDataA) #ifdef USE_CMS : iccColorSpaceCache(5) #endif { int i; xref = xrefA; catalog = catalogA; subPage = gTrue; printCommands = globalParams->getPrintCommands(); profileCommands = globalParams->getProfileCommands(); textHaveCSPattern = gFalse; drawText = gFalse; drawText = gFalse; maskHaveCSPattern = gFalse; mcStack = NULL; parser = NULL; res = new GfxResources(xref, resDict, NULL); out = outA; state = new GfxState(72, 72, box, 0, gFalse); stackHeight = 1; pushStateGuard(); fontChanged = gFalse; clip = clipNone; ignoreUndef = 0; for (i = 0; i < 6; ++i) { baseMatrix[i] = state->getCTM()[i]; } formDepth = 0; abortCheckCbk = abortCheckCbkA; abortCheckCbkData = abortCheckCbkDataA; if (cropBox) { state->moveTo(cropBox->x1, cropBox->y1); state->lineTo(cropBox->x2, cropBox->y1); state->lineTo(cropBox->x2, cropBox->y2); state->lineTo(cropBox->x1, cropBox->y2); state->closePath(); state->clip(); out->clip(state); state->clearPath(); } }
164,905
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static NavigationPolicy NavigationPolicyForRequest( const FrameLoadRequest& request) { NavigationPolicy policy = kNavigationPolicyCurrentTab; Event* event = request.TriggeringEvent(); if (!event) return policy; if (request.Form() && event->UnderlyingEvent()) event = event->UnderlyingEvent(); if (event->IsMouseEvent()) { MouseEvent* mouse_event = ToMouseEvent(event); NavigationPolicyFromMouseEvent( mouse_event->button(), mouse_event->ctrlKey(), mouse_event->shiftKey(), mouse_event->altKey(), mouse_event->metaKey(), &policy); } else if (event->IsKeyboardEvent()) { KeyboardEvent* key_event = ToKeyboardEvent(event); NavigationPolicyFromMouseEvent(0, key_event->ctrlKey(), key_event->shiftKey(), key_event->altKey(), key_event->metaKey(), &policy); } else if (event->IsGestureEvent()) { GestureEvent* gesture_event = ToGestureEvent(event); NavigationPolicyFromMouseEvent( 0, gesture_event->ctrlKey(), gesture_event->shiftKey(), gesture_event->altKey(), gesture_event->metaKey(), &policy); } return policy; } Commit Message: Only allow downloading in response to real keyboard modifiers BUG=848531 Change-Id: I97554c8d312243b55647f1376945aee32dbd95bf Reviewed-on: https://chromium-review.googlesource.com/1082216 Reviewed-by: Mike West <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#564051} CWE ID:
static NavigationPolicy NavigationPolicyForRequest( static NavigationPolicy NavigationPolicyForEvent(Event* event) { NavigationPolicy policy = kNavigationPolicyCurrentTab; if (event->IsMouseEvent()) { MouseEvent* mouse_event = ToMouseEvent(event); NavigationPolicyFromMouseEvent( mouse_event->button(), mouse_event->ctrlKey(), mouse_event->shiftKey(), mouse_event->altKey(), mouse_event->metaKey(), &policy); } else if (event->IsKeyboardEvent()) { KeyboardEvent* key_event = ToKeyboardEvent(event); NavigationPolicyFromMouseEvent(0, key_event->ctrlKey(), key_event->shiftKey(), key_event->altKey(), key_event->metaKey(), &policy); } else if (event->IsGestureEvent()) { GestureEvent* gesture_event = ToGestureEvent(event); NavigationPolicyFromMouseEvent( 0, gesture_event->ctrlKey(), gesture_event->shiftKey(), gesture_event->altKey(), gesture_event->metaKey(), &policy); } return policy; }
173,191
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppShortcutManager::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_EXTENSIONS_READY: { OnceOffCreateShortcuts(); break; } case chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED: { #if defined(OS_MACOSX) if (!apps::IsAppShimsEnabled()) break; #endif // defined(OS_MACOSX) const extensions::InstalledExtensionInfo* installed_info = content::Details<const extensions::InstalledExtensionInfo>(details) .ptr(); const Extension* extension = installed_info->extension; if (installed_info->is_update) { web_app::UpdateAllShortcuts( base::UTF8ToUTF16(installed_info->old_name), profile_, extension); } else if (ShouldCreateShortcutFor(profile_, extension)) { CreateShortcutsInApplicationsMenu(profile_, extension); } break; } case chrome::NOTIFICATION_EXTENSION_UNINSTALLED: { const Extension* extension = content::Details<const Extension>( details).ptr(); web_app::DeleteAllShortcuts(profile_, extension); break; } default: NOTREACHED(); } } Commit Message: Remove --disable-app-shims. App shims have been enabled by default for 3 milestones (since r242711). BUG=350161 Review URL: https://codereview.chromium.org/298953002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void AppShortcutManager::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_EXTENSIONS_READY: { OnceOffCreateShortcuts(); break; } case chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED: { const extensions::InstalledExtensionInfo* installed_info = content::Details<const extensions::InstalledExtensionInfo>(details) .ptr(); const Extension* extension = installed_info->extension; if (installed_info->is_update) { web_app::UpdateAllShortcuts( base::UTF8ToUTF16(installed_info->old_name), profile_, extension); } else if (ShouldCreateShortcutFor(profile_, extension)) { CreateShortcutsInApplicationsMenu(profile_, extension); } break; } case chrome::NOTIFICATION_EXTENSION_UNINSTALLED: { const Extension* extension = content::Details<const Extension>( details).ptr(); web_app::DeleteAllShortcuts(profile_, extension); break; } default: NOTREACHED(); } }
171,145
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env) { YYUSE (yyvaluep); YYUSE (yyscanner); YYUSE (lex_env); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN switch (yytype) { case 16: /* tokens */ #line 94 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1023 "hex_grammar.c" /* yacc.c:1257 */ break; case 17: /* token_sequence */ #line 95 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1029 "hex_grammar.c" /* yacc.c:1257 */ break; case 18: /* token_or_range */ #line 96 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1035 "hex_grammar.c" /* yacc.c:1257 */ break; case 19: /* token */ #line 97 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1041 "hex_grammar.c" /* yacc.c:1257 */ break; case 21: /* range */ #line 100 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1047 "hex_grammar.c" /* yacc.c:1257 */ break; case 22: /* alternatives */ #line 99 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1053 "hex_grammar.c" /* yacc.c:1257 */ break; case 23: /* byte */ #line 98 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1059 "hex_grammar.c" /* yacc.c:1257 */ break; default: break; } YY_IGNORE_MAYBE_UNINITIALIZED_END } Commit Message: Fix issue #674 for hex strings. CWE ID: CWE-674
yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env) { YYUSE (yyvaluep); YYUSE (yyscanner); YYUSE (lex_env); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN switch (yytype) { case 16: /* tokens */ #line 101 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1030 "hex_grammar.c" /* yacc.c:1257 */ break; case 17: /* token_sequence */ #line 102 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1036 "hex_grammar.c" /* yacc.c:1257 */ break; case 18: /* token_or_range */ #line 103 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1042 "hex_grammar.c" /* yacc.c:1257 */ break; case 19: /* token */ #line 104 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1048 "hex_grammar.c" /* yacc.c:1257 */ break; case 21: /* range */ #line 107 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1054 "hex_grammar.c" /* yacc.c:1257 */ break; case 22: /* alternatives */ #line 106 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1060 "hex_grammar.c" /* yacc.c:1257 */ break; case 23: /* byte */ #line 105 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1066 "hex_grammar.c" /* yacc.c:1257 */ break; default: break; } YY_IGNORE_MAYBE_UNINITIALIZED_END }
168,100
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: transform_name(int t) /* The name, if 't' has multiple bits set the name of the lowest set bit is * returned. */ { unsigned int i; t &= -t; /* first set bit */ for (i=0; i<TTABLE_SIZE; ++i) { if ((transform_info[i].transform & t) != 0) return transform_info[i].name; } return "invalid transform"; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
transform_name(int t) /* The name, if 't' has multiple bits set the name of the lowest set bit is * returned. */ { unsigned int i; t &= -t; /* first set bit */ for (i=0; i<TTABLE_SIZE; ++i) if (transform_info[i].name != NULL) { if ((transform_info[i].transform & t) != 0) return transform_info[i].name; } return "invalid transform"; }
173,590
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: validate_event(struct pmu_hw_events *hw_events, struct perf_event *event) { struct arm_pmu *armpmu = to_arm_pmu(event->pmu); struct pmu *leader_pmu = event->group_leader->pmu; if (event->pmu != leader_pmu || event->state < PERF_EVENT_STATE_OFF) return 1; if (event->state == PERF_EVENT_STATE_OFF && !event->attr.enable_on_exec) return 1; return armpmu->get_event_idx(hw_events, event) >= 0; } Commit Message: ARM: 7809/1: perf: fix event validation for software group leaders It is possible to construct an event group with a software event as a group leader and then subsequently add a hardware event to the group. This results in the event group being validated by adding all members of the group to a fake PMU and attempting to allocate each event on their respective PMU. Unfortunately, for software events wthout a corresponding arm_pmu, this results in a kernel crash attempting to dereference the ->get_event_idx function pointer. This patch fixes the problem by checking explicitly for software events and ignoring those in event validation (since they can always be scheduled). We will probably want to revisit this for 3.12, since the validation checks don't appear to work correctly when dealing with multiple hardware PMUs anyway. Cc: <[email protected]> Reported-by: Vince Weaver <[email protected]> Tested-by: Vince Weaver <[email protected]> Tested-by: Mark Rutland <[email protected]> Signed-off-by: Will Deacon <[email protected]> Signed-off-by: Russell King <[email protected]> CWE ID: CWE-20
validate_event(struct pmu_hw_events *hw_events, struct perf_event *event) { struct arm_pmu *armpmu = to_arm_pmu(event->pmu); struct pmu *leader_pmu = event->group_leader->pmu; if (is_software_event(event)) return 1; if (event->pmu != leader_pmu || event->state < PERF_EVENT_STATE_OFF) return 1; if (event->state == PERF_EVENT_STATE_OFF && !event->attr.enable_on_exec) return 1; return armpmu->get_event_idx(hw_events, event) >= 0; }
166,009
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileObject, __construct) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_bool use_include_path = 0; char *p1, *p2; char *tmp_path; int tmp_path_len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); intern->u.file.open_mode = NULL; intern->u.file.open_mode_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|sbr!", &intern->file_name, &intern->file_name_len, &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { intern->u.file.open_mode = NULL; intern->file_name = NULL; zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (intern->u.file.open_mode == NULL) { intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == SUCCESS) { tmp_path_len = strlen(intern->u.file.stream->orig_path); if (tmp_path_len > 1 && IS_SLASH_AT(intern->u.file.stream->orig_path, tmp_path_len-1)) { tmp_path_len--; } tmp_path = estrndup(intern->u.file.stream->orig_path, tmp_path_len); p1 = strrchr(tmp_path, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(tmp_path, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - tmp_path; } else { intern->_path_len = 0; } efree(tmp_path); intern->_path = estrndup(intern->u.file.stream->orig_path, intern->_path_len); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplTempFileObject::__construct([int max_memory]) Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, __construct) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_bool use_include_path = 0; char *p1, *p2; char *tmp_path; int tmp_path_len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); intern->u.file.open_mode = NULL; intern->u.file.open_mode_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|sbr!", &intern->file_name, &intern->file_name_len, &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { intern->u.file.open_mode = NULL; intern->file_name = NULL; zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (intern->u.file.open_mode == NULL) { intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == SUCCESS) { tmp_path_len = strlen(intern->u.file.stream->orig_path); if (tmp_path_len > 1 && IS_SLASH_AT(intern->u.file.stream->orig_path, tmp_path_len-1)) { tmp_path_len--; } tmp_path = estrndup(intern->u.file.stream->orig_path, tmp_path_len); p1 = strrchr(tmp_path, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(tmp_path, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - tmp_path; } else { intern->_path_len = 0; } efree(tmp_path); intern->_path = estrndup(intern->u.file.stream->orig_path, intern->_path_len); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplTempFileObject::__construct([int max_memory])
167,049
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FrameLoader::Trace(blink::Visitor* visitor) { visitor->Trace(frame_); visitor->Trace(progress_tracker_); visitor->Trace(document_loader_); visitor->Trace(provisional_document_loader_); } Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener Spec PR: https://github.com/w3c/webappsec-csp/pull/358 Bug: 905301, 894228, 836148 Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a Reviewed-on: https://chromium-review.googlesource.com/c/1314633 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#610850} CWE ID: CWE-20
void FrameLoader::Trace(blink::Visitor* visitor) { visitor->Trace(frame_); visitor->Trace(progress_tracker_); visitor->Trace(document_loader_); visitor->Trace(provisional_document_loader_); visitor->Trace(last_origin_document_); }
173,059
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool LocalFrame::ShouldReuseDefaultView(const KURL& url) const { if (!Loader().StateMachine()->IsDisplayingInitialEmptyDocument()) return false; return GetDocument()->IsSecureTransitionTo(url); } Commit Message: Prevent sandboxed documents from reusing the default window Bug: 377995 Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541 Reviewed-on: https://chromium-review.googlesource.com/983558 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#567663} CWE ID: CWE-285
bool LocalFrame::ShouldReuseDefaultView(const KURL& url) const { bool LocalFrame::ShouldReuseDefaultView( const KURL& url, const ContentSecurityPolicy* csp) const { if (!Loader().StateMachine()->IsDisplayingInitialEmptyDocument()) return false; // The Window object should only be re-used if it is same-origin. // Since sandboxing turns the origin into an opaque origin it needs to also // be considered when deciding whether to reuse it. // Spec: // https://html.spec.whatwg.org/multipage/browsing-the-web.html#initialise-the-document-object if (csp && SecurityContext::IsSandboxed(kSandboxOrigin, csp->GetSandboxMask())) { return false; } return GetDocument()->IsSecureTransitionTo(url); }
173,196
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int may_ptrace_stop(void) { if (!likely(current->ptrace)) return 0; /* * Are we in the middle of do_coredump? * If so and our tracer is also part of the coredump stopping * is a deadlock situation, and pointless because our tracer * is dead so don't allow us to stop. * If SIGKILL was already sent before the caller unlocked * ->siglock we must see ->core_state != NULL. Otherwise it * is safe to enter schedule(). */ if (unlikely(current->mm->core_state) && unlikely(current->mm == current->parent->mm)) return 0; return 1; } Commit Message: ptrace: ensure arch_ptrace/ptrace_request can never race with SIGKILL putreg() assumes that the tracee is not running and pt_regs_access() can safely play with its stack. However a killed tracee can return from ptrace_stop() to the low-level asm code and do RESTORE_REST, this means that debugger can actually read/modify the kernel stack until the tracee does SAVE_REST again. set_task_blockstep() can race with SIGKILL too and in some sense this race is even worse, the very fact the tracee can be woken up breaks the logic. As Linus suggested we can clear TASK_WAKEKILL around the arch_ptrace() call, this ensures that nobody can ever wakeup the tracee while the debugger looks at it. Not only this fixes the mentioned problems, we can do some cleanups/simplifications in arch_ptrace() paths. Probably ptrace_unfreeze_traced() needs more callers, for example it makes sense to make the tracee killable for oom-killer before access_process_vm(). While at it, add the comment into may_ptrace_stop() to explain why ptrace_stop() still can't rely on SIGKILL and signal_pending_state(). Reported-by: Salman Qazi <[email protected]> Reported-by: Suleiman Souhlal <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Signed-off-by: Oleg Nesterov <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362
static inline int may_ptrace_stop(void) { if (!likely(current->ptrace)) return 0; /* * Are we in the middle of do_coredump? * If so and our tracer is also part of the coredump stopping * is a deadlock situation, and pointless because our tracer * is dead so don't allow us to stop. * If SIGKILL was already sent before the caller unlocked * ->siglock we must see ->core_state != NULL. Otherwise it * is safe to enter schedule(). * * This is almost outdated, a task with the pending SIGKILL can't * block in TASK_TRACED. But PTRACE_EVENT_EXIT can be reported * after SIGKILL was already dequeued. */ if (unlikely(current->mm->core_state) && unlikely(current->mm == current->parent->mm)) return 0; return 1; }
166,139
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: l2tp_proxy_auth_id_print(netdissect_options *ndo, const u_char *dat) { const uint16_t *ptr = (const uint16_t *)dat; ND_PRINT((ndo, "%u", EXTRACT_16BITS(ptr) & L2TP_PROXY_AUTH_ID_MASK)); } Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
l2tp_proxy_auth_id_print(netdissect_options *ndo, const u_char *dat) l2tp_proxy_auth_id_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; if (length < 2) { ND_PRINT((ndo, "AVP too short")); return; } ND_PRINT((ndo, "%u", EXTRACT_16BITS(ptr) & L2TP_PROXY_AUTH_ID_MASK)); }
167,899
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: HeadlessPrintManager::GetPrintParamsFromSettings( const HeadlessPrintSettings& settings) { printing::PrintSettings print_settings; print_settings.set_dpi(printing::kPointsPerInch); print_settings.set_should_print_backgrounds( settings.should_print_backgrounds); print_settings.set_scale_factor(settings.scale); print_settings.SetOrientation(settings.landscape); print_settings.set_display_header_footer(settings.display_header_footer); if (print_settings.display_header_footer()) { url::Replacements<char> url_sanitizer; url_sanitizer.ClearUsername(); url_sanitizer.ClearPassword(); std::string url = printing_rfh_->GetLastCommittedURL() .ReplaceComponents(url_sanitizer) .spec(); print_settings.set_url(base::UTF8ToUTF16(url)); } print_settings.set_margin_type(printing::CUSTOM_MARGINS); print_settings.SetCustomMargins(settings.margins_in_points); gfx::Rect printable_area_device_units(settings.paper_size_in_points); print_settings.SetPrinterPrintableArea(settings.paper_size_in_points, printable_area_device_units, true); auto print_params = std::make_unique<PrintMsg_PrintPages_Params>(); printing::RenderParamsFromPrintSettings(print_settings, &print_params->params); print_params->params.document_cookie = printing::PrintSettings::NewCookie(); return print_params; } Commit Message: DevTools: allow styling the page number element when printing over the protocol. Bug: none Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4 Reviewed-on: https://chromium-review.googlesource.com/809759 Commit-Queue: Pavel Feldman <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: Tom Sepez <[email protected]> Reviewed-by: Jianzhou Feng <[email protected]> Cr-Commit-Position: refs/heads/master@{#523966} CWE ID: CWE-20
HeadlessPrintManager::GetPrintParamsFromSettings( const HeadlessPrintSettings& settings) { printing::PrintSettings print_settings; print_settings.set_dpi(printing::kPointsPerInch); print_settings.set_should_print_backgrounds( settings.should_print_backgrounds); print_settings.set_scale_factor(settings.scale); print_settings.SetOrientation(settings.landscape); print_settings.set_display_header_footer(settings.display_header_footer); if (print_settings.display_header_footer()) { url::Replacements<char> url_sanitizer; url_sanitizer.ClearUsername(); url_sanitizer.ClearPassword(); std::string url = printing_rfh_->GetLastCommittedURL() .ReplaceComponents(url_sanitizer) .spec(); print_settings.set_url(base::UTF8ToUTF16(url)); } print_settings.set_margin_type(printing::CUSTOM_MARGINS); print_settings.SetCustomMargins(settings.margins_in_points); gfx::Rect printable_area_device_units(settings.paper_size_in_points); print_settings.SetPrinterPrintableArea(settings.paper_size_in_points, printable_area_device_units, true); auto print_params = std::make_unique<PrintMsg_PrintPages_Params>(); printing::RenderParamsFromPrintSettings(print_settings, &print_params->params); print_params->params.document_cookie = printing::PrintSettings::NewCookie(); print_params->params.header_template = base::UTF8ToUTF16(settings.header_template); print_params->params.footer_template = base::UTF8ToUTF16(settings.footer_template); return print_params; }
172,902
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(void) { FILE *f; char *tmpname; f = xfmkstemp(&tmpname, NULL); unlink(tmpname); free(tmpname); fclose(f); return EXIT_FAILURE; } Commit Message: chsh, chfn, vipw: fix filenames collision The utils when compiled WITHOUT libuser then mkostemp()ing "/etc/%s.XXXXXX" where the filename prefix is argv[0] basename. An attacker could repeatedly execute the util with modified argv[0] and after many many attempts mkostemp() may generate suffix which makes sense. The result maybe temporary file with name like rc.status ld.so.preload or krb5.keytab, etc. Note that distros usually use libuser based ch{sh,fn} or stuff from shadow-utils. It's probably very minor security bug. Addresses: CVE-2015-5224 Signed-off-by: Karel Zak <[email protected]> CWE ID: CWE-264
int main(void) { FILE *f; char *tmpname; f = xfmkstemp(&tmpname, NULL, "test"); unlink(tmpname); free(tmpname); fclose(f); return EXIT_FAILURE; }
168,872
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ip6_mroute_getsockopt(struct sock *sk, int optname, char __user *optval, int __user *optlen) { int olr; int val; struct net *net = sock_net(sk); struct mr6_table *mrt; mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT); if (!mrt) return -ENOENT; switch (optname) { case MRT6_VERSION: val = 0x0305; break; #ifdef CONFIG_IPV6_PIMSM_V2 case MRT6_PIM: val = mrt->mroute_do_pim; break; #endif case MRT6_ASSERT: val = mrt->mroute_do_assert; break; default: return -ENOPROTOOPT; } if (get_user(olr, optlen)) return -EFAULT; olr = min_t(int, olr, sizeof(int)); if (olr < 0) return -EINVAL; if (put_user(olr, optlen)) return -EFAULT; if (copy_to_user(optval, &val, olr)) return -EFAULT; return 0; } Commit Message: ipv6: check sk sk_type and protocol early in ip_mroute_set/getsockopt Commit 5e1859fbcc3c ("ipv4: ipmr: various fixes and cleanups") fixed the issue for ipv4 ipmr: ip_mroute_setsockopt() & ip_mroute_getsockopt() should not access/set raw_sk(sk)->ipmr_table before making sure the socket is a raw socket, and protocol is IGMP The same fix should be done for ipv6 ipmr as well. This patch can fix the panic caused by overwriting the same offset as ipmr_table as in raw_sk(sk) when accessing other type's socket by ip_mroute_setsockopt(). Signed-off-by: Xin Long <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
int ip6_mroute_getsockopt(struct sock *sk, int optname, char __user *optval, int __user *optlen) { int olr; int val; struct net *net = sock_net(sk); struct mr6_table *mrt; if (sk->sk_type != SOCK_RAW || inet_sk(sk)->inet_num != IPPROTO_ICMPV6) return -EOPNOTSUPP; mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT); if (!mrt) return -ENOENT; switch (optname) { case MRT6_VERSION: val = 0x0305; break; #ifdef CONFIG_IPV6_PIMSM_V2 case MRT6_PIM: val = mrt->mroute_do_pim; break; #endif case MRT6_ASSERT: val = mrt->mroute_do_assert; break; default: return -ENOPROTOOPT; } if (get_user(olr, optlen)) return -EFAULT; olr = min_t(int, olr, sizeof(int)); if (olr < 0) return -EINVAL; if (put_user(olr, optlen)) return -EFAULT; if (copy_to_user(optval, &val, olr)) return -EFAULT; return 0; }
169,857
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct ion_handle *ion_handle_get_by_id(struct ion_client *client, int id) { struct ion_handle *handle; mutex_lock(&client->lock); handle = idr_find(&client->idr, id); if (handle) ion_handle_get(handle); mutex_unlock(&client->lock); return handle ? handle : ERR_PTR(-EINVAL); } Commit Message: staging/android/ion : fix a race condition in the ion driver There is a use-after-free problem in the ion driver. This is caused by a race condition in the ion_ioctl() function. A handle has ref count of 1 and two tasks on different cpus calls ION_IOC_FREE simultaneously. cpu 0 cpu 1 ------------------------------------------------------- ion_handle_get_by_id() (ref == 2) ion_handle_get_by_id() (ref == 3) ion_free() (ref == 2) ion_handle_put() (ref == 1) ion_free() (ref == 0 so ion_handle_destroy() is called and the handle is freed.) ion_handle_put() is called and it decreases the slub's next free pointer The problem is detected as an unaligned access in the spin lock functions since it uses load exclusive instruction. In some cases it corrupts the slub's free pointer which causes a mis-aligned access to the next free pointer.(kmalloc returns a pointer like ffffc0745b4580aa). And it causes lots of other hard-to-debug problems. This symptom is caused since the first member in the ion_handle structure is the reference count and the ion driver decrements the reference after it has been freed. To fix this problem client->lock mutex is extended to protect all the codes that uses the handle. Signed-off-by: Eun Taik Lee <[email protected]> Reviewed-by: Laura Abbott <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-416
static struct ion_handle *ion_handle_get_by_id(struct ion_client *client, static struct ion_handle *ion_handle_get_by_id_nolock(struct ion_client *client, int id) { struct ion_handle *handle; handle = idr_find(&client->idr, id); if (handle) ion_handle_get(handle); return handle ? handle : ERR_PTR(-EINVAL); }
166,897
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: handle_ppp(netdissect_options *ndo, u_int proto, const u_char *p, int length) { if ((proto & 0xff00) == 0x7e00) { /* is this an escape code ? */ ppp_hdlc(ndo, p - 1, length); return; } switch (proto) { case PPP_LCP: /* fall through */ case PPP_IPCP: case PPP_OSICP: case PPP_MPLSCP: case PPP_IPV6CP: case PPP_CCP: case PPP_BACP: handle_ctrl_proto(ndo, proto, p, length); break; case PPP_ML: handle_mlppp(ndo, p, length); break; case PPP_CHAP: handle_chap(ndo, p, length); break; case PPP_PAP: handle_pap(ndo, p, length); break; case PPP_BAP: /* XXX: not yet completed */ handle_bap(ndo, p, length); break; case ETHERTYPE_IP: /*XXX*/ case PPP_VJNC: case PPP_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: /*XXX*/ case PPP_IPV6: ip6_print(ndo, p, length); break; case ETHERTYPE_IPX: /*XXX*/ case PPP_IPX: ipx_print(ndo, p, length); break; case PPP_OSI: isoclns_print(ndo, p, length, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; case PPP_COMP: ND_PRINT((ndo, "compressed PPP data")); break; default: ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto))); print_unknown_data(ndo, p, "\n\t", length); break; } } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
handle_ppp(netdissect_options *ndo, u_int proto, const u_char *p, int length) { if ((proto & 0xff00) == 0x7e00) { /* is this an escape code ? */ ppp_hdlc(ndo, p - 1, length); return; } switch (proto) { case PPP_LCP: /* fall through */ case PPP_IPCP: case PPP_OSICP: case PPP_MPLSCP: case PPP_IPV6CP: case PPP_CCP: case PPP_BACP: handle_ctrl_proto(ndo, proto, p, length); break; case PPP_ML: handle_mlppp(ndo, p, length); break; case PPP_CHAP: handle_chap(ndo, p, length); break; case PPP_PAP: handle_pap(ndo, p, length); break; case PPP_BAP: /* XXX: not yet completed */ handle_bap(ndo, p, length); break; case ETHERTYPE_IP: /*XXX*/ case PPP_VJNC: case PPP_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: /*XXX*/ case PPP_IPV6: ip6_print(ndo, p, length); break; case ETHERTYPE_IPX: /*XXX*/ case PPP_IPX: ipx_print(ndo, p, length); break; case PPP_OSI: isoclns_print(ndo, p, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; case PPP_COMP: ND_PRINT((ndo, "compressed PPP data")); break; default: ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto))); print_unknown_data(ndo, p, "\n\t", length); break; } }
167,956
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Chapters::Display::Parse( IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x05) // ChapterString ID { status = UnserializeString(pReader, pos, size, m_string); if (status) return status; } else if (id == 0x037C) // ChapterLanguage ID { status = UnserializeString(pReader, pos, size, m_language); if (status) return status; } else if (id == 0x037E) // ChapterCountry ID { status = UnserializeString(pReader, pos, size, m_country); if (status) return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } 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 Chapters::Display::Parse(
174,403
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Chapters::ExpandEditionsArray() { if (m_editions_size > m_editions_count) return true; // nothing else to do const int size = (m_editions_size == 0) ? 1 : 2 * m_editions_size; Edition* const editions = new (std::nothrow) Edition[size]; if (editions == NULL) return false; for (int idx = 0; idx < m_editions_count; ++idx) { m_editions[idx].ShallowCopy(editions[idx]); } delete[] m_editions; m_editions = editions; m_editions_size = size; return true; } 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
bool Chapters::ExpandEditionsArray() Edition& e = m_editions[m_editions_count++]; e.Init(); return e.Parse(m_pSegment->m_pReader, pos, size); } Chapters::Edition::Edition() {} Chapters::Edition::~Edition() {} int Chapters::Edition::GetAtomCount() const { return m_atoms_count; } const Chapters::Atom* Chapters::Edition::GetAtom(int index) const { if (index < 0) return NULL; if (index >= m_atoms_count) return NULL; return m_atoms + index; } void Chapters::Edition::Init() { m_atoms = NULL; m_atoms_size = 0; m_atoms_count = 0; } void Chapters::Edition::ShallowCopy(Edition& rhs) const { rhs.m_atoms = m_atoms; rhs.m_atoms_size = m_atoms_size; rhs.m_atoms_count = m_atoms_count; } void Chapters::Edition::Clear() { while (m_atoms_count > 0) { Atom& a = m_atoms[--m_atoms_count]; a.Clear(); } delete[] m_atoms; m_atoms = NULL; m_atoms_size = 0; } long Chapters::Edition::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x36) { // Atom ID status = ParseAtom(pReader, pos, size); if (status < 0) // error return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; }
174,276
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BrowserTabStripController::TabDetachedAt(TabContents* contents, int model_index) { hover_tab_selector_.CancelTabTransition(); tabstrip_->RemoveTabAt(model_index); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void BrowserTabStripController::TabDetachedAt(TabContents* contents, void BrowserTabStripController::TabDetachedAt(WebContents* contents, int model_index) { hover_tab_selector_.CancelTabTransition(); tabstrip_->RemoveTabAt(model_index); }
171,523
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: jbig2_decode_gray_scale_image(Jbig2Ctx *ctx, Jbig2Segment *segment, const byte *data, const size_t size, bool GSMMR, uint32_t GSW, uint32_t GSH, uint32_t GSBPP, bool GSUSESKIP, Jbig2Image *GSKIP, int GSTEMPLATE, Jbig2ArithCx *GB_stats) { uint8_t **GSVALS = NULL; size_t consumed_bytes = 0; int i, j, code, stride; int x, y; Jbig2Image **GSPLANES; Jbig2GenericRegionParams rparams; Jbig2WordStream *ws = NULL; Jbig2ArithState *as = NULL; /* allocate GSPLANES */ GSPLANES = jbig2_new(ctx, Jbig2Image *, GSBPP); if (GSPLANES == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate %d bytes for GSPLANES", GSBPP); return NULL; } for (i = 0; i < GSBPP; ++i) { GSPLANES[i] = jbig2_image_new(ctx, GSW, GSH); if (GSPLANES[i] == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate %dx%d image for GSPLANES", GSW, GSH); /* free already allocated */ for (j = i - 1; j >= 0; --j) { jbig2_image_release(ctx, GSPLANES[j]); } jbig2_free(ctx->allocator, GSPLANES); return NULL; } } } Commit Message: CWE ID: CWE-119
jbig2_decode_gray_scale_image(Jbig2Ctx *ctx, Jbig2Segment *segment, const byte *data, const size_t size, bool GSMMR, uint32_t GSW, uint32_t GSH, uint32_t GSBPP, bool GSUSESKIP, Jbig2Image *GSKIP, int GSTEMPLATE, Jbig2ArithCx *GB_stats) { uint8_t **GSVALS = NULL; size_t consumed_bytes = 0; uint32_t i, j, stride, x, y; int code; Jbig2Image **GSPLANES; Jbig2GenericRegionParams rparams; Jbig2WordStream *ws = NULL; Jbig2ArithState *as = NULL; /* allocate GSPLANES */ GSPLANES = jbig2_new(ctx, Jbig2Image *, GSBPP); if (GSPLANES == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate %d bytes for GSPLANES", GSBPP); return NULL; } for (i = 0; i < GSBPP; ++i) { GSPLANES[i] = jbig2_image_new(ctx, GSW, GSH); if (GSPLANES[i] == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate %dx%d image for GSPLANES", GSW, GSH); /* free already allocated */ for (j = i; j > 0;) jbig2_image_release(ctx, GSPLANES[--j]); jbig2_free(ctx->allocator, GSPLANES); return NULL; } } }
165,487
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct nfs4_state *nfs4_opendata_to_nfs4_state(struct nfs4_opendata *data) { struct inode *inode; struct nfs4_state *state = NULL; struct nfs_delegation *delegation; int ret; if (!data->rpc_done) { state = nfs4_try_open_cached(data); goto out; } ret = -EAGAIN; if (!(data->f_attr.valid & NFS_ATTR_FATTR)) goto err; inode = nfs_fhget(data->dir->d_sb, &data->o_res.fh, &data->f_attr); ret = PTR_ERR(inode); if (IS_ERR(inode)) goto err; ret = -ENOMEM; state = nfs4_get_open_state(inode, data->owner); if (state == NULL) goto err_put_inode; if (data->o_res.delegation_type != 0) { int delegation_flags = 0; rcu_read_lock(); delegation = rcu_dereference(NFS_I(inode)->delegation); if (delegation) delegation_flags = delegation->flags; rcu_read_unlock(); if ((delegation_flags & 1UL<<NFS_DELEGATION_NEED_RECLAIM) == 0) nfs_inode_set_delegation(state->inode, data->owner->so_cred, &data->o_res); else nfs_inode_reclaim_delegation(state->inode, data->owner->so_cred, &data->o_res); } update_open_stateid(state, &data->o_res.stateid, NULL, data->o_arg.open_flags); iput(inode); out: return state; err_put_inode: iput(inode); err: return ERR_PTR(ret); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static struct nfs4_state *nfs4_opendata_to_nfs4_state(struct nfs4_opendata *data) { struct inode *inode; struct nfs4_state *state = NULL; struct nfs_delegation *delegation; int ret; if (!data->rpc_done) { state = nfs4_try_open_cached(data); goto out; } ret = -EAGAIN; if (!(data->f_attr.valid & NFS_ATTR_FATTR)) goto err; inode = nfs_fhget(data->dir->d_sb, &data->o_res.fh, &data->f_attr); ret = PTR_ERR(inode); if (IS_ERR(inode)) goto err; ret = -ENOMEM; state = nfs4_get_open_state(inode, data->owner); if (state == NULL) goto err_put_inode; if (data->o_res.delegation_type != 0) { int delegation_flags = 0; rcu_read_lock(); delegation = rcu_dereference(NFS_I(inode)->delegation); if (delegation) delegation_flags = delegation->flags; rcu_read_unlock(); if ((delegation_flags & 1UL<<NFS_DELEGATION_NEED_RECLAIM) == 0) nfs_inode_set_delegation(state->inode, data->owner->so_cred, &data->o_res); else nfs_inode_reclaim_delegation(state->inode, data->owner->so_cred, &data->o_res); } update_open_stateid(state, &data->o_res.stateid, NULL, data->o_arg.fmode); iput(inode); out: return state; err_put_inode: iput(inode); err: return ERR_PTR(ret); }
165,701
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, int linesize_align[AV_NUM_DATA_POINTERS]) { int i; int w_align = 1; int h_align = 1; AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt); if (desc) { w_align = 1 << desc->log2_chroma_w; h_align = 1 << desc->log2_chroma_h; } switch (s->pix_fmt) { case AV_PIX_FMT_YUV420P: case AV_PIX_FMT_YUYV422: case AV_PIX_FMT_YVYU422: case AV_PIX_FMT_UYVY422: case AV_PIX_FMT_YUV422P: case AV_PIX_FMT_YUV440P: case AV_PIX_FMT_YUV444P: case AV_PIX_FMT_GBRP: case AV_PIX_FMT_GBRAP: case AV_PIX_FMT_GRAY8: case AV_PIX_FMT_GRAY16BE: case AV_PIX_FMT_GRAY16LE: case AV_PIX_FMT_YUVJ420P: case AV_PIX_FMT_YUVJ422P: case AV_PIX_FMT_YUVJ440P: case AV_PIX_FMT_YUVJ444P: case AV_PIX_FMT_YUVA420P: case AV_PIX_FMT_YUVA422P: case AV_PIX_FMT_YUVA444P: case AV_PIX_FMT_YUV420P9LE: case AV_PIX_FMT_YUV420P9BE: case AV_PIX_FMT_YUV420P10LE: case AV_PIX_FMT_YUV420P10BE: case AV_PIX_FMT_YUV420P12LE: case AV_PIX_FMT_YUV420P12BE: case AV_PIX_FMT_YUV420P14LE: case AV_PIX_FMT_YUV420P14BE: case AV_PIX_FMT_YUV420P16LE: case AV_PIX_FMT_YUV420P16BE: case AV_PIX_FMT_YUVA420P9LE: case AV_PIX_FMT_YUVA420P9BE: case AV_PIX_FMT_YUVA420P10LE: case AV_PIX_FMT_YUVA420P10BE: case AV_PIX_FMT_YUVA420P16LE: case AV_PIX_FMT_YUVA420P16BE: case AV_PIX_FMT_YUV422P9LE: case AV_PIX_FMT_YUV422P9BE: case AV_PIX_FMT_YUV422P10LE: case AV_PIX_FMT_YUV422P10BE: case AV_PIX_FMT_YUV422P12LE: case AV_PIX_FMT_YUV422P12BE: case AV_PIX_FMT_YUV422P14LE: case AV_PIX_FMT_YUV422P14BE: case AV_PIX_FMT_YUV422P16LE: case AV_PIX_FMT_YUV422P16BE: case AV_PIX_FMT_YUVA422P9LE: case AV_PIX_FMT_YUVA422P9BE: case AV_PIX_FMT_YUVA422P10LE: case AV_PIX_FMT_YUVA422P10BE: case AV_PIX_FMT_YUVA422P16LE: case AV_PIX_FMT_YUVA422P16BE: case AV_PIX_FMT_YUV440P10LE: case AV_PIX_FMT_YUV440P10BE: case AV_PIX_FMT_YUV440P12LE: case AV_PIX_FMT_YUV440P12BE: case AV_PIX_FMT_YUV444P9LE: case AV_PIX_FMT_YUV444P9BE: case AV_PIX_FMT_YUV444P10LE: case AV_PIX_FMT_YUV444P10BE: case AV_PIX_FMT_YUV444P12LE: case AV_PIX_FMT_YUV444P12BE: case AV_PIX_FMT_YUV444P14LE: case AV_PIX_FMT_YUV444P14BE: case AV_PIX_FMT_YUV444P16LE: case AV_PIX_FMT_YUV444P16BE: case AV_PIX_FMT_YUVA444P9LE: case AV_PIX_FMT_YUVA444P9BE: case AV_PIX_FMT_YUVA444P10LE: case AV_PIX_FMT_YUVA444P10BE: case AV_PIX_FMT_YUVA444P16LE: case AV_PIX_FMT_YUVA444P16BE: case AV_PIX_FMT_GBRP9LE: case AV_PIX_FMT_GBRP9BE: case AV_PIX_FMT_GBRP10LE: case AV_PIX_FMT_GBRP10BE: case AV_PIX_FMT_GBRP12LE: case AV_PIX_FMT_GBRP12BE: case AV_PIX_FMT_GBRP14LE: case AV_PIX_FMT_GBRP14BE: case AV_PIX_FMT_GBRP16LE: case AV_PIX_FMT_GBRP16BE: case AV_PIX_FMT_GBRAP12LE: case AV_PIX_FMT_GBRAP12BE: case AV_PIX_FMT_GBRAP16LE: case AV_PIX_FMT_GBRAP16BE: w_align = 16; //FIXME assume 16 pixel per macroblock h_align = 16 * 2; // interlaced needs 2 macroblocks height break; case AV_PIX_FMT_YUV411P: case AV_PIX_FMT_YUVJ411P: case AV_PIX_FMT_UYYVYY411: w_align = 32; h_align = 16 * 2; break; case AV_PIX_FMT_YUV410P: if (s->codec_id == AV_CODEC_ID_SVQ1) { w_align = 64; h_align = 64; } break; case AV_PIX_FMT_RGB555: if (s->codec_id == AV_CODEC_ID_RPZA) { w_align = 4; h_align = 4; } break; case AV_PIX_FMT_PAL8: case AV_PIX_FMT_BGR8: case AV_PIX_FMT_RGB8: if (s->codec_id == AV_CODEC_ID_SMC || s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } if (s->codec_id == AV_CODEC_ID_JV) { w_align = 8; h_align = 8; } break; case AV_PIX_FMT_BGR24: if ((s->codec_id == AV_CODEC_ID_MSZH) || (s->codec_id == AV_CODEC_ID_ZLIB)) { w_align = 4; h_align = 4; } break; case AV_PIX_FMT_RGB24: if (s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } break; default: break; } if (s->codec_id == AV_CODEC_ID_IFF_ILBM) { w_align = FFMAX(w_align, 8); } *width = FFALIGN(*width, w_align); *height = FFALIGN(*height, h_align); if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) { *height += 2; *width = FFMAX(*width, 32); } for (i = 0; i < 4; i++) linesize_align[i] = STRIDE_ALIGN; } Commit Message: avcodec/utils: correct align value for interplay Fixes out of array access Fixes: 452/fuzz-1-ffmpeg_VIDEO_AV_CODEC_ID_INTERPLAY_VIDEO_fuzzer Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-787
void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, int linesize_align[AV_NUM_DATA_POINTERS]) { int i; int w_align = 1; int h_align = 1; AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt); if (desc) { w_align = 1 << desc->log2_chroma_w; h_align = 1 << desc->log2_chroma_h; } switch (s->pix_fmt) { case AV_PIX_FMT_YUV420P: case AV_PIX_FMT_YUYV422: case AV_PIX_FMT_YVYU422: case AV_PIX_FMT_UYVY422: case AV_PIX_FMT_YUV422P: case AV_PIX_FMT_YUV440P: case AV_PIX_FMT_YUV444P: case AV_PIX_FMT_GBRP: case AV_PIX_FMT_GBRAP: case AV_PIX_FMT_GRAY8: case AV_PIX_FMT_GRAY16BE: case AV_PIX_FMT_GRAY16LE: case AV_PIX_FMT_YUVJ420P: case AV_PIX_FMT_YUVJ422P: case AV_PIX_FMT_YUVJ440P: case AV_PIX_FMT_YUVJ444P: case AV_PIX_FMT_YUVA420P: case AV_PIX_FMT_YUVA422P: case AV_PIX_FMT_YUVA444P: case AV_PIX_FMT_YUV420P9LE: case AV_PIX_FMT_YUV420P9BE: case AV_PIX_FMT_YUV420P10LE: case AV_PIX_FMT_YUV420P10BE: case AV_PIX_FMT_YUV420P12LE: case AV_PIX_FMT_YUV420P12BE: case AV_PIX_FMT_YUV420P14LE: case AV_PIX_FMT_YUV420P14BE: case AV_PIX_FMT_YUV420P16LE: case AV_PIX_FMT_YUV420P16BE: case AV_PIX_FMT_YUVA420P9LE: case AV_PIX_FMT_YUVA420P9BE: case AV_PIX_FMT_YUVA420P10LE: case AV_PIX_FMT_YUVA420P10BE: case AV_PIX_FMT_YUVA420P16LE: case AV_PIX_FMT_YUVA420P16BE: case AV_PIX_FMT_YUV422P9LE: case AV_PIX_FMT_YUV422P9BE: case AV_PIX_FMT_YUV422P10LE: case AV_PIX_FMT_YUV422P10BE: case AV_PIX_FMT_YUV422P12LE: case AV_PIX_FMT_YUV422P12BE: case AV_PIX_FMT_YUV422P14LE: case AV_PIX_FMT_YUV422P14BE: case AV_PIX_FMT_YUV422P16LE: case AV_PIX_FMT_YUV422P16BE: case AV_PIX_FMT_YUVA422P9LE: case AV_PIX_FMT_YUVA422P9BE: case AV_PIX_FMT_YUVA422P10LE: case AV_PIX_FMT_YUVA422P10BE: case AV_PIX_FMT_YUVA422P16LE: case AV_PIX_FMT_YUVA422P16BE: case AV_PIX_FMT_YUV440P10LE: case AV_PIX_FMT_YUV440P10BE: case AV_PIX_FMT_YUV440P12LE: case AV_PIX_FMT_YUV440P12BE: case AV_PIX_FMT_YUV444P9LE: case AV_PIX_FMT_YUV444P9BE: case AV_PIX_FMT_YUV444P10LE: case AV_PIX_FMT_YUV444P10BE: case AV_PIX_FMT_YUV444P12LE: case AV_PIX_FMT_YUV444P12BE: case AV_PIX_FMT_YUV444P14LE: case AV_PIX_FMT_YUV444P14BE: case AV_PIX_FMT_YUV444P16LE: case AV_PIX_FMT_YUV444P16BE: case AV_PIX_FMT_YUVA444P9LE: case AV_PIX_FMT_YUVA444P9BE: case AV_PIX_FMT_YUVA444P10LE: case AV_PIX_FMT_YUVA444P10BE: case AV_PIX_FMT_YUVA444P16LE: case AV_PIX_FMT_YUVA444P16BE: case AV_PIX_FMT_GBRP9LE: case AV_PIX_FMT_GBRP9BE: case AV_PIX_FMT_GBRP10LE: case AV_PIX_FMT_GBRP10BE: case AV_PIX_FMT_GBRP12LE: case AV_PIX_FMT_GBRP12BE: case AV_PIX_FMT_GBRP14LE: case AV_PIX_FMT_GBRP14BE: case AV_PIX_FMT_GBRP16LE: case AV_PIX_FMT_GBRP16BE: case AV_PIX_FMT_GBRAP12LE: case AV_PIX_FMT_GBRAP12BE: case AV_PIX_FMT_GBRAP16LE: case AV_PIX_FMT_GBRAP16BE: w_align = 16; //FIXME assume 16 pixel per macroblock h_align = 16 * 2; // interlaced needs 2 macroblocks height break; case AV_PIX_FMT_YUV411P: case AV_PIX_FMT_YUVJ411P: case AV_PIX_FMT_UYYVYY411: w_align = 32; h_align = 16 * 2; break; case AV_PIX_FMT_YUV410P: if (s->codec_id == AV_CODEC_ID_SVQ1) { w_align = 64; h_align = 64; } break; case AV_PIX_FMT_RGB555: if (s->codec_id == AV_CODEC_ID_RPZA) { w_align = 4; h_align = 4; } if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) { w_align = 8; h_align = 8; } break; case AV_PIX_FMT_PAL8: case AV_PIX_FMT_BGR8: case AV_PIX_FMT_RGB8: if (s->codec_id == AV_CODEC_ID_SMC || s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } if (s->codec_id == AV_CODEC_ID_JV || s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) { w_align = 8; h_align = 8; } break; case AV_PIX_FMT_BGR24: if ((s->codec_id == AV_CODEC_ID_MSZH) || (s->codec_id == AV_CODEC_ID_ZLIB)) { w_align = 4; h_align = 4; } break; case AV_PIX_FMT_RGB24: if (s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } break; default: break; } if (s->codec_id == AV_CODEC_ID_IFF_ILBM) { w_align = FFMAX(w_align, 8); } *width = FFALIGN(*width, w_align); *height = FFALIGN(*height, h_align); if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) { *height += 2; *width = FFMAX(*width, 32); } for (i = 0; i < 4; i++) linesize_align[i] = STRIDE_ALIGN; }
168,246
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ResourceRequestBlockedReason BaseFetchContext::CanRequest( Resource::Type type, const ResourceRequest& resource_request, const KURL& url, const ResourceLoaderOptions& options, SecurityViolationReportingPolicy reporting_policy, FetchParameters::OriginRestriction origin_restriction, ResourceRequest::RedirectStatus redirect_status) const { ResourceRequestBlockedReason blocked_reason = CanRequestInternal(type, resource_request, url, options, reporting_policy, origin_restriction, redirect_status); if (blocked_reason != ResourceRequestBlockedReason::kNone && reporting_policy == SecurityViolationReportingPolicy::kReport) { DispatchDidBlockRequest(resource_request, options.initiator_info, blocked_reason); } return blocked_reason; } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
ResourceRequestBlockedReason BaseFetchContext::CanRequest( Resource::Type type, const ResourceRequest& resource_request, const KURL& url, const ResourceLoaderOptions& options, SecurityViolationReportingPolicy reporting_policy, FetchParameters::OriginRestriction origin_restriction, ResourceRequest::RedirectStatus redirect_status) const { ResourceRequestBlockedReason blocked_reason = CanRequestInternal(type, resource_request, url, options, reporting_policy, origin_restriction, redirect_status); if (blocked_reason != ResourceRequestBlockedReason::kNone && reporting_policy == SecurityViolationReportingPolicy::kReport) { DispatchDidBlockRequest(resource_request, options.initiator_info, blocked_reason, type); } return blocked_reason; }
172,472
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view, scoped_ptr<Delegate> delegate) : content::RenderViewObserver(render_view), content::RenderViewObserverTracker<PrintWebViewHelper>(render_view), reset_prep_frame_view_(false), is_print_ready_metafile_sent_(false), ignore_css_margins_(false), is_scripted_printing_blocked_(false), notify_browser_of_print_failure_(true), print_for_preview_(false), delegate_(delegate.Pass()), print_node_in_progress_(false), is_loading_(false), is_scripted_preview_delayed_(false), weak_ptr_factory_(this) { if (!delegate_->IsPrintPreviewEnabled()) DisablePreview(); } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID:
PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view, scoped_ptr<Delegate> delegate) : content::RenderViewObserver(render_view), content::RenderViewObserverTracker<PrintWebViewHelper>(render_view), reset_prep_frame_view_(false), is_print_ready_metafile_sent_(false), ignore_css_margins_(false), is_scripted_printing_blocked_(false), notify_browser_of_print_failure_(true), print_for_preview_(false), delegate_(delegate.Pass()), print_node_in_progress_(false), is_loading_(false), is_scripted_preview_delayed_(false), ipc_nesting_level_(0), weak_ptr_factory_(this) { if (!delegate_->IsPrintPreviewEnabled()) DisablePreview(); }
171,878
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PassRefPtr<SharedBuffer> readFile(const char* fileName) { String filePath = Platform::current()->unitTestSupport()->webKitRootDir(); filePath.append(fileName); return Platform::current()->unitTestSupport()->readFromFile(filePath); } Commit Message: Fix handling of broken GIFs with weird frame sizes Code didn't handle well if a GIF frame has dimension greater than the "screen" dimension. This will break deferred image decoding. This change reports the size as final only when the first frame is encountered. Added a test to verify this behavior. Frame size reported by the decoder should be constant. BUG=437651 [email protected], [email protected] Review URL: https://codereview.chromium.org/813943003 git-svn-id: svn://svn.chromium.org/blink/trunk@188423 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
PassRefPtr<SharedBuffer> readFile(const char* fileName) const char decodersTestingDir[] = "Source/platform/image-decoders/testing"; const char layoutTestResourcesDir[] = "LayoutTests/fast/images/resources"; const char webTestsDataDir[] = "Source/web/tests/data"; PassRefPtr<SharedBuffer> readFile(const char* dir, const char* fileName) { String filePath = Platform::current()->unitTestSupport()->webKitRootDir(); filePath.append("/"); filePath.append(dir); filePath.append("/"); filePath.append(fileName); return Platform::current()->unitTestSupport()->readFromFile(filePath); }
172,026
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebContents* TabsCaptureVisibleTabFunction::GetWebContentsForID( int window_id, std::string* error) { Browser* browser = NULL; if (!GetBrowserFromWindowID(chrome_details_, window_id, &browser, error)) return nullptr; WebContents* contents = browser->tab_strip_model()->GetActiveWebContents(); if (!contents) { *error = "No active web contents to capture"; return nullptr; } if (!extension()->permissions_data()->CanCaptureVisiblePage( SessionTabHelper::IdForTab(contents).id(), error)) { return nullptr; } return contents; } Commit Message: [Extensions] Restrict tabs.captureVisibleTab() Modify the permissions for tabs.captureVisibleTab(). Instead of just checking for <all_urls> and assuming its safe, do the following: - If the page is a "normal" web page (e.g., http/https), allow the capture if the extension has activeTab granted or <all_urls>. - If the page is a file page (file:///), allow the capture if the extension has file access *and* either of the <all_urls> or activeTab permissions. - If the page is a chrome:// page, allow the capture only if the extension has activeTab granted. Bug: 810220 Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304 Reviewed-on: https://chromium-review.googlesource.com/981195 Commit-Queue: Devlin <[email protected]> Reviewed-by: Karan Bhatia <[email protected]> Cr-Commit-Position: refs/heads/master@{#548891} CWE ID: CWE-20
WebContents* TabsCaptureVisibleTabFunction::GetWebContentsForID( int window_id, std::string* error) { Browser* browser = NULL; if (!GetBrowserFromWindowID(chrome_details_, window_id, &browser, error)) return nullptr; WebContents* contents = browser->tab_strip_model()->GetActiveWebContents(); if (!contents) { *error = "No active web contents to capture"; return nullptr; } if (!extension()->permissions_data()->CanCaptureVisiblePage( contents->GetLastCommittedURL(), extension(), SessionTabHelper::IdForTab(contents).id(), error)) { return nullptr; } return contents; }
173,229
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftAVC::internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR params) { int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: { return internalSetBitrateParams( (const OMX_VIDEO_PARAM_BITRATETYPE *)params); } case OMX_IndexParamVideoAvc: { OMX_VIDEO_PARAM_AVCTYPE *avcType = (OMX_VIDEO_PARAM_AVCTYPE *)params; if (avcType->nPortIndex != 1) { return OMX_ErrorUndefined; } mEntropyMode = 0; if (OMX_TRUE == avcType->bEntropyCodingCABAC) mEntropyMode = 1; if ((avcType->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) && avcType->nPFrames) { mBframes = avcType->nBFrames / avcType->nPFrames; } mIInterval = avcType->nPFrames + avcType->nBFrames; if (OMX_VIDEO_AVCLoopFilterDisable == avcType->eLoopFilterMode) mDisableDeblkLevel = 4; if (avcType->nRefFrames != 1 || avcType->bUseHadamard != OMX_TRUE || avcType->nRefIdx10ActiveMinus1 != 0 || avcType->nRefIdx11ActiveMinus1 != 0 || avcType->bWeightedPPrediction != OMX_FALSE || avcType->bconstIpred != OMX_FALSE || avcType->bDirect8x8Inference != OMX_FALSE || avcType->bDirectSpatialTemporal != OMX_FALSE || avcType->nCabacInitIdc != 0) { return OMX_ErrorUndefined; } if (OK != ConvertOmxAvcLevelToAvcSpecLevel(avcType->eLevel, &mAVCEncLevel)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAVC::internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR params) { int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE *bitRate = (OMX_VIDEO_PARAM_BITRATETYPE *)params; if (!isValidOMXParam(bitRate)) { return OMX_ErrorBadParameter; } return internalSetBitrateParams(bitRate); } case OMX_IndexParamVideoAvc: { OMX_VIDEO_PARAM_AVCTYPE *avcType = (OMX_VIDEO_PARAM_AVCTYPE *)params; if (!isValidOMXParam(avcType)) { return OMX_ErrorBadParameter; } if (avcType->nPortIndex != 1) { return OMX_ErrorUndefined; } mEntropyMode = 0; if (OMX_TRUE == avcType->bEntropyCodingCABAC) mEntropyMode = 1; if ((avcType->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) && avcType->nPFrames) { mBframes = avcType->nBFrames / avcType->nPFrames; } mIInterval = avcType->nPFrames + avcType->nBFrames; if (OMX_VIDEO_AVCLoopFilterDisable == avcType->eLoopFilterMode) mDisableDeblkLevel = 4; if (avcType->nRefFrames != 1 || avcType->bUseHadamard != OMX_TRUE || avcType->nRefIdx10ActiveMinus1 != 0 || avcType->nRefIdx11ActiveMinus1 != 0 || avcType->bWeightedPPrediction != OMX_FALSE || avcType->bconstIpred != OMX_FALSE || avcType->bDirect8x8Inference != OMX_FALSE || avcType->bDirectSpatialTemporal != OMX_FALSE || avcType->nCabacInitIdc != 0) { return OMX_ErrorUndefined; } if (OK != ConvertOmxAvcLevelToAvcSpecLevel(avcType->eLevel, &mAVCEncLevel)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalSetParameter(index, params); } }
174,201
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t CameraService::dump(int fd, const Vector<String16>& args) { String8 result; if (checkCallingPermission(String16("android.permission.DUMP")) == false) { result.appendFormat("Permission Denial: " "can't dump CameraService from pid=%d, uid=%d\n", getCallingPid(), getCallingUid()); write(fd, result.string(), result.size()); } else { bool locked = tryLock(mServiceLock); if (!locked) { result.append("CameraService may be deadlocked\n"); write(fd, result.string(), result.size()); } bool hasClient = false; if (!mModule) { result = String8::format("No camera module available!\n"); write(fd, result.string(), result.size()); return NO_ERROR; } result = String8::format("Camera module HAL API version: 0x%x\n", mModule->common.hal_api_version); result.appendFormat("Camera module API version: 0x%x\n", mModule->common.module_api_version); result.appendFormat("Camera module name: %s\n", mModule->common.name); result.appendFormat("Camera module author: %s\n", mModule->common.author); result.appendFormat("Number of camera devices: %d\n\n", mNumberOfCameras); write(fd, result.string(), result.size()); for (int i = 0; i < mNumberOfCameras; i++) { result = String8::format("Camera %d static information:\n", i); camera_info info; status_t rc = mModule->get_camera_info(i, &info); if (rc != OK) { result.appendFormat(" Error reading static information!\n"); write(fd, result.string(), result.size()); } else { result.appendFormat(" Facing: %s\n", info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT"); result.appendFormat(" Orientation: %d\n", info.orientation); int deviceVersion; if (mModule->common.module_api_version < CAMERA_MODULE_API_VERSION_2_0) { deviceVersion = CAMERA_DEVICE_API_VERSION_1_0; } else { deviceVersion = info.device_version; } result.appendFormat(" Device version: 0x%x\n", deviceVersion); if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) { result.appendFormat(" Device static metadata:\n"); write(fd, result.string(), result.size()); dump_indented_camera_metadata(info.static_camera_characteristics, fd, 2, 4); } else { write(fd, result.string(), result.size()); } } sp<BasicClient> client = mClient[i].promote(); if (client == 0) { result = String8::format(" Device is closed, no client instance\n"); write(fd, result.string(), result.size()); continue; } hasClient = true; result = String8::format(" Device is open. Client instance dump:\n"); write(fd, result.string(), result.size()); client->dump(fd, args); } if (!hasClient) { result = String8::format("\nNo active camera clients yet.\n"); write(fd, result.string(), result.size()); } if (locked) mServiceLock.unlock(); write(fd, "\n", 1); camera3::CameraTraces::dump(fd, args); int n = args.size(); for (int i = 0; i + 1 < n; i++) { String16 verboseOption("-v"); if (args[i] == verboseOption) { String8 levelStr(args[i+1]); int level = atoi(levelStr.string()); result = String8::format("\nSetting log level to %d.\n", level); setLogLevel(level); write(fd, result.string(), result.size()); } } } return NO_ERROR; } Commit Message: Camera: Disallow dumping clients directly Camera service dumps should only be initiated through ICameraService::dump. Bug: 26265403 Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803 CWE ID: CWE-264
status_t CameraService::dump(int fd, const Vector<String16>& args) { String8 result; if (checkCallingPermission(String16("android.permission.DUMP")) == false) { result.appendFormat("Permission Denial: " "can't dump CameraService from pid=%d, uid=%d\n", getCallingPid(), getCallingUid()); write(fd, result.string(), result.size()); } else { bool locked = tryLock(mServiceLock); if (!locked) { result.append("CameraService may be deadlocked\n"); write(fd, result.string(), result.size()); } bool hasClient = false; if (!mModule) { result = String8::format("No camera module available!\n"); write(fd, result.string(), result.size()); return NO_ERROR; } result = String8::format("Camera module HAL API version: 0x%x\n", mModule->common.hal_api_version); result.appendFormat("Camera module API version: 0x%x\n", mModule->common.module_api_version); result.appendFormat("Camera module name: %s\n", mModule->common.name); result.appendFormat("Camera module author: %s\n", mModule->common.author); result.appendFormat("Number of camera devices: %d\n\n", mNumberOfCameras); write(fd, result.string(), result.size()); for (int i = 0; i < mNumberOfCameras; i++) { result = String8::format("Camera %d static information:\n", i); camera_info info; status_t rc = mModule->get_camera_info(i, &info); if (rc != OK) { result.appendFormat(" Error reading static information!\n"); write(fd, result.string(), result.size()); } else { result.appendFormat(" Facing: %s\n", info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT"); result.appendFormat(" Orientation: %d\n", info.orientation); int deviceVersion; if (mModule->common.module_api_version < CAMERA_MODULE_API_VERSION_2_0) { deviceVersion = CAMERA_DEVICE_API_VERSION_1_0; } else { deviceVersion = info.device_version; } result.appendFormat(" Device version: 0x%x\n", deviceVersion); if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) { result.appendFormat(" Device static metadata:\n"); write(fd, result.string(), result.size()); dump_indented_camera_metadata(info.static_camera_characteristics, fd, 2, 4); } else { write(fd, result.string(), result.size()); } } sp<BasicClient> client = mClient[i].promote(); if (client == 0) { result = String8::format(" Device is closed, no client instance\n"); write(fd, result.string(), result.size()); continue; } hasClient = true; result = String8::format(" Device is open. Client instance dump:\n"); write(fd, result.string(), result.size()); client->dumpClient(fd, args); } if (!hasClient) { result = String8::format("\nNo active camera clients yet.\n"); write(fd, result.string(), result.size()); } if (locked) mServiceLock.unlock(); write(fd, "\n", 1); camera3::CameraTraces::dump(fd, args); int n = args.size(); for (int i = 0; i + 1 < n; i++) { String16 verboseOption("-v"); if (args[i] == verboseOption) { String8 levelStr(args[i+1]); int level = atoi(levelStr.string()); result = String8::format("\nSetting log level to %d.\n", level); setLogLevel(level); write(fd, result.string(), result.size()); } } } return NO_ERROR; }
173,936
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char *get_object( FILE *fp, int obj_id, const xref_t *xref, size_t *size, int *is_stream) { static const int blk_sz = 256; int i, total_sz, read_sz, n_blks, search, stream; size_t obj_sz; char *c, *data; long start; const xref_entry_t *entry; if (size) *size = 0; if (is_stream) *is_stream = 0; start = ftell(fp); /* Find object */ entry = NULL; for (i=0; i<xref->n_entries; i++) if (xref->entries[i].obj_id == obj_id) { entry = &xref->entries[i]; break; } if (!entry) return NULL; /* Jump to object start */ fseek(fp, entry->offset, SEEK_SET); /* Initial allocate */ obj_sz = 0; /* Bytes in object */ total_sz = 0; /* Bytes read in */ n_blks = 1; data = malloc(blk_sz * n_blks); memset(data, 0, blk_sz * n_blks); /* Suck in data */ stream = 0; while ((read_sz = fread(data+total_sz, 1, blk_sz-1, fp)) && !ferror(fp)) { total_sz += read_sz; *(data + total_sz) = '\0'; if (total_sz + blk_sz >= (blk_sz * n_blks)) data = realloc(data, blk_sz * (++n_blks)); search = total_sz - read_sz; if (search < 0) search = 0; if ((c = strstr(data + search, "endobj"))) { *(c + strlen("endobj") + 1) = '\0'; obj_sz = (void *)strstr(data + search, "endobj") - (void *)data; obj_sz += strlen("endobj") + 1; break; } else if (strstr(data, "stream")) stream = 1; } clearerr(fp); fseek(fp, start, SEEK_SET); if (size) *size = obj_sz; if (is_stream) *is_stream = stream; return data; } 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
static char *get_object( FILE *fp, int obj_id, const xref_t *xref, size_t *size, int *is_stream) { static const int blk_sz = 256; int i, total_sz, read_sz, n_blks, search, stream; size_t obj_sz; char *c, *data; long start; const xref_entry_t *entry; if (size) *size = 0; if (is_stream) *is_stream = 0; start = ftell(fp); /* Find object */ entry = NULL; for (i=0; i<xref->n_entries; i++) if (xref->entries[i].obj_id == obj_id) { entry = &xref->entries[i]; break; } if (!entry) return NULL; /* Jump to object start */ fseek(fp, entry->offset, SEEK_SET); /* Initial allocate */ obj_sz = 0; /* Bytes in object */ total_sz = 0; /* Bytes read in */ n_blks = 1; data = safe_calloc(blk_sz * n_blks); /* Suck in data */ stream = 0; while ((read_sz = fread(data+total_sz, 1, blk_sz-1, fp)) && !ferror(fp)) { total_sz += read_sz; *(data + total_sz) = '\0'; if (total_sz + blk_sz >= (blk_sz * n_blks)) data = realloc(data, blk_sz * (++n_blks)); search = total_sz - read_sz; if (search < 0) search = 0; if ((c = strstr(data + search, "endobj"))) { *(c + strlen("endobj") + 1) = '\0'; obj_sz = (void *)strstr(data + search, "endobj") - (void *)data; obj_sz += strlen("endobj") + 1; break; } else if (strstr(data, "stream")) stream = 1; } clearerr(fp); fseek(fp, start, SEEK_SET); if (size) *size = obj_sz; if (is_stream) *is_stream = stream; return data; }
169,568
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GCInfoTable::Init() { CHECK(!g_gc_info_table); Resize(); } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362
void GCInfoTable::Init() { GCInfoTable::GCInfoTable() { CHECK(!table_); table_ = reinterpret_cast<GCInfo const**>(base::AllocPages( nullptr, MaxTableSize(), base::kPageAllocationGranularity, base::PageInaccessible)); CHECK(table_); Resize(); }
173,135
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ZEND_API void zend_object_store_ctor_failed(zval *zobject TSRMLS_DC) { zend_object_handle handle = Z_OBJ_HANDLE_P(zobject); zend_object_store_bucket *obj_bucket = &EG(objects_store).object_buckets[handle]; obj_bucket->bucket.obj.handlers = Z_OBJ_HT_P(zobject);; obj_bucket->destructor_called = 1; } Commit Message: Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction CWE ID: CWE-119
ZEND_API void zend_object_store_ctor_failed(zval *zobject TSRMLS_DC) { zend_object_handle handle = Z_OBJ_HANDLE_P(zobject); zend_object_store_bucket *obj_bucket = &EG(objects_store).object_buckets[handle]; obj_bucket->bucket.obj.handlers = Z_OBJ_HT_P(zobject); obj_bucket->destructor_called = 1; }
166,938
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: unsigned long long Track::GetCodecDelay() const { return m_info.codecDelay; } 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
unsigned long long Track::GetCodecDelay() const
174,292
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: XListFonts( register Display *dpy, _Xconst char *pattern, /* null-terminated */ int maxNames, int *actualCount) /* RETURN */ { register long nbytes; register unsigned i; register int length; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; xListFontsReply rep; register xListFontsReq *req; unsigned long rlen = 0; LockDisplay(dpy); GetReq(ListFonts, req); req->maxNames = maxNames; nbytes = req->nbytes = pattern ? strlen (pattern) : 0; req->length += (nbytes + 3) >> 2; _XSend (dpy, pattern, nbytes); /* use _XSend instead of Data, since following _XReply will flush buffer */ if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) { *actualCount = 0; UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } if (rep.nFonts) { flist = Xmalloc (rep.nFonts * sizeof(char *)); if (rep.length < (INT_MAX >> 2)) { rlen = rep.length << 2; ch = Xmalloc(rlen + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); *actualCount = 0; UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, rlen); /* * unpack into null terminated strings. */ chend = ch + (rlen + 1); length = *(unsigned char *)ch; *ch = 1; /* make sure it is non-zero for XFreeFontNames */ for (i = 0; i < rep.nFonts; i++) { if (ch + length < chend) { flist[i] = ch + 1; /* skip over length */ ch += length + 1; /* find next length ... */ length = *(unsigned char *)ch; *ch = '\0'; /* and replace with null-termination */ count++; } else flist[i] = NULL; } } *actualCount = count; for (names = list+1; *names; names++) Xfree (*names); } Commit Message: CWE ID: CWE-787
XListFonts( register Display *dpy, _Xconst char *pattern, /* null-terminated */ int maxNames, int *actualCount) /* RETURN */ { register long nbytes; register unsigned i; register int length; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; xListFontsReply rep; register xListFontsReq *req; unsigned long rlen = 0; LockDisplay(dpy); GetReq(ListFonts, req); req->maxNames = maxNames; nbytes = req->nbytes = pattern ? strlen (pattern) : 0; req->length += (nbytes + 3) >> 2; _XSend (dpy, pattern, nbytes); /* use _XSend instead of Data, since following _XReply will flush buffer */ if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) { *actualCount = 0; UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } if (rep.nFonts) { flist = Xmalloc (rep.nFonts * sizeof(char *)); if (rep.length > 0 && rep.length < (INT_MAX >> 2)) { rlen = rep.length << 2; ch = Xmalloc(rlen + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); *actualCount = 0; UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, rlen); /* * unpack into null terminated strings. */ chend = ch + (rlen + 1); length = *(unsigned char *)ch; *ch = 1; /* make sure it is non-zero for XFreeFontNames */ for (i = 0; i < rep.nFonts; i++) { if (ch + length < chend) { flist[i] = ch + 1; /* skip over length */ ch += length + 1; /* find next length ... */ if (ch <= chend) { length = *(unsigned char *)ch; *ch = '\0'; /* and replace with null-termination */ count++; } else { Xfree(flist); flist = NULL; count = 0; break; } } else { Xfree(flist); flist = NULL; count = 0; break; } } } *actualCount = count; for (names = list+1; *names; names++) Xfree (*names); }
164,923
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ScreenPositionController::ConvertHostPointToRelativeToRootWindow( aura::Window* root_window, const aura::Window::Windows& root_windows, gfx::Point* point, aura::Window** target_root) { DCHECK(!root_window->parent()); gfx::Point point_in_root(*point); root_window->GetHost()->ConvertPointFromHost(&point_in_root); *target_root = root_window; *point = point_in_root; #if defined(USE_X11) || defined(USE_OZONE) if (!root_window->GetHost()->GetBounds().Contains(*point)) { gfx::Point location_in_native(point_in_root); root_window->GetHost()->ConvertPointToNativeScreen(&location_in_native); for (size_t i = 0; i < root_windows.size(); ++i) { aura::WindowTreeHost* host = root_windows[i]->GetHost(); const gfx::Rect native_bounds = host->GetBounds(); if (native_bounds.Contains(location_in_native)) { *target_root = root_windows[i]; *point = location_in_native; host->ConvertPointFromNativeScreen(point); break; } } } #else NOTIMPLEMENTED(); #endif } Commit Message: Use the host coordinate when comparing to host window bounds. I somehow overlooked this and the test was not strict enough to catch this. BUG=521919 TEST=Updated ScreenPositionControllerTest.ConvertHostPointToScreenHiDPI so that it fails without the patch. Review URL: https://codereview.chromium.org/1293373002 Cr-Commit-Position: refs/heads/master@{#344186} CWE ID: CWE-399
void ScreenPositionController::ConvertHostPointToRelativeToRootWindow( aura::Window* root_window, const aura::Window::Windows& root_windows, gfx::Point* point, aura::Window** target_root) { DCHECK(!root_window->parent()); gfx::Point point_in_root(*point); root_window->GetHost()->ConvertPointFromHost(&point_in_root); #if defined(USE_X11) || defined(USE_OZONE) gfx::Rect host_bounds(root_window->GetHost()->GetBounds().size()); if (!host_bounds.Contains(*point)) { gfx::Point location_in_native(point_in_root); root_window->GetHost()->ConvertPointToNativeScreen(&location_in_native); for (size_t i = 0; i < root_windows.size(); ++i) { aura::WindowTreeHost* host = root_windows[i]->GetHost(); const gfx::Rect native_bounds = host->GetBounds(); if (native_bounds.Contains(location_in_native)) { *target_root = root_windows[i]; *point = location_in_native; host->ConvertPointFromNativeScreen(point); return; } } } #endif *target_root = root_window; *point = point_in_root; }
171,711
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int iscsi_add_notunderstood_response( char *key, char *value, struct iscsi_param_list *param_list) { struct iscsi_extra_response *extra_response; if (strlen(value) > VALUE_MAXLEN) { pr_err("Value for notunderstood key \"%s\" exceeds %d," " protocol error.\n", key, VALUE_MAXLEN); return -1; } extra_response = kzalloc(sizeof(struct iscsi_extra_response), GFP_KERNEL); if (!extra_response) { pr_err("Unable to allocate memory for" " struct iscsi_extra_response.\n"); return -1; } INIT_LIST_HEAD(&extra_response->er_list); strncpy(extra_response->key, key, strlen(key) + 1); strncpy(extra_response->value, NOTUNDERSTOOD, strlen(NOTUNDERSTOOD) + 1); list_add_tail(&extra_response->er_list, &param_list->extra_response_list); return 0; } Commit Message: iscsi-target: fix heap buffer overflow on error If a key was larger than 64 bytes, as checked by iscsi_check_key(), the error response packet, generated by iscsi_add_notunderstood_response(), would still attempt to copy the entire key into the packet, overflowing the structure on the heap. Remote preauthentication kernel memory corruption was possible if a target was configured and listening on the network. CVE-2013-2850 Signed-off-by: Kees Cook <[email protected]> Cc: [email protected] Signed-off-by: Nicholas Bellinger <[email protected]> CWE ID: CWE-119
static int iscsi_add_notunderstood_response( char *key, char *value, struct iscsi_param_list *param_list) { struct iscsi_extra_response *extra_response; if (strlen(value) > VALUE_MAXLEN) { pr_err("Value for notunderstood key \"%s\" exceeds %d," " protocol error.\n", key, VALUE_MAXLEN); return -1; } extra_response = kzalloc(sizeof(struct iscsi_extra_response), GFP_KERNEL); if (!extra_response) { pr_err("Unable to allocate memory for" " struct iscsi_extra_response.\n"); return -1; } INIT_LIST_HEAD(&extra_response->er_list); strlcpy(extra_response->key, key, sizeof(extra_response->key)); strlcpy(extra_response->value, NOTUNDERSTOOD, sizeof(extra_response->value)); list_add_tail(&extra_response->er_list, &param_list->extra_response_list); return 0; }
166,050
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AXNodeObject::isMultiSelectable() const { const AtomicString& ariaMultiSelectable = getAttribute(aria_multiselectableAttr); if (equalIgnoringCase(ariaMultiSelectable, "true")) return true; if (equalIgnoringCase(ariaMultiSelectable, "false")) return false; return isHTMLSelectElement(getNode()) && toHTMLSelectElement(*getNode()).isMultiple(); } 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::isMultiSelectable() const { const AtomicString& ariaMultiSelectable = getAttribute(aria_multiselectableAttr); if (equalIgnoringASCIICase(ariaMultiSelectable, "true")) return true; if (equalIgnoringASCIICase(ariaMultiSelectable, "false")) return false; return isHTMLSelectElement(getNode()) && toHTMLSelectElement(*getNode()).isMultiple(); }
171,917
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info, int texel_size,ExceptionInfo *exception) { register ssize_t i; MagickOffsetType offset; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); } Commit Message: Moved EOF check. CWE ID: CWE-20
static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info, int texel_size,ExceptionInfo *exception) { register ssize_t i; MagickOffsetType offset; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); }
170,154
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GDataFileSystem::OnGetDocumentEntry(const FilePath& cache_file_path, const GetFileFromCacheParams& params, GDataErrorCode status, scoped_ptr<base::Value> data) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); GDataFileError error = util::GDataToGDataFileError(status); scoped_ptr<GDataEntry> fresh_entry; if (error == GDATA_FILE_OK) { scoped_ptr<DocumentEntry> doc_entry(DocumentEntry::ExtractAndParse(*data)); if (doc_entry.get()) { fresh_entry.reset( GDataEntry::FromDocumentEntry(NULL, doc_entry.get(), directory_service_.get())); } if (!fresh_entry.get() || !fresh_entry->AsGDataFile()) { LOG(ERROR) << "Got invalid entry from server for " << params.resource_id; error = GDATA_FILE_ERROR_FAILED; } } if (error != GDATA_FILE_OK) { if (!params.get_file_callback.is_null()) { params.get_file_callback.Run(error, cache_file_path, params.mime_type, REGULAR_FILE); } return; } GURL content_url = fresh_entry->content_url(); int64 file_size = fresh_entry->file_info().size; DCHECK_EQ(params.resource_id, fresh_entry->resource_id()); scoped_ptr<GDataFile> fresh_entry_as_file( fresh_entry.release()->AsGDataFile()); directory_service_->RefreshFile(fresh_entry_as_file.Pass()); bool* has_enough_space = new bool(false); util::PostBlockingPoolSequencedTaskAndReply( FROM_HERE, blocking_task_runner_, base::Bind(&GDataCache::FreeDiskSpaceIfNeededFor, base::Unretained(cache_), file_size, has_enough_space), base::Bind(&GDataFileSystem::StartDownloadFileIfEnoughSpace, ui_weak_ptr_, params, content_url, cache_file_path, base::Owned(has_enough_space))); } Commit Message: Remove parent* arg from GDataEntry ctor. * Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry. * Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry. * Add GDataDirectoryService::FromDocumentEntry and use this everywhere. * Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and CreateGDataDirectory. Make GDataEntry ctor protected. BUG=141494 TEST=unit tests. Review URL: https://chromiumcodereview.appspot.com/10854083 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void GDataFileSystem::OnGetDocumentEntry(const FilePath& cache_file_path, const GetFileFromCacheParams& params, GDataErrorCode status, scoped_ptr<base::Value> data) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); GDataFileError error = util::GDataToGDataFileError(status); scoped_ptr<GDataEntry> fresh_entry; if (error == GDATA_FILE_OK) { scoped_ptr<DocumentEntry> doc_entry(DocumentEntry::ExtractAndParse(*data)); if (doc_entry.get()) { fresh_entry.reset(directory_service_->FromDocumentEntry(doc_entry.get())); } if (!fresh_entry.get() || !fresh_entry->AsGDataFile()) { LOG(ERROR) << "Got invalid entry from server for " << params.resource_id; error = GDATA_FILE_ERROR_FAILED; } } if (error != GDATA_FILE_OK) { if (!params.get_file_callback.is_null()) { params.get_file_callback.Run(error, cache_file_path, params.mime_type, REGULAR_FILE); } return; } GURL content_url = fresh_entry->content_url(); int64 file_size = fresh_entry->file_info().size; DCHECK_EQ(params.resource_id, fresh_entry->resource_id()); scoped_ptr<GDataFile> fresh_entry_as_file( fresh_entry.release()->AsGDataFile()); directory_service_->RefreshFile(fresh_entry_as_file.Pass()); bool* has_enough_space = new bool(false); util::PostBlockingPoolSequencedTaskAndReply( FROM_HERE, blocking_task_runner_, base::Bind(&GDataCache::FreeDiskSpaceIfNeededFor, base::Unretained(cache_), file_size, has_enough_space), base::Bind(&GDataFileSystem::StartDownloadFileIfEnoughSpace, ui_weak_ptr_, params, content_url, cache_file_path, base::Owned(has_enough_space))); }
171,482
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL) { if (origin && BlobURL::getOrigin(url) == "null") originMap()->add(url.string(), origin); if (isMainThread()) blobRegistry().registerBlobURL(url, srcURL); else { OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, srcURL)); callOnMainThread(&registerBlobURLFromTask, context.leakPtr()); } } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL) void BlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL) { if (origin && BlobURL::getOrigin(url) == "null") originMap()->add(url.string(), origin); if (isMainThread()) { if (WebBlobRegistry* registry = blobRegistry()) registry->registerBlobURL(url, srcURL); } else { OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, srcURL)); callOnMainThread(&registerBlobURLFromTask, context.leakPtr()); } }
170,685
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ssl3_get_new_session_ticket(SSL *s) { int ok, al, ret = 0, ticklen; long n; const unsigned char *p; unsigned char *d; n = s->method->ssl_get_message(s, SSL3_ST_CR_SESSION_TICKET_A, SSL3_ST_CR_SESSION_TICKET_B, SSL3_MT_NEWSESSION_TICKET, 16384, &ok); if (!ok) return ((int)n); if (n < 6) { /* need at least ticket_lifetime_hint + ticket length */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH); goto f_err; } p = d = (unsigned char *)s->init_msg; n2l(p, s->session->tlsext_tick_lifetime_hint); n2s(p, ticklen); /* ticket_lifetime_hint + ticket_length + ticket */ if (ticklen + 6 != n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH); goto f_err; } OPENSSL_free(s->session->tlsext_tick); s->session->tlsext_ticklen = 0; s->session->tlsext_tick = OPENSSL_malloc(ticklen); if (!s->session->tlsext_tick) { SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE); goto err; } memcpy(s->session->tlsext_tick, p, ticklen); s->session->tlsext_ticklen = ticklen; /* * There are two ways to detect a resumed ticket session. One is to set * an appropriate session ID and then the server must return a match in * ServerHello. This allows the normal client session ID matching to work * and we know much earlier that the ticket has been accepted. The * other way is to set zero length session ID when the ticket is * presented and rely on the handshake to determine session resumption. * We choose the former approach because this fits in with assumptions * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is * SHA256 is disabled) hash of the ticket. */ EVP_Digest(p, ticklen, s->session->session_id, &s->session->session_id_length, EVP_sha256(), NULL); ret = 1; return (ret); f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: s->state = SSL_ST_ERR; return (-1); } Commit Message: Fix race condition in NewSessionTicket If a NewSessionTicket is received by a multi-threaded client when attempting to reuse a previous ticket then a race condition can occur potentially leading to a double free of the ticket data. CVE-2015-1791 This also fixes RT#3808 where a session ID is changed for a session already in the client session cache. Since the session ID is the key to the cache this breaks the cache access. Parts of this patch were inspired by this Akamai change: https://github.com/akamai/openssl/commit/c0bf69a791239ceec64509f9f19fcafb2461b0d3 Reviewed-by: Rich Salz <[email protected]> CWE ID: CWE-362
int ssl3_get_new_session_ticket(SSL *s) { int ok, al, ret = 0, ticklen; long n; const unsigned char *p; unsigned char *d; n = s->method->ssl_get_message(s, SSL3_ST_CR_SESSION_TICKET_A, SSL3_ST_CR_SESSION_TICKET_B, SSL3_MT_NEWSESSION_TICKET, 16384, &ok); if (!ok) return ((int)n); if (n < 6) { /* need at least ticket_lifetime_hint + ticket length */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH); goto f_err; } p = d = (unsigned char *)s->init_msg; if (s->session->session_id_length > 0) { int i = s->session_ctx->session_cache_mode; SSL_SESSION *new_sess; /* * We reused an existing session, so we need to replace it with a new * one */ if (i & SSL_SESS_CACHE_CLIENT) { /* * Remove the old session from the cache */ if (i & SSL_SESS_CACHE_NO_INTERNAL_STORE) { if (s->session_ctx->remove_session_cb != NULL) s->session_ctx->remove_session_cb(s->session_ctx, s->session); } else { /* We carry on if this fails */ SSL_CTX_remove_session(s->session_ctx, s->session); } } if ((new_sess = ssl_session_dup(s->session, 0)) == 0) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE); goto f_err; } SSL_SESSION_free(s->session); s->session = new_sess; } n2l(p, s->session->tlsext_tick_lifetime_hint); n2s(p, ticklen); /* ticket_lifetime_hint + ticket_length + ticket */ if (ticklen + 6 != n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH); goto f_err; } OPENSSL_free(s->session->tlsext_tick); s->session->tlsext_ticklen = 0; s->session->tlsext_tick = OPENSSL_malloc(ticklen); if (!s->session->tlsext_tick) { SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE); goto err; } memcpy(s->session->tlsext_tick, p, ticklen); s->session->tlsext_ticklen = ticklen; /* * There are two ways to detect a resumed ticket session. One is to set * an appropriate session ID and then the server must return a match in * ServerHello. This allows the normal client session ID matching to work * and we know much earlier that the ticket has been accepted. The * other way is to set zero length session ID when the ticket is * presented and rely on the handshake to determine session resumption. * We choose the former approach because this fits in with assumptions * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is * SHA256 is disabled) hash of the ticket. */ EVP_Digest(p, ticklen, s->session->session_id, &s->session->session_id_length, EVP_sha256(), NULL); ret = 1; return (ret); f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: s->state = SSL_ST_ERR; return (-1); }
166,691
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: plan_a (char const *filename) { char const *s; char const *lim; char const **ptr; char *buffer; lin iline; size_t size = instat.st_size; /* Fail if the file size doesn't fit in a size_t, or if storage isn't available. */ if (! (size == instat.st_size && (buffer = malloc (size ? size : (size_t) 1)))) return false; /* Read the input file, but don't bother reading it if it's empty. When creating files, the files do not actually exist. */ if (size) { if (S_ISREG (instat.st_mode)) { int ifd = safe_open (filename, O_RDONLY|binary_transput, 0); size_t buffered = 0, n; if (ifd < 0) pfatal ("can't open file %s", quotearg (filename)); /* Some non-POSIX hosts exaggerate st_size in text mode; or the file may have shrunk! */ size = buffered; break; } if (n == (size_t) -1) { /* Perhaps size is too large for this host. */ close (ifd); free (buffer); return false; } buffered += n; } if (close (ifd) != 0) read_fatal (); } Commit Message: CWE ID: CWE-59
plan_a (char const *filename) { char const *s; char const *lim; char const **ptr; char *buffer; lin iline; size_t size = instat.st_size; /* Fail if the file size doesn't fit in a size_t, or if storage isn't available. */ if (! (size == instat.st_size && (buffer = malloc (size ? size : (size_t) 1)))) return false; /* Read the input file, but don't bother reading it if it's empty. When creating files, the files do not actually exist. */ if (size) { if (S_ISREG (instat.st_mode)) { int flags = O_RDONLY | binary_transput; size_t buffered = 0, n; int ifd; if (! follow_symlinks) flags |= O_NOFOLLOW; ifd = safe_open (filename, flags, 0); if (ifd < 0) pfatal ("can't open file %s", quotearg (filename)); /* Some non-POSIX hosts exaggerate st_size in text mode; or the file may have shrunk! */ size = buffered; break; } if (n == (size_t) -1) { /* Perhaps size is too large for this host. */ close (ifd); free (buffer); return false; } buffered += n; } if (close (ifd) != 0) read_fatal (); }
164,685
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SYSCALL_DEFINE5(add_key, const char __user *, _type, const char __user *, _description, const void __user *, _payload, size_t, plen, key_serial_t, ringid) { key_ref_t keyring_ref, key_ref; char type[32], *description; void *payload; long ret; ret = -EINVAL; if (plen > 1024 * 1024 - 1) goto error; /* draw all the data into kernel space */ ret = key_get_type_from_user(type, _type, sizeof(type)); if (ret < 0) goto error; description = NULL; if (_description) { description = strndup_user(_description, KEY_MAX_DESC_SIZE); if (IS_ERR(description)) { ret = PTR_ERR(description); goto error; } if (!*description) { kfree(description); description = NULL; } else if ((description[0] == '.') && (strncmp(type, "keyring", 7) == 0)) { ret = -EPERM; goto error2; } } /* pull the payload in if one was supplied */ payload = NULL; if (_payload) { ret = -ENOMEM; payload = kvmalloc(plen, GFP_KERNEL); if (!payload) goto error2; ret = -EFAULT; if (copy_from_user(payload, _payload, plen) != 0) goto error3; } /* find the target keyring (which must be writable) */ keyring_ref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE); if (IS_ERR(keyring_ref)) { ret = PTR_ERR(keyring_ref); goto error3; } /* create or update the requested key and add it to the target * keyring */ key_ref = key_create_or_update(keyring_ref, type, description, payload, plen, KEY_PERM_UNDEF, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key_ref)) { ret = key_ref_to_ptr(key_ref)->serial; key_ref_put(key_ref); } else { ret = PTR_ERR(key_ref); } key_ref_put(keyring_ref); error3: kvfree(payload); error2: kfree(description); error: return ret; } Commit Message: KEYS: fix dereferencing NULL payload with nonzero length sys_add_key() and the KEYCTL_UPDATE operation of sys_keyctl() allowed a NULL payload with nonzero length to be passed to the key type's ->preparse(), ->instantiate(), and/or ->update() methods. Various key types including asymmetric, cifs.idmap, cifs.spnego, and pkcs7_test did not handle this case, allowing an unprivileged user to trivially cause a NULL pointer dereference (kernel oops) if one of these key types was present. Fix it by doing the copy_from_user() when 'plen' is nonzero rather than when '_payload' is non-NULL, causing the syscall to fail with EFAULT as expected when an invalid buffer is specified. Cc: [email protected] # 2.6.10+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Signed-off-by: James Morris <[email protected]> CWE ID: CWE-476
SYSCALL_DEFINE5(add_key, const char __user *, _type, const char __user *, _description, const void __user *, _payload, size_t, plen, key_serial_t, ringid) { key_ref_t keyring_ref, key_ref; char type[32], *description; void *payload; long ret; ret = -EINVAL; if (plen > 1024 * 1024 - 1) goto error; /* draw all the data into kernel space */ ret = key_get_type_from_user(type, _type, sizeof(type)); if (ret < 0) goto error; description = NULL; if (_description) { description = strndup_user(_description, KEY_MAX_DESC_SIZE); if (IS_ERR(description)) { ret = PTR_ERR(description); goto error; } if (!*description) { kfree(description); description = NULL; } else if ((description[0] == '.') && (strncmp(type, "keyring", 7) == 0)) { ret = -EPERM; goto error2; } } /* pull the payload in if one was supplied */ payload = NULL; if (plen) { ret = -ENOMEM; payload = kvmalloc(plen, GFP_KERNEL); if (!payload) goto error2; ret = -EFAULT; if (copy_from_user(payload, _payload, plen) != 0) goto error3; } /* find the target keyring (which must be writable) */ keyring_ref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE); if (IS_ERR(keyring_ref)) { ret = PTR_ERR(keyring_ref); goto error3; } /* create or update the requested key and add it to the target * keyring */ key_ref = key_create_or_update(keyring_ref, type, description, payload, plen, KEY_PERM_UNDEF, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key_ref)) { ret = key_ref_to_ptr(key_ref)->serial; key_ref_put(key_ref); } else { ret = PTR_ERR(key_ref); } key_ref_put(keyring_ref); error3: kvfree(payload); error2: kfree(description); error: return ret; }
167,726
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int pppol2tp_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct l2tp_session *session; struct l2tp_tunnel *tunnel; int val, len; int err; struct pppol2tp_session *ps; if (level != SOL_PPPOL2TP) return udp_prot.getsockopt(sk, level, optname, optval, optlen); if (get_user(len, optlen)) return -EFAULT; len = min_t(unsigned int, len, sizeof(int)); if (len < 0) return -EINVAL; err = -ENOTCONN; if (sk->sk_user_data == NULL) goto end; /* Get the session context */ err = -EBADF; session = pppol2tp_sock_to_session(sk); if (session == NULL) goto end; /* Special case: if session_id == 0x0000, treat as operation on tunnel */ ps = l2tp_session_priv(session); if ((session->session_id == 0) && (session->peer_session_id == 0)) { err = -EBADF; tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock); if (tunnel == NULL) goto end_put_sess; err = pppol2tp_tunnel_getsockopt(sk, tunnel, optname, &val); sock_put(ps->tunnel_sock); } else err = pppol2tp_session_getsockopt(sk, session, optname, &val); err = -EFAULT; if (put_user(len, optlen)) goto end_put_sess; if (copy_to_user((void __user *) optval, &val, len)) goto end_put_sess; err = 0; end_put_sess: sock_put(sk); end: return err; } Commit Message: net/l2tp: don't fall back on UDP [get|set]sockopt The l2tp [get|set]sockopt() code has fallen back to the UDP functions for socket option levels != SOL_PPPOL2TP since day one, but that has never actually worked, since the l2tp socket isn't an inet socket. As David Miller points out: "If we wanted this to work, it'd have to look up the tunnel and then use tunnel->sk, but I wonder how useful that would be" Since this can never have worked so nobody could possibly have depended on that functionality, just remove the broken code and return -EINVAL. Reported-by: Sasha Levin <[email protected]> Acked-by: James Chapman <[email protected]> Acked-by: David Miller <[email protected]> Cc: Phil Turnbull <[email protected]> Cc: Vegard Nossum <[email protected]> Cc: Willy Tarreau <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
static int pppol2tp_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct l2tp_session *session; struct l2tp_tunnel *tunnel; int val, len; int err; struct pppol2tp_session *ps; if (level != SOL_PPPOL2TP) return -EINVAL; if (get_user(len, optlen)) return -EFAULT; len = min_t(unsigned int, len, sizeof(int)); if (len < 0) return -EINVAL; err = -ENOTCONN; if (sk->sk_user_data == NULL) goto end; /* Get the session context */ err = -EBADF; session = pppol2tp_sock_to_session(sk); if (session == NULL) goto end; /* Special case: if session_id == 0x0000, treat as operation on tunnel */ ps = l2tp_session_priv(session); if ((session->session_id == 0) && (session->peer_session_id == 0)) { err = -EBADF; tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock); if (tunnel == NULL) goto end_put_sess; err = pppol2tp_tunnel_getsockopt(sk, tunnel, optname, &val); sock_put(ps->tunnel_sock); } else err = pppol2tp_session_getsockopt(sk, session, optname, &val); err = -EFAULT; if (put_user(len, optlen)) goto end_put_sess; if (copy_to_user((void __user *) optval, &val, len)) goto end_put_sess; err = 0; end_put_sess: sock_put(sk); end: return err; }
166,286
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Ins_GETVARIATION( TT_ExecContext exc, FT_Long* args ) { FT_UInt num_axes = exc->face->blend->num_axis; FT_Fixed* coords = exc->face->blend->normalizedcoords; FT_UInt i; if ( BOUNDS( num_axes, exc->stackSize + 1 - exc->top ) ) { exc->error = FT_THROW( Stack_Overflow ); return; } for ( i = 0; i < num_axes; i++ ) args[i] = coords[i] >> 2; /* convert 16.16 to 2.14 format */ } Commit Message: CWE ID: CWE-476
Ins_GETVARIATION( TT_ExecContext exc, FT_Long* args ) { FT_UInt num_axes = exc->face->blend->num_axis; FT_Fixed* coords = exc->face->blend->normalizedcoords; FT_UInt i; if ( BOUNDS( num_axes, exc->stackSize + 1 - exc->top ) ) { exc->error = FT_THROW( Stack_Overflow ); return; } if ( coords ) { for ( i = 0; i < num_axes; i++ ) args[i] = coords[i] >> 2; /* convert 16.16 to 2.14 format */ } else { for ( i = 0; i < num_axes; i++ ) args[i] = 0; } }
165,021
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HostCache::RecordSet(SetOutcome outcome, base::TimeTicks now, const Entry* old_entry, const Entry& new_entry) { CACHE_HISTOGRAM_ENUM("Set", outcome, MAX_SET_OUTCOME); switch (outcome) { case SET_INSERT: case SET_UPDATE_VALID: break; case SET_UPDATE_STALE: { EntryStaleness stale; old_entry->GetStaleness(now, network_changes_, &stale); CACHE_HISTOGRAM_TIME("UpdateStale.ExpiredBy", stale.expired_by); CACHE_HISTOGRAM_COUNT("UpdateStale.NetworkChanges", stale.network_changes); CACHE_HISTOGRAM_COUNT("UpdateStale.StaleHits", stale.stale_hits); if (old_entry->error() == OK && new_entry.error() == OK) { AddressListDeltaType delta = FindAddressListDeltaType( old_entry->addresses(), new_entry.addresses()); RecordUpdateStale(delta, stale); } break; } case MAX_SET_OUTCOME: NOTREACHED(); break; } } Commit Message: Add PersistenceDelegate to HostCache PersistenceDelegate is a new interface for persisting the contents of the HostCache. This commit includes the interface itself, the logic in HostCache for interacting with it, and a mock implementation of the interface for testing. It does not include support for immediate data removal since that won't be needed for the currently planned use case. BUG=605149 Review-Url: https://codereview.chromium.org/2943143002 Cr-Commit-Position: refs/heads/master@{#481015} CWE ID:
void HostCache::RecordSet(SetOutcome outcome, base::TimeTicks now, const Entry* old_entry, const Entry& new_entry, AddressListDeltaType delta) { CACHE_HISTOGRAM_ENUM("Set", outcome, MAX_SET_OUTCOME); switch (outcome) { case SET_INSERT: case SET_UPDATE_VALID: break; case SET_UPDATE_STALE: { EntryStaleness stale; old_entry->GetStaleness(now, network_changes_, &stale); CACHE_HISTOGRAM_TIME("UpdateStale.ExpiredBy", stale.expired_by); CACHE_HISTOGRAM_COUNT("UpdateStale.NetworkChanges", stale.network_changes); CACHE_HISTOGRAM_COUNT("UpdateStale.StaleHits", stale.stale_hits); if (old_entry->error() == OK && new_entry.error() == OK) { RecordUpdateStale(delta, stale); } break; } case MAX_SET_OUTCOME: NOTREACHED(); break; } }
172,008
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void EglRenderingVDAClient::CreateDecoder() { CHECK(decoder_deleted()); #if defined(OS_WIN) scoped_refptr<DXVAVideoDecodeAccelerator> decoder = new DXVAVideoDecodeAccelerator(this, base::GetCurrentProcessHandle()); #else // OS_WIN scoped_refptr<OmxVideoDecodeAccelerator> decoder = new OmxVideoDecodeAccelerator(this); decoder->SetEglState(egl_display(), egl_context()); #endif // OS_WIN decoder_ = decoder.release(); SetState(CS_DECODER_SET); if (decoder_deleted()) return; media::VideoCodecProfile profile = media::H264PROFILE_BASELINE; if (profile_ != -1) profile = static_cast<media::VideoCodecProfile>(profile_); CHECK(decoder_->Initialize(profile)); } 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 EglRenderingVDAClient::CreateDecoder() { CHECK(decoder_deleted()); #if defined(OS_WIN) scoped_refptr<DXVAVideoDecodeAccelerator> decoder = new DXVAVideoDecodeAccelerator(this); #else // OS_WIN scoped_refptr<OmxVideoDecodeAccelerator> decoder = new OmxVideoDecodeAccelerator(this); decoder->SetEglState(egl_display(), egl_context()); #endif // OS_WIN decoder_ = decoder.release(); SetState(CS_DECODER_SET); if (decoder_deleted()) return; media::VideoCodecProfile profile = media::H264PROFILE_BASELINE; if (profile_ != -1) profile = static_cast<media::VideoCodecProfile>(profile_); CHECK(decoder_->Initialize(profile)); }
170,943
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: check_1_6_dummy(kadm5_principal_ent_t entry, long mask, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char **passptr) { int i; char *password = *passptr; /* Old-style randkey operations disallowed tickets to start. */ if (!(mask & KADM5_ATTRIBUTES) || !(entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX)) return; /* The 1.6 dummy password was the octets 1..255. */ for (i = 0; (unsigned char) password[i] == i + 1; i++); if (password[i] != '\0' || i != 255) return; /* This will make the caller use a random password instead. */ *passptr = NULL; } Commit Message: Null pointer deref in kadmind [CVE-2012-1013] The fix for #6626 could cause kadmind to dereference a null pointer if a create-principal request contains no password but does contain the KRB5_KDB_DISALLOW_ALL_TIX flag (e.g. "addprinc -randkey -allow_tix name"). Only clients authorized to create principals can trigger the bug. Fix the bug by testing for a null password in check_1_6_dummy. CVSSv2 vector: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:O/RC:C [[email protected]: Minor style change and commit message] ticket: 7152 target_version: 1.10.2 tags: pullup CWE ID:
check_1_6_dummy(kadm5_principal_ent_t entry, long mask, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char **passptr) { int i; char *password = *passptr; /* Old-style randkey operations disallowed tickets to start. */ if (password == NULL || !(mask & KADM5_ATTRIBUTES) || !(entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX)) return; /* The 1.6 dummy password was the octets 1..255. */ for (i = 0; (unsigned char) password[i] == i + 1; i++); if (password[i] != '\0' || i != 255) return; /* This will make the caller use a random password instead. */ *passptr = NULL; }
165,646
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void TearDownTestCase() { vpx_free(input_ - 1); input_ = NULL; vpx_free(output_); output_ = NULL; } 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 TearDownTestCase() { vpx_free(input_ - 1); input_ = NULL; vpx_free(output_); output_ = NULL; vpx_free(output_ref_); output_ref_ = NULL; #if CONFIG_VP9_HIGHBITDEPTH vpx_free(input16_ - 1); input16_ = NULL; vpx_free(output16_); output16_ = NULL; vpx_free(output16_ref_); output16_ref_ = NULL; #endif }
174,507
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t SoundTriggerHwService::Module::startRecognition(sound_model_handle_t handle, const sp<IMemory>& dataMemory) { ALOGV("startRecognition() model handle %d", handle); if (!captureHotwordAllowed()) { return PERMISSION_DENIED; } if (dataMemory != 0 && dataMemory->pointer() == NULL) { ALOGE("startRecognition() dataMemory is non-0 but has NULL pointer()"); return BAD_VALUE; } AutoMutex lock(mLock); if (mServiceState == SOUND_TRIGGER_STATE_DISABLED) { return INVALID_OPERATION; } sp<Model> model = getModel(handle); if (model == 0) { return BAD_VALUE; } if ((dataMemory == 0) || (dataMemory->size() < sizeof(struct sound_trigger_recognition_config))) { return BAD_VALUE; } if (model->mState == Model::STATE_ACTIVE) { return INVALID_OPERATION; } struct sound_trigger_recognition_config *config = (struct sound_trigger_recognition_config *)dataMemory->pointer(); config->capture_handle = model->mCaptureIOHandle; config->capture_device = model->mCaptureDevice; status_t status = mHwDevice->start_recognition(mHwDevice, handle, config, SoundTriggerHwService::recognitionCallback, this); if (status == NO_ERROR) { model->mState = Model::STATE_ACTIVE; model->mConfig = *config; } return status; } Commit Message: soundtrigger: add size check on sound model and recogntion data Bug: 30148546 Change-Id: I082f535a853c96571887eeea37c6d41ecee7d8c0 (cherry picked from commit bb00d8f139ff51336ab3c810d35685003949bcf8) (cherry picked from commit ef0c91518446e65533ca8bab6726a845f27c73fd) CWE ID: CWE-264
status_t SoundTriggerHwService::Module::startRecognition(sound_model_handle_t handle, const sp<IMemory>& dataMemory) { ALOGV("startRecognition() model handle %d", handle); if (!captureHotwordAllowed()) { return PERMISSION_DENIED; } if (dataMemory == 0 || dataMemory->pointer() == NULL) { ALOGE("startRecognition() dataMemory is 0 or has NULL pointer()"); return BAD_VALUE; } struct sound_trigger_recognition_config *config = (struct sound_trigger_recognition_config *)dataMemory->pointer(); if (config->data_offset < sizeof(struct sound_trigger_recognition_config) || config->data_size > (UINT_MAX - config->data_offset) || dataMemory->size() < config->data_offset || config->data_size > (dataMemory->size() - config->data_offset)) { ALOGE("startRecognition() data_size is too big"); return BAD_VALUE; } AutoMutex lock(mLock); if (mServiceState == SOUND_TRIGGER_STATE_DISABLED) { return INVALID_OPERATION; } sp<Model> model = getModel(handle); if (model == 0) { return BAD_VALUE; } if (model->mState == Model::STATE_ACTIVE) { return INVALID_OPERATION; } config->capture_handle = model->mCaptureIOHandle; config->capture_device = model->mCaptureDevice; status_t status = mHwDevice->start_recognition(mHwDevice, handle, config, SoundTriggerHwService::recognitionCallback, this); if (status == NO_ERROR) { model->mState = Model::STATE_ACTIVE; model->mConfig = *config; } return status; }
173,400
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool IsTraceEventArgsWhitelisted(const char* category_group_name, const char* event_name) { if (base::MatchPattern(category_group_name, "toplevel") && base::MatchPattern(event_name, "*")) { return true; } return false; } Commit Message: Tracing: Add support for PII whitelisting of individual trace event arguments R=dsinclair,shatch BUG=546093 Review URL: https://codereview.chromium.org/1415013003 Cr-Commit-Position: refs/heads/master@{#356690} CWE ID: CWE-399
bool IsTraceEventArgsWhitelisted(const char* category_group_name, const char* event_name, ArgumentNameFilterPredicate* arg_filter) { if (base::MatchPattern(category_group_name, "toplevel") && base::MatchPattern(event_name, "*")) { return true; } if (base::MatchPattern(category_group_name, "benchmark") && base::MatchPattern(event_name, "granularly_whitelisted")) { *arg_filter = base::Bind(&IsArgNameWhitelisted); return true; } return false; }
171,679
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void OpenSSL_add_all_ciphers(void) { #ifndef OPENSSL_NO_DES EVP_add_cipher(EVP_des_cfb()); EVP_add_cipher(EVP_des_cfb1()); EVP_add_cipher(EVP_des_cfb8()); EVP_add_cipher(EVP_des_ede_cfb()); EVP_add_cipher(EVP_des_ede3_cfb()); EVP_add_cipher(EVP_des_ede3_cfb1()); EVP_add_cipher(EVP_des_ede3_cfb8()); EVP_add_cipher(EVP_des_ofb()); EVP_add_cipher(EVP_des_ede_ofb()); EVP_add_cipher(EVP_des_ede3_ofb()); EVP_add_cipher(EVP_desx_cbc()); EVP_add_cipher_alias(SN_desx_cbc,"DESX"); EVP_add_cipher_alias(SN_desx_cbc,"desx"); EVP_add_cipher(EVP_des_cbc()); EVP_add_cipher_alias(SN_des_cbc,"DES"); EVP_add_cipher_alias(SN_des_cbc,"des"); EVP_add_cipher(EVP_des_ede_cbc()); EVP_add_cipher(EVP_des_ede3_cbc()); EVP_add_cipher_alias(SN_des_ede3_cbc,"DES3"); EVP_add_cipher_alias(SN_des_ede3_cbc,"des3"); EVP_add_cipher(EVP_des_ecb()); EVP_add_cipher(EVP_des_ede()); EVP_add_cipher(EVP_des_ede3()); #endif #ifndef OPENSSL_NO_RC4 EVP_add_cipher(EVP_rc4()); EVP_add_cipher(EVP_rc4_40()); #ifndef OPENSSL_NO_MD5 EVP_add_cipher(EVP_rc4_hmac_md5()); #endif #endif #ifndef OPENSSL_NO_IDEA EVP_add_cipher(EVP_idea_ecb()); EVP_add_cipher(EVP_idea_cfb()); EVP_add_cipher(EVP_idea_ofb()); EVP_add_cipher(EVP_idea_cbc()); EVP_add_cipher_alias(SN_idea_cbc,"IDEA"); EVP_add_cipher_alias(SN_idea_cbc,"idea"); #endif #ifndef OPENSSL_NO_SEED EVP_add_cipher(EVP_seed_ecb()); EVP_add_cipher(EVP_seed_cfb()); EVP_add_cipher(EVP_seed_ofb()); EVP_add_cipher(EVP_seed_cbc()); EVP_add_cipher_alias(SN_seed_cbc,"SEED"); EVP_add_cipher_alias(SN_seed_cbc,"seed"); #endif #ifndef OPENSSL_NO_RC2 EVP_add_cipher(EVP_rc2_ecb()); EVP_add_cipher(EVP_rc2_cfb()); EVP_add_cipher(EVP_rc2_ofb()); EVP_add_cipher(EVP_rc2_cbc()); EVP_add_cipher(EVP_rc2_40_cbc()); EVP_add_cipher(EVP_rc2_64_cbc()); EVP_add_cipher_alias(SN_rc2_cbc,"RC2"); EVP_add_cipher_alias(SN_rc2_cbc,"rc2"); #endif #ifndef OPENSSL_NO_BF EVP_add_cipher(EVP_bf_ecb()); EVP_add_cipher(EVP_bf_cfb()); EVP_add_cipher(EVP_bf_ofb()); EVP_add_cipher(EVP_bf_cbc()); EVP_add_cipher_alias(SN_bf_cbc,"BF"); EVP_add_cipher_alias(SN_bf_cbc,"bf"); EVP_add_cipher_alias(SN_bf_cbc,"blowfish"); #endif #ifndef OPENSSL_NO_CAST EVP_add_cipher(EVP_cast5_ecb()); EVP_add_cipher(EVP_cast5_cfb()); EVP_add_cipher(EVP_cast5_ofb()); EVP_add_cipher(EVP_cast5_cbc()); EVP_add_cipher_alias(SN_cast5_cbc,"CAST"); EVP_add_cipher_alias(SN_cast5_cbc,"cast"); EVP_add_cipher_alias(SN_cast5_cbc,"CAST-cbc"); EVP_add_cipher_alias(SN_cast5_cbc,"cast-cbc"); #endif #ifndef OPENSSL_NO_RC5 EVP_add_cipher(EVP_rc5_32_12_16_ecb()); EVP_add_cipher(EVP_rc5_32_12_16_cfb()); EVP_add_cipher(EVP_rc5_32_12_16_ofb()); EVP_add_cipher(EVP_rc5_32_12_16_cbc()); EVP_add_cipher_alias(SN_rc5_cbc,"rc5"); EVP_add_cipher_alias(SN_rc5_cbc,"RC5"); #endif #ifndef OPENSSL_NO_AES EVP_add_cipher(EVP_aes_128_ecb()); EVP_add_cipher(EVP_aes_128_cbc()); EVP_add_cipher(EVP_aes_128_cfb()); EVP_add_cipher(EVP_aes_128_cfb1()); EVP_add_cipher(EVP_aes_128_cfb8()); EVP_add_cipher(EVP_aes_128_ofb()); EVP_add_cipher(EVP_aes_128_ctr()); EVP_add_cipher(EVP_aes_128_gcm()); EVP_add_cipher(EVP_aes_128_xts()); EVP_add_cipher_alias(SN_aes_128_cbc,"AES128"); EVP_add_cipher_alias(SN_aes_128_cbc,"aes128"); EVP_add_cipher(EVP_aes_192_ecb()); EVP_add_cipher(EVP_aes_192_cbc()); EVP_add_cipher(EVP_aes_192_cfb()); EVP_add_cipher(EVP_aes_192_cfb1()); EVP_add_cipher(EVP_aes_192_cfb8()); EVP_add_cipher(EVP_aes_192_ofb()); EVP_add_cipher(EVP_aes_192_ctr()); EVP_add_cipher(EVP_aes_192_gcm()); EVP_add_cipher_alias(SN_aes_192_cbc,"AES192"); EVP_add_cipher_alias(SN_aes_192_cbc,"aes192"); EVP_add_cipher(EVP_aes_256_ecb()); EVP_add_cipher(EVP_aes_256_cbc()); EVP_add_cipher(EVP_aes_256_cfb()); EVP_add_cipher(EVP_aes_256_cfb1()); EVP_add_cipher(EVP_aes_256_cfb8()); EVP_add_cipher(EVP_aes_256_ofb()); EVP_add_cipher(EVP_aes_256_ctr()); EVP_add_cipher(EVP_aes_256_gcm()); EVP_add_cipher(EVP_aes_256_xts()); EVP_add_cipher_alias(SN_aes_256_cbc,"AES256"); EVP_add_cipher_alias(SN_aes_256_cbc,"aes256"); #if 0 /* Disabled because of timing side-channel leaks. */ #if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1) EVP_add_cipher(EVP_aes_128_cbc_hmac_sha1()); EVP_add_cipher(EVP_aes_256_cbc_hmac_sha1()); #endif #endif #endif #ifndef OPENSSL_NO_CAMELLIA EVP_add_cipher(EVP_camellia_128_ecb()); #ifndef OPENSSL_NO_CAMELLIA EVP_add_cipher(EVP_camellia_128_ecb()); EVP_add_cipher(EVP_camellia_128_cbc()); EVP_add_cipher(EVP_camellia_128_cfb()); EVP_add_cipher(EVP_camellia_128_cfb1()); EVP_add_cipher(EVP_camellia_128_cfb8()); EVP_add_cipher(EVP_camellia_128_ofb()); EVP_add_cipher_alias(SN_camellia_128_cbc,"CAMELLIA128"); EVP_add_cipher_alias(SN_camellia_128_cbc,"camellia128"); EVP_add_cipher(EVP_camellia_192_ecb()); EVP_add_cipher(EVP_camellia_192_cbc()); EVP_add_cipher(EVP_camellia_192_cfb()); EVP_add_cipher(EVP_camellia_192_cfb1()); EVP_add_cipher(EVP_camellia_192_cfb8()); EVP_add_cipher(EVP_camellia_192_ofb()); EVP_add_cipher_alias(SN_camellia_192_cbc,"CAMELLIA192"); EVP_add_cipher_alias(SN_camellia_192_cbc,"camellia192"); EVP_add_cipher(EVP_camellia_256_ecb()); EVP_add_cipher(EVP_camellia_256_cbc()); EVP_add_cipher(EVP_camellia_256_cfb()); EVP_add_cipher(EVP_camellia_256_cfb1()); EVP_add_cipher(EVP_camellia_256_cfb8()); EVP_add_cipher(EVP_camellia_256_ofb()); EVP_add_cipher_alias(SN_camellia_256_cbc,"CAMELLIA256"); EVP_add_cipher_alias(SN_camellia_256_cbc,"camellia256"); #endif } Commit Message: CWE ID: CWE-310
void OpenSSL_add_all_ciphers(void) { #ifndef OPENSSL_NO_DES EVP_add_cipher(EVP_des_cfb()); EVP_add_cipher(EVP_des_cfb1()); EVP_add_cipher(EVP_des_cfb8()); EVP_add_cipher(EVP_des_ede_cfb()); EVP_add_cipher(EVP_des_ede3_cfb()); EVP_add_cipher(EVP_des_ede3_cfb1()); EVP_add_cipher(EVP_des_ede3_cfb8()); EVP_add_cipher(EVP_des_ofb()); EVP_add_cipher(EVP_des_ede_ofb()); EVP_add_cipher(EVP_des_ede3_ofb()); EVP_add_cipher(EVP_desx_cbc()); EVP_add_cipher_alias(SN_desx_cbc,"DESX"); EVP_add_cipher_alias(SN_desx_cbc,"desx"); EVP_add_cipher(EVP_des_cbc()); EVP_add_cipher_alias(SN_des_cbc,"DES"); EVP_add_cipher_alias(SN_des_cbc,"des"); EVP_add_cipher(EVP_des_ede_cbc()); EVP_add_cipher(EVP_des_ede3_cbc()); EVP_add_cipher_alias(SN_des_ede3_cbc,"DES3"); EVP_add_cipher_alias(SN_des_ede3_cbc,"des3"); EVP_add_cipher(EVP_des_ecb()); EVP_add_cipher(EVP_des_ede()); EVP_add_cipher(EVP_des_ede3()); #endif #ifndef OPENSSL_NO_RC4 EVP_add_cipher(EVP_rc4()); EVP_add_cipher(EVP_rc4_40()); #ifndef OPENSSL_NO_MD5 EVP_add_cipher(EVP_rc4_hmac_md5()); #endif #endif #ifndef OPENSSL_NO_IDEA EVP_add_cipher(EVP_idea_ecb()); EVP_add_cipher(EVP_idea_cfb()); EVP_add_cipher(EVP_idea_ofb()); EVP_add_cipher(EVP_idea_cbc()); EVP_add_cipher_alias(SN_idea_cbc,"IDEA"); EVP_add_cipher_alias(SN_idea_cbc,"idea"); #endif #ifndef OPENSSL_NO_SEED EVP_add_cipher(EVP_seed_ecb()); EVP_add_cipher(EVP_seed_cfb()); EVP_add_cipher(EVP_seed_ofb()); EVP_add_cipher(EVP_seed_cbc()); EVP_add_cipher_alias(SN_seed_cbc,"SEED"); EVP_add_cipher_alias(SN_seed_cbc,"seed"); #endif #ifndef OPENSSL_NO_RC2 EVP_add_cipher(EVP_rc2_ecb()); EVP_add_cipher(EVP_rc2_cfb()); EVP_add_cipher(EVP_rc2_ofb()); EVP_add_cipher(EVP_rc2_cbc()); EVP_add_cipher(EVP_rc2_40_cbc()); EVP_add_cipher(EVP_rc2_64_cbc()); EVP_add_cipher_alias(SN_rc2_cbc,"RC2"); EVP_add_cipher_alias(SN_rc2_cbc,"rc2"); #endif #ifndef OPENSSL_NO_BF EVP_add_cipher(EVP_bf_ecb()); EVP_add_cipher(EVP_bf_cfb()); EVP_add_cipher(EVP_bf_ofb()); EVP_add_cipher(EVP_bf_cbc()); EVP_add_cipher_alias(SN_bf_cbc,"BF"); EVP_add_cipher_alias(SN_bf_cbc,"bf"); EVP_add_cipher_alias(SN_bf_cbc,"blowfish"); #endif #ifndef OPENSSL_NO_CAST EVP_add_cipher(EVP_cast5_ecb()); EVP_add_cipher(EVP_cast5_cfb()); EVP_add_cipher(EVP_cast5_ofb()); EVP_add_cipher(EVP_cast5_cbc()); EVP_add_cipher_alias(SN_cast5_cbc,"CAST"); EVP_add_cipher_alias(SN_cast5_cbc,"cast"); EVP_add_cipher_alias(SN_cast5_cbc,"CAST-cbc"); EVP_add_cipher_alias(SN_cast5_cbc,"cast-cbc"); #endif #ifndef OPENSSL_NO_RC5 EVP_add_cipher(EVP_rc5_32_12_16_ecb()); EVP_add_cipher(EVP_rc5_32_12_16_cfb()); EVP_add_cipher(EVP_rc5_32_12_16_ofb()); EVP_add_cipher(EVP_rc5_32_12_16_cbc()); EVP_add_cipher_alias(SN_rc5_cbc,"rc5"); EVP_add_cipher_alias(SN_rc5_cbc,"RC5"); #endif #ifndef OPENSSL_NO_AES EVP_add_cipher(EVP_aes_128_ecb()); EVP_add_cipher(EVP_aes_128_cbc()); EVP_add_cipher(EVP_aes_128_cfb()); EVP_add_cipher(EVP_aes_128_cfb1()); EVP_add_cipher(EVP_aes_128_cfb8()); EVP_add_cipher(EVP_aes_128_ofb()); EVP_add_cipher(EVP_aes_128_ctr()); EVP_add_cipher(EVP_aes_128_gcm()); EVP_add_cipher(EVP_aes_128_xts()); EVP_add_cipher_alias(SN_aes_128_cbc,"AES128"); EVP_add_cipher_alias(SN_aes_128_cbc,"aes128"); EVP_add_cipher(EVP_aes_192_ecb()); EVP_add_cipher(EVP_aes_192_cbc()); EVP_add_cipher(EVP_aes_192_cfb()); EVP_add_cipher(EVP_aes_192_cfb1()); EVP_add_cipher(EVP_aes_192_cfb8()); EVP_add_cipher(EVP_aes_192_ofb()); EVP_add_cipher(EVP_aes_192_ctr()); EVP_add_cipher(EVP_aes_192_gcm()); EVP_add_cipher_alias(SN_aes_192_cbc,"AES192"); EVP_add_cipher_alias(SN_aes_192_cbc,"aes192"); EVP_add_cipher(EVP_aes_256_ecb()); EVP_add_cipher(EVP_aes_256_cbc()); EVP_add_cipher(EVP_aes_256_cfb()); EVP_add_cipher(EVP_aes_256_cfb1()); EVP_add_cipher(EVP_aes_256_cfb8()); EVP_add_cipher(EVP_aes_256_ofb()); EVP_add_cipher(EVP_aes_256_ctr()); EVP_add_cipher(EVP_aes_256_gcm()); EVP_add_cipher(EVP_aes_256_xts()); EVP_add_cipher_alias(SN_aes_256_cbc,"AES256"); EVP_add_cipher_alias(SN_aes_256_cbc,"aes256"); #if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1) EVP_add_cipher(EVP_aes_128_cbc_hmac_sha1()); EVP_add_cipher(EVP_aes_256_cbc_hmac_sha1()); #endif #endif #ifndef OPENSSL_NO_CAMELLIA EVP_add_cipher(EVP_camellia_128_ecb()); #ifndef OPENSSL_NO_CAMELLIA EVP_add_cipher(EVP_camellia_128_ecb()); EVP_add_cipher(EVP_camellia_128_cbc()); EVP_add_cipher(EVP_camellia_128_cfb()); EVP_add_cipher(EVP_camellia_128_cfb1()); EVP_add_cipher(EVP_camellia_128_cfb8()); EVP_add_cipher(EVP_camellia_128_ofb()); EVP_add_cipher_alias(SN_camellia_128_cbc,"CAMELLIA128"); EVP_add_cipher_alias(SN_camellia_128_cbc,"camellia128"); EVP_add_cipher(EVP_camellia_192_ecb()); EVP_add_cipher(EVP_camellia_192_cbc()); EVP_add_cipher(EVP_camellia_192_cfb()); EVP_add_cipher(EVP_camellia_192_cfb1()); EVP_add_cipher(EVP_camellia_192_cfb8()); EVP_add_cipher(EVP_camellia_192_ofb()); EVP_add_cipher_alias(SN_camellia_192_cbc,"CAMELLIA192"); EVP_add_cipher_alias(SN_camellia_192_cbc,"camellia192"); EVP_add_cipher(EVP_camellia_256_ecb()); EVP_add_cipher(EVP_camellia_256_cbc()); EVP_add_cipher(EVP_camellia_256_cfb()); EVP_add_cipher(EVP_camellia_256_cfb1()); EVP_add_cipher(EVP_camellia_256_cfb8()); EVP_add_cipher(EVP_camellia_256_ofb()); EVP_add_cipher_alias(SN_camellia_256_cbc,"CAMELLIA256"); EVP_add_cipher_alias(SN_camellia_256_cbc,"camellia256"); #endif }
164,867
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Cues::LoadCuePoint() const { const long long stop = m_start + m_size; if (m_pos >= stop) return false; // nothing else to do Init(); IMkvReader* const pReader = m_pSegment->m_pReader; while (m_pos < stop) { const long long idpos = m_pos; long len; const long long id = ReadUInt(pReader, m_pos, len); assert(id >= 0); // TODO assert((m_pos + len) <= stop); m_pos += len; // consume ID const long long size = ReadUInt(pReader, m_pos, len); assert(size >= 0); assert((m_pos + len) <= stop); m_pos += len; // consume Size field assert((m_pos + size) <= stop); if (id != 0x3B) { // CuePoint ID m_pos += size; // consume payload assert(m_pos <= stop); continue; } assert(m_preload_count > 0); CuePoint* const pCP = m_cue_points[m_count]; assert(pCP); assert((pCP->GetTimeCode() >= 0) || (-pCP->GetTimeCode() == idpos)); if (pCP->GetTimeCode() < 0 && (-pCP->GetTimeCode() != idpos)) return false; pCP->Load(pReader); ++m_count; --m_preload_count; m_pos += size; // consume payload assert(m_pos <= stop); return true; // yes, we loaded a cue point } } 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
bool Cues::LoadCuePoint() const { const long long stop = m_start + m_size; if (m_pos >= stop) return false; // nothing else to do if (!Init()) { m_pos = stop; return false; } IMkvReader* const pReader = m_pSegment->m_pReader; while (m_pos < stop) { const long long idpos = m_pos; long len; const long long id = ReadID(pReader, m_pos, len); if (id < 0 || (m_pos + len) > stop) return false; m_pos += len; // consume ID const long long size = ReadUInt(pReader, m_pos, len); if (size < 0 || (m_pos + len) > stop) return false; m_pos += len; // consume Size field if ((m_pos + size) > stop) return false; if (id != 0x3B) { // CuePoint ID m_pos += size; // consume payload if (m_pos > stop) return false; continue; } if (m_preload_count < 1) return false; CuePoint* const pCP = m_cue_points[m_count]; if (!pCP || (pCP->GetTimeCode() < 0 && (-pCP->GetTimeCode() != idpos))) return false; if (!pCP->Load(pReader)) { m_pos = stop; return false; } ++m_count; --m_preload_count; m_pos += size; // consume payload if (m_pos > stop) return false; return true; // yes, we loaded a cue point } }
173,831
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sd2_parse_rsrc_fork (SF_PRIVATE *psf) { SD2_RSRC rsrc ; int k, marker, error = 0 ; psf_use_rsrc (psf, SF_TRUE) ; memset (&rsrc, 0, sizeof (rsrc)) ; rsrc.rsrc_len = psf_get_filelen (psf) ; psf_log_printf (psf, "Resource length : %d (0x%04X)\n", rsrc.rsrc_len, rsrc.rsrc_len) ; if (rsrc.rsrc_len > SIGNED_SIZEOF (psf->header)) { rsrc.rsrc_data = calloc (1, rsrc.rsrc_len) ; rsrc.need_to_free_rsrc_data = SF_TRUE ; } else { rsrc.rsrc_data = psf->header ; rsrc.need_to_free_rsrc_data = SF_FALSE ; } ; /* Read in the whole lot. */ psf_fread (rsrc.rsrc_data, rsrc.rsrc_len, 1, psf) ; /* Reset the header storage because we have changed to the rsrcdes. */ psf->headindex = psf->headend = rsrc.rsrc_len ; rsrc.data_offset = read_rsrc_int (&rsrc, 0) ; rsrc.map_offset = read_rsrc_int (&rsrc, 4) ; rsrc.data_length = read_rsrc_int (&rsrc, 8) ; rsrc.map_length = read_rsrc_int (&rsrc, 12) ; if (rsrc.data_offset == 0x51607 && rsrc.map_offset == 0x20000) { psf_log_printf (psf, "Trying offset of 0x52 bytes.\n") ; rsrc.data_offset = read_rsrc_int (&rsrc, 0x52 + 0) + 0x52 ; rsrc.map_offset = read_rsrc_int (&rsrc, 0x52 + 4) + 0x52 ; rsrc.data_length = read_rsrc_int (&rsrc, 0x52 + 8) ; rsrc.map_length = read_rsrc_int (&rsrc, 0x52 + 12) ; } ; psf_log_printf (psf, " data offset : 0x%04X\n map offset : 0x%04X\n" " data length : 0x%04X\n map length : 0x%04X\n", rsrc.data_offset, rsrc.map_offset, rsrc.data_length, rsrc.map_length) ; if (rsrc.data_offset > rsrc.rsrc_len) { psf_log_printf (psf, "Error : rsrc.data_offset (%d, 0x%x) > len\n", rsrc.data_offset, rsrc.data_offset) ; error = SFE_SD2_BAD_DATA_OFFSET ; goto parse_rsrc_fork_cleanup ; } ; if (rsrc.map_offset > rsrc.rsrc_len) { psf_log_printf (psf, "Error : rsrc.map_offset > len\n") ; error = SFE_SD2_BAD_MAP_OFFSET ; goto parse_rsrc_fork_cleanup ; } ; if (rsrc.data_length > rsrc.rsrc_len) { psf_log_printf (psf, "Error : rsrc.data_length > len\n") ; error = SFE_SD2_BAD_DATA_LENGTH ; goto parse_rsrc_fork_cleanup ; } ; if (rsrc.map_length > rsrc.rsrc_len) { psf_log_printf (psf, "Error : rsrc.map_length > len\n") ; error = SFE_SD2_BAD_MAP_LENGTH ; goto parse_rsrc_fork_cleanup ; } ; if (rsrc.data_offset + rsrc.data_length != rsrc.map_offset || rsrc.map_offset + rsrc.map_length != rsrc.rsrc_len) { psf_log_printf (psf, "Error : This does not look like a MacOSX resource fork.\n") ; error = SFE_SD2_BAD_RSRC ; goto parse_rsrc_fork_cleanup ; } ; if (rsrc.map_offset + 28 >= rsrc.rsrc_len) { psf_log_printf (psf, "Bad map offset (%d + 28 > %d).\n", rsrc.map_offset, rsrc.rsrc_len) ; error = SFE_SD2_BAD_RSRC ; goto parse_rsrc_fork_cleanup ; } ; rsrc.string_offset = rsrc.map_offset + read_rsrc_short (&rsrc, rsrc.map_offset + 26) ; if (rsrc.string_offset > rsrc.rsrc_len) { psf_log_printf (psf, "Bad string offset (%d).\n", rsrc.string_offset) ; error = SFE_SD2_BAD_RSRC ; goto parse_rsrc_fork_cleanup ; } ; rsrc.type_offset = rsrc.map_offset + 30 ; rsrc.type_count = read_rsrc_short (&rsrc, rsrc.map_offset + 28) + 1 ; if (rsrc.type_count < 1) { psf_log_printf (psf, "Bad type count.\n") ; error = SFE_SD2_BAD_RSRC ; goto parse_rsrc_fork_cleanup ; } ; rsrc.item_offset = rsrc.type_offset + rsrc.type_count * 8 ; if (rsrc.item_offset < 0 || rsrc.item_offset > rsrc.rsrc_len) { psf_log_printf (psf, "Bad item offset (%d).\n", rsrc.item_offset) ; error = SFE_SD2_BAD_RSRC ; goto parse_rsrc_fork_cleanup ; } ; rsrc.str_index = -1 ; for (k = 0 ; k < rsrc.type_count ; k ++) { marker = read_rsrc_marker (&rsrc, rsrc.type_offset + k * 8) ; if (marker == STR_MARKER) { rsrc.str_index = k ; rsrc.str_count = read_rsrc_short (&rsrc, rsrc.type_offset + k * 8 + 4) + 1 ; error = parse_str_rsrc (psf, &rsrc) ; goto parse_rsrc_fork_cleanup ; } ; } ; psf_log_printf (psf, "No 'STR ' resource.\n") ; error = SFE_SD2_BAD_RSRC ; parse_rsrc_fork_cleanup : psf_use_rsrc (psf, SF_FALSE) ; if (rsrc.need_to_free_rsrc_data) free (rsrc.rsrc_data) ; return error ; } /* sd2_parse_rsrc_fork */ Commit Message: src/sd2.c : Fix two potential buffer read overflows. Closes: https://github.com/erikd/libsndfile/issues/93 CWE ID: CWE-119
sd2_parse_rsrc_fork (SF_PRIVATE *psf) { SD2_RSRC rsrc ; int k, marker, error = 0 ; psf_use_rsrc (psf, SF_TRUE) ; memset (&rsrc, 0, sizeof (rsrc)) ; rsrc.rsrc_len = psf_get_filelen (psf) ; psf_log_printf (psf, "Resource length : %d (0x%04X)\n", rsrc.rsrc_len, rsrc.rsrc_len) ; if (rsrc.rsrc_len > SIGNED_SIZEOF (psf->header)) { rsrc.rsrc_data = calloc (1, rsrc.rsrc_len) ; rsrc.need_to_free_rsrc_data = SF_TRUE ; } else { rsrc.rsrc_data = psf->header ; rsrc.need_to_free_rsrc_data = SF_FALSE ; } ; /* Read in the whole lot. */ psf_fread (rsrc.rsrc_data, rsrc.rsrc_len, 1, psf) ; /* Reset the header storage because we have changed to the rsrcdes. */ psf->headindex = psf->headend = rsrc.rsrc_len ; rsrc.data_offset = read_rsrc_int (&rsrc, 0) ; rsrc.map_offset = read_rsrc_int (&rsrc, 4) ; rsrc.data_length = read_rsrc_int (&rsrc, 8) ; rsrc.map_length = read_rsrc_int (&rsrc, 12) ; if (rsrc.data_offset == 0x51607 && rsrc.map_offset == 0x20000) { psf_log_printf (psf, "Trying offset of 0x52 bytes.\n") ; rsrc.data_offset = read_rsrc_int (&rsrc, 0x52 + 0) + 0x52 ; rsrc.map_offset = read_rsrc_int (&rsrc, 0x52 + 4) + 0x52 ; rsrc.data_length = read_rsrc_int (&rsrc, 0x52 + 8) ; rsrc.map_length = read_rsrc_int (&rsrc, 0x52 + 12) ; } ; psf_log_printf (psf, " data offset : 0x%04X\n map offset : 0x%04X\n" " data length : 0x%04X\n map length : 0x%04X\n", rsrc.data_offset, rsrc.map_offset, rsrc.data_length, rsrc.map_length) ; if (rsrc.data_offset > rsrc.rsrc_len) { psf_log_printf (psf, "Error : rsrc.data_offset (%d, 0x%x) > len\n", rsrc.data_offset, rsrc.data_offset) ; error = SFE_SD2_BAD_DATA_OFFSET ; goto parse_rsrc_fork_cleanup ; } ; if (rsrc.map_offset > rsrc.rsrc_len) { psf_log_printf (psf, "Error : rsrc.map_offset > len\n") ; error = SFE_SD2_BAD_MAP_OFFSET ; goto parse_rsrc_fork_cleanup ; } ; if (rsrc.data_length > rsrc.rsrc_len) { psf_log_printf (psf, "Error : rsrc.data_length > len\n") ; error = SFE_SD2_BAD_DATA_LENGTH ; goto parse_rsrc_fork_cleanup ; } ; if (rsrc.map_length > rsrc.rsrc_len) { psf_log_printf (psf, "Error : rsrc.map_length > len\n") ; error = SFE_SD2_BAD_MAP_LENGTH ; goto parse_rsrc_fork_cleanup ; } ; if (rsrc.data_offset + rsrc.data_length != rsrc.map_offset || rsrc.map_offset + rsrc.map_length != rsrc.rsrc_len) { psf_log_printf (psf, "Error : This does not look like a MacOSX resource fork.\n") ; error = SFE_SD2_BAD_RSRC ; goto parse_rsrc_fork_cleanup ; } ; if (rsrc.map_offset + 28 >= rsrc.rsrc_len) { psf_log_printf (psf, "Bad map offset (%d + 28 > %d).\n", rsrc.map_offset, rsrc.rsrc_len) ; error = SFE_SD2_BAD_RSRC ; goto parse_rsrc_fork_cleanup ; } ; rsrc.string_offset = rsrc.map_offset + read_rsrc_short (&rsrc, rsrc.map_offset + 26) ; if (rsrc.string_offset > rsrc.rsrc_len) { psf_log_printf (psf, "Bad string offset (%d).\n", rsrc.string_offset) ; error = SFE_SD2_BAD_RSRC ; goto parse_rsrc_fork_cleanup ; } ; rsrc.type_offset = rsrc.map_offset + 30 ; if (rsrc.map_offset + 28 > rsrc.rsrc_len) { psf_log_printf (psf, "Bad map offset.\n") ; goto parse_rsrc_fork_cleanup ; } ; rsrc.type_count = read_rsrc_short (&rsrc, rsrc.map_offset + 28) + 1 ; if (rsrc.type_count < 1) { psf_log_printf (psf, "Bad type count.\n") ; error = SFE_SD2_BAD_RSRC ; goto parse_rsrc_fork_cleanup ; } ; rsrc.item_offset = rsrc.type_offset + rsrc.type_count * 8 ; if (rsrc.item_offset < 0 || rsrc.item_offset > rsrc.rsrc_len) { psf_log_printf (psf, "Bad item offset (%d).\n", rsrc.item_offset) ; error = SFE_SD2_BAD_RSRC ; goto parse_rsrc_fork_cleanup ; } ; rsrc.str_index = -1 ; for (k = 0 ; k < rsrc.type_count ; k ++) { if (rsrc.type_offset + k * 8 > rsrc.rsrc_len) { psf_log_printf (psf, "Bad rsrc marker.\n") ; goto parse_rsrc_fork_cleanup ; } ; marker = read_rsrc_marker (&rsrc, rsrc.type_offset + k * 8) ; if (marker == STR_MARKER) { rsrc.str_index = k ; rsrc.str_count = read_rsrc_short (&rsrc, rsrc.type_offset + k * 8 + 4) + 1 ; error = parse_str_rsrc (psf, &rsrc) ; goto parse_rsrc_fork_cleanup ; } ; } ; psf_log_printf (psf, "No 'STR ' resource.\n") ; error = SFE_SD2_BAD_RSRC ; parse_rsrc_fork_cleanup : psf_use_rsrc (psf, SF_FALSE) ; if (rsrc.need_to_free_rsrc_data) free (rsrc.rsrc_data) ; return error ; } /* sd2_parse_rsrc_fork */
166,784
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xps_select_best_font_encoding(xps_font_t *font) { static struct { int pid, eid; } xps_cmap_list[] = { { 3, 10 }, /* Unicode with surrogates */ { 3, 1 }, /* Unicode without surrogates */ { 3, 5 }, /* Wansung */ { 3, 4 }, /* Big5 */ { 3, 3 }, /* Prc */ { 3, 2 }, /* ShiftJis */ { 3, 0 }, /* Symbol */ { 1, 0 }, { -1, -1 }, }; int i, k, n, pid, eid; n = xps_count_font_encodings(font); for (k = 0; xps_cmap_list[k].pid != -1; k++) { for (i = 0; i < n; i++) { xps_identify_font_encoding(font, i, &pid, &eid); if (pid == xps_cmap_list[k].pid && eid == xps_cmap_list[k].eid) { xps_select_font_encoding(font, i); return; } } } gs_warn("could not find a suitable cmap"); } Commit Message: CWE ID: CWE-125
xps_select_best_font_encoding(xps_font_t *font) { static struct { int pid, eid; } xps_cmap_list[] = { { 3, 10 }, /* Unicode with surrogates */ { 3, 1 }, /* Unicode without surrogates */ { 3, 5 }, /* Wansung */ { 3, 4 }, /* Big5 */ { 3, 3 }, /* Prc */ { 3, 2 }, /* ShiftJis */ { 3, 0 }, /* Symbol */ { 1, 0 }, { -1, -1 }, }; int i, k, n, pid, eid; n = xps_count_font_encodings(font); for (k = 0; xps_cmap_list[k].pid != -1; k++) { for (i = 0; i < n; i++) { xps_identify_font_encoding(font, i, &pid, &eid); if (pid == xps_cmap_list[k].pid && eid == xps_cmap_list[k].eid) { if (xps_select_font_encoding(font, i)) return; } } } gs_warn("could not find a suitable cmap"); }
164,783
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GpuProcessHostUIShim::OnAcceleratedSurfaceNew( const GpuHostMsg_AcceleratedSurfaceNew_Params& params) { RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; view->AcceleratedSurfaceNew( params.width, params.height, params.surface_handle); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuProcessHostUIShim::OnAcceleratedSurfaceNew( const GpuHostMsg_AcceleratedSurfaceNew_Params& params) { RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; if (params.mailbox_name.length() && params.mailbox_name.length() != GL_MAILBOX_SIZE_CHROMIUM) return; view->AcceleratedSurfaceNew( params.width, params.height, params.surface_handle, params.mailbox_name); }
171,358
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char *argv[]) { time_t timep; struct tm *timeptr; char *now; if (argc < 3) { send_error(1); return -1; } else if (argc > 3) { send_error(5); return -1; } build_needs_escape(); if (argv[2] == NULL) index_directory(argv[1], argv[1]); else index_directory(argv[1], argv[2]); time(&timep); #ifdef USE_LOCALTIME timeptr = localtime(&timep); #else timeptr = gmtime(&timep); #endif now = strdup(asctime(timeptr)); now[strlen(now) - 1] = '\0'; #ifdef USE_LOCALTIME printf("</table>\n<hr noshade>\nIndex generated %s %s\n" "<!-- This program is part of the Boa Webserver Copyright (C) 1991-2002 http://www.boa.org -->\n" "</body>\n</html>\n", now, TIMEZONE(timeptr)); #else printf("</table>\n<hr noshade>\nIndex generated %s UTC\n" "<!-- This program is part of the Boa Webserver Copyright (C) 1991-2002 http://www.boa.org -->\n" "</body>\n</html>\n", now); #endif return 0; } Commit Message: misc oom and possible memory leak fix CWE ID:
int main(int argc, char *argv[]) { time_t timep; struct tm *timeptr; char *now; if (argc < 3) { send_error(1); return -1; } else if (argc > 3) { send_error(5); return -1; } build_needs_escape(); if (argv[2] == NULL) index_directory(argv[1], argv[1]); else index_directory(argv[1], argv[2]); time(&timep); #ifdef USE_LOCALTIME timeptr = localtime(&timep); #else timeptr = gmtime(&timep); #endif now = strdup(asctime(timeptr)); if (!now) { return -1; } now[strlen(now) - 1] = '\0'; #ifdef USE_LOCALTIME printf("</table>\n<hr noshade>\nIndex generated %s %s\n" "<!-- This program is part of the Boa Webserver Copyright (C) 1991-2002 http://www.boa.org -->\n" "</body>\n</html>\n", now, TIMEZONE(timeptr)); #else printf("</table>\n<hr noshade>\nIndex generated %s UTC\n" "<!-- This program is part of the Boa Webserver Copyright (C) 1991-2002 http://www.boa.org -->\n" "</body>\n</html>\n", now); #endif free(now); return 0; }
169,756
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: icmp6_rrenum_print(netdissect_options *ndo, const u_char *bp, const u_char *ep) { const struct icmp6_router_renum *rr6; const char *cp; const struct rr_pco_match *match; const struct rr_pco_use *use; char hbuf[NI_MAXHOST]; int n; if (ep < bp) return; rr6 = (const struct icmp6_router_renum *)bp; cp = (const char *)(rr6 + 1); ND_TCHECK(rr6->rr_reserved); switch (rr6->rr_code) { case ICMP6_ROUTER_RENUMBERING_COMMAND: ND_PRINT((ndo,"router renum: command")); break; case ICMP6_ROUTER_RENUMBERING_RESULT: ND_PRINT((ndo,"router renum: result")); break; case ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET: ND_PRINT((ndo,"router renum: sequence number reset")); break; default: ND_PRINT((ndo,"router renum: code-#%d", rr6->rr_code)); break; } ND_PRINT((ndo,", seq=%u", EXTRACT_32BITS(&rr6->rr_seqnum))); if (ndo->ndo_vflag) { #define F(x, y) ((rr6->rr_flags) & (x) ? (y) : "") ND_PRINT((ndo,"[")); /*]*/ if (rr6->rr_flags) { ND_PRINT((ndo,"%s%s%s%s%s,", F(ICMP6_RR_FLAGS_TEST, "T"), F(ICMP6_RR_FLAGS_REQRESULT, "R"), F(ICMP6_RR_FLAGS_FORCEAPPLY, "A"), F(ICMP6_RR_FLAGS_SPECSITE, "S"), F(ICMP6_RR_FLAGS_PREVDONE, "P"))); } ND_PRINT((ndo,"seg=%u,", rr6->rr_segnum)); ND_PRINT((ndo,"maxdelay=%u", EXTRACT_16BITS(&rr6->rr_maxdelay))); if (rr6->rr_reserved) ND_PRINT((ndo,"rsvd=0x%x", EXTRACT_32BITS(&rr6->rr_reserved))); /*[*/ ND_PRINT((ndo,"]")); #undef F } if (rr6->rr_code == ICMP6_ROUTER_RENUMBERING_COMMAND) { match = (const struct rr_pco_match *)cp; cp = (const char *)(match + 1); ND_TCHECK(match->rpm_prefix); if (ndo->ndo_vflag > 1) ND_PRINT((ndo,"\n\t")); else ND_PRINT((ndo," ")); ND_PRINT((ndo,"match(")); /*)*/ switch (match->rpm_code) { case RPM_PCO_ADD: ND_PRINT((ndo,"add")); break; case RPM_PCO_CHANGE: ND_PRINT((ndo,"change")); break; case RPM_PCO_SETGLOBAL: ND_PRINT((ndo,"setglobal")); break; default: ND_PRINT((ndo,"#%u", match->rpm_code)); break; } if (ndo->ndo_vflag) { ND_PRINT((ndo,",ord=%u", match->rpm_ordinal)); ND_PRINT((ndo,",min=%u", match->rpm_minlen)); ND_PRINT((ndo,",max=%u", match->rpm_maxlen)); } if (addrtostr6(&match->rpm_prefix, hbuf, sizeof(hbuf))) ND_PRINT((ndo,",%s/%u", hbuf, match->rpm_matchlen)); else ND_PRINT((ndo,",?/%u", match->rpm_matchlen)); /*(*/ ND_PRINT((ndo,")")); n = match->rpm_len - 3; if (n % 4) goto trunc; n /= 4; while (n-- > 0) { use = (const struct rr_pco_use *)cp; cp = (const char *)(use + 1); ND_TCHECK(use->rpu_prefix); if (ndo->ndo_vflag > 1) ND_PRINT((ndo,"\n\t")); else ND_PRINT((ndo," ")); ND_PRINT((ndo,"use(")); /*)*/ if (use->rpu_flags) { #define F(x, y) ((use->rpu_flags) & (x) ? (y) : "") ND_PRINT((ndo,"%s%s,", F(ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME, "V"), F(ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME, "P"))); #undef F } if (ndo->ndo_vflag) { ND_PRINT((ndo,"mask=0x%x,", use->rpu_ramask)); ND_PRINT((ndo,"raflags=0x%x,", use->rpu_raflags)); if (~use->rpu_vltime == 0) ND_PRINT((ndo,"vltime=infty,")); else ND_PRINT((ndo,"vltime=%u,", EXTRACT_32BITS(&use->rpu_vltime))); if (~use->rpu_pltime == 0) ND_PRINT((ndo,"pltime=infty,")); else ND_PRINT((ndo,"pltime=%u,", EXTRACT_32BITS(&use->rpu_pltime))); } if (addrtostr6(&use->rpu_prefix, hbuf, sizeof(hbuf))) ND_PRINT((ndo,"%s/%u/%u", hbuf, use->rpu_uselen, use->rpu_keeplen)); else ND_PRINT((ndo,"?/%u/%u", use->rpu_uselen, use->rpu_keeplen)); /*(*/ ND_PRINT((ndo,")")); } } return; trunc: ND_PRINT((ndo,"[|icmp6]")); } Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check Moreover: Add and use *_tstr[] strings. Update four tests outputs accordingly. Fix a space. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test. CWE ID: CWE-125
icmp6_rrenum_print(netdissect_options *ndo, const u_char *bp, const u_char *ep) { const struct icmp6_router_renum *rr6; const char *cp; const struct rr_pco_match *match; const struct rr_pco_use *use; char hbuf[NI_MAXHOST]; int n; if (ep < bp) return; rr6 = (const struct icmp6_router_renum *)bp; cp = (const char *)(rr6 + 1); ND_TCHECK(rr6->rr_reserved); switch (rr6->rr_code) { case ICMP6_ROUTER_RENUMBERING_COMMAND: ND_PRINT((ndo,"router renum: command")); break; case ICMP6_ROUTER_RENUMBERING_RESULT: ND_PRINT((ndo,"router renum: result")); break; case ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET: ND_PRINT((ndo,"router renum: sequence number reset")); break; default: ND_PRINT((ndo,"router renum: code-#%d", rr6->rr_code)); break; } ND_PRINT((ndo,", seq=%u", EXTRACT_32BITS(&rr6->rr_seqnum))); if (ndo->ndo_vflag) { #define F(x, y) ((rr6->rr_flags) & (x) ? (y) : "") ND_PRINT((ndo,"[")); /*]*/ if (rr6->rr_flags) { ND_PRINT((ndo,"%s%s%s%s%s,", F(ICMP6_RR_FLAGS_TEST, "T"), F(ICMP6_RR_FLAGS_REQRESULT, "R"), F(ICMP6_RR_FLAGS_FORCEAPPLY, "A"), F(ICMP6_RR_FLAGS_SPECSITE, "S"), F(ICMP6_RR_FLAGS_PREVDONE, "P"))); } ND_PRINT((ndo,"seg=%u,", rr6->rr_segnum)); ND_PRINT((ndo,"maxdelay=%u", EXTRACT_16BITS(&rr6->rr_maxdelay))); if (rr6->rr_reserved) ND_PRINT((ndo,"rsvd=0x%x", EXTRACT_32BITS(&rr6->rr_reserved))); /*[*/ ND_PRINT((ndo,"]")); #undef F } if (rr6->rr_code == ICMP6_ROUTER_RENUMBERING_COMMAND) { match = (const struct rr_pco_match *)cp; cp = (const char *)(match + 1); ND_TCHECK(match->rpm_prefix); if (ndo->ndo_vflag > 1) ND_PRINT((ndo,"\n\t")); else ND_PRINT((ndo," ")); ND_PRINT((ndo,"match(")); /*)*/ switch (match->rpm_code) { case RPM_PCO_ADD: ND_PRINT((ndo,"add")); break; case RPM_PCO_CHANGE: ND_PRINT((ndo,"change")); break; case RPM_PCO_SETGLOBAL: ND_PRINT((ndo,"setglobal")); break; default: ND_PRINT((ndo,"#%u", match->rpm_code)); break; } if (ndo->ndo_vflag) { ND_PRINT((ndo,",ord=%u", match->rpm_ordinal)); ND_PRINT((ndo,",min=%u", match->rpm_minlen)); ND_PRINT((ndo,",max=%u", match->rpm_maxlen)); } if (addrtostr6(&match->rpm_prefix, hbuf, sizeof(hbuf))) ND_PRINT((ndo,",%s/%u", hbuf, match->rpm_matchlen)); else ND_PRINT((ndo,",?/%u", match->rpm_matchlen)); /*(*/ ND_PRINT((ndo,")")); n = match->rpm_len - 3; if (n % 4) goto trunc; n /= 4; while (n-- > 0) { use = (const struct rr_pco_use *)cp; cp = (const char *)(use + 1); ND_TCHECK(use->rpu_prefix); if (ndo->ndo_vflag > 1) ND_PRINT((ndo,"\n\t")); else ND_PRINT((ndo," ")); ND_PRINT((ndo,"use(")); /*)*/ if (use->rpu_flags) { #define F(x, y) ((use->rpu_flags) & (x) ? (y) : "") ND_PRINT((ndo,"%s%s,", F(ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME, "V"), F(ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME, "P"))); #undef F } if (ndo->ndo_vflag) { ND_PRINT((ndo,"mask=0x%x,", use->rpu_ramask)); ND_PRINT((ndo,"raflags=0x%x,", use->rpu_raflags)); if (~use->rpu_vltime == 0) ND_PRINT((ndo,"vltime=infty,")); else ND_PRINT((ndo,"vltime=%u,", EXTRACT_32BITS(&use->rpu_vltime))); if (~use->rpu_pltime == 0) ND_PRINT((ndo,"pltime=infty,")); else ND_PRINT((ndo,"pltime=%u,", EXTRACT_32BITS(&use->rpu_pltime))); } if (addrtostr6(&use->rpu_prefix, hbuf, sizeof(hbuf))) ND_PRINT((ndo,"%s/%u/%u", hbuf, use->rpu_uselen, use->rpu_keeplen)); else ND_PRINT((ndo,"?/%u/%u", use->rpu_uselen, use->rpu_keeplen)); /*(*/ ND_PRINT((ndo,")")); } } return; trunc: ND_PRINT((ndo, "%s", icmp6_tstr)); }
169,825
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ~CreateFileResult() { } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
~CreateFileResult()
171,416
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput); if (header == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */); sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */); if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource && backup->capacity() >= sizeof(VideoNativeMetadata) && codec->capacity() >= sizeof(VideoGrallocMetadata) && ((VideoNativeMetadata *)backup->base())->eType == kMetadataBufferTypeANWBuffer) { VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base(); VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base(); CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p", backupMeta.pBuffer, backupMeta.pBuffer->handle); codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL; codecMeta.eType = kMetadataBufferTypeGrallocSource; header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0; header->nOffset = 0; } else { if (rangeOffset > header->nAllocLen || rangeLength > header->nAllocLen - rangeOffset) { CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd)); if (fenceFd >= 0) { ::close(fenceFd); } return BAD_VALUE; } header->nFilledLen = rangeLength; header->nOffset = rangeOffset; buffer_meta->CopyToOMX(header); } return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd); } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) { Mutex::Autolock autoLock(mLock); // no emptybuffer if using input surface if (getGraphicBufferSource() != NULL) { android_errorWriteLog(0x534e4554, "29422020"); return INVALID_OPERATION; } OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput); if (header == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */); sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */); if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource && backup->capacity() >= sizeof(VideoNativeMetadata) && codec->capacity() >= sizeof(VideoGrallocMetadata) && ((VideoNativeMetadata *)backup->base())->eType == kMetadataBufferTypeANWBuffer) { VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base(); VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base(); CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p", backupMeta.pBuffer, backupMeta.pBuffer->handle); codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL; codecMeta.eType = kMetadataBufferTypeGrallocSource; header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0; header->nOffset = 0; } else { if (rangeOffset > header->nAllocLen || rangeLength > header->nAllocLen - rangeOffset) { CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd)); if (fenceFd >= 0) { ::close(fenceFd); } return BAD_VALUE; } header->nFilledLen = rangeLength; header->nOffset = rangeOffset; buffer_meta->CopyToOMX(header); } return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd); }
174,133
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it) { ASN1_VALUE **opval = NULL; ASN1_STRING *stmp; ASN1_TYPE *typ = NULL; int ret = 0; const ASN1_PRIMITIVE_FUNCS *pf; ASN1_INTEGER **tint; pf = it->funcs; if (pf && pf->prim_c2i) return pf->prim_c2i(pval, cont, len, utype, free_cont, it); /* If ANY type clear type and set pointer to internal value */ if (it->utype == V_ASN1_ANY) { if (!*pval) { typ = ASN1_TYPE_new(); if (typ == NULL) goto err; *pval = (ASN1_VALUE *)typ; } else typ = (ASN1_TYPE *)*pval; if (utype != typ->type) ASN1_TYPE_set(typ, utype, NULL); opval = pval; pval = &typ->value.asn1_value; } switch (utype) { case V_ASN1_OBJECT: if (!c2i_ASN1_OBJECT((ASN1_OBJECT **)pval, &cont, len)) goto err; break; case V_ASN1_NULL: if (len) { ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_NULL_IS_WRONG_LENGTH); goto err; } *pval = (ASN1_VALUE *)1; break; case V_ASN1_BOOLEAN: if (len != 1) { ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_BOOLEAN_IS_WRONG_LENGTH); goto err; } else { ASN1_BOOLEAN *tbool; tbool = (ASN1_BOOLEAN *)pval; *tbool = *cont; } break; case V_ASN1_BIT_STRING: if (!c2i_ASN1_BIT_STRING((ASN1_BIT_STRING **)pval, &cont, len)) goto err; break; case V_ASN1_INTEGER: case V_ASN1_NEG_INTEGER: case V_ASN1_ENUMERATED: case V_ASN1_NEG_ENUMERATED: tint = (ASN1_INTEGER **)pval; if (!c2i_ASN1_INTEGER(tint, &cont, len)) goto err; if (!c2i_ASN1_INTEGER(tint, &cont, len)) goto err; /* Fixup type to match the expected form */ (*tint)->type = utype | ((*tint)->type & V_ASN1_NEG); break; case V_ASN1_OCTET_STRING: case V_ASN1_NUMERICSTRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_T61STRING: case V_ASN1_VIDEOTEXSTRING: case V_ASN1_IA5STRING: case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: case V_ASN1_GRAPHICSTRING: case V_ASN1_VISIBLESTRING: case V_ASN1_GENERALSTRING: case V_ASN1_UNIVERSALSTRING: case V_ASN1_BMPSTRING: case V_ASN1_UTF8STRING: case V_ASN1_OTHER: case V_ASN1_SET: case V_ASN1_SEQUENCE: default: if (utype == V_ASN1_BMPSTRING && (len & 1)) { ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_BMPSTRING_IS_WRONG_LENGTH); goto err; } if (utype == V_ASN1_UNIVERSALSTRING && (len & 3)) { ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH); goto err; } /* All based on ASN1_STRING and handled the same */ if (!*pval) { stmp = ASN1_STRING_type_new(utype); if (!stmp) { ASN1err(ASN1_F_ASN1_EX_C2I, ERR_R_MALLOC_FAILURE); goto err; } *pval = (ASN1_VALUE *)stmp; } else { stmp = (ASN1_STRING *)*pval; stmp->type = utype; } /* If we've already allocated a buffer use it */ if (*free_cont) { if (stmp->data) OPENSSL_free(stmp->data); stmp->data = (unsigned char *)cont; /* UGLY CAST! RL */ stmp->length = len; *free_cont = 0; } else { if (!ASN1_STRING_set(stmp, cont, len)) { ASN1err(ASN1_F_ASN1_EX_C2I, ERR_R_MALLOC_FAILURE); ASN1_STRING_free(stmp); *pval = NULL; goto err; } } break; } /* If ASN1_ANY and NULL type fix up value */ if (typ && (utype == V_ASN1_NULL)) typ->value.ptr = NULL; ret = 1; err: if (!ret) { ASN1_TYPE_free(typ); if (opval) *opval = NULL; } return ret; } Commit Message: CWE ID: CWE-119
int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it) { ASN1_VALUE **opval = NULL; ASN1_STRING *stmp; ASN1_TYPE *typ = NULL; int ret = 0; const ASN1_PRIMITIVE_FUNCS *pf; ASN1_INTEGER **tint; pf = it->funcs; if (pf && pf->prim_c2i) return pf->prim_c2i(pval, cont, len, utype, free_cont, it); /* If ANY type clear type and set pointer to internal value */ if (it->utype == V_ASN1_ANY) { if (!*pval) { typ = ASN1_TYPE_new(); if (typ == NULL) goto err; *pval = (ASN1_VALUE *)typ; } else typ = (ASN1_TYPE *)*pval; if (utype != typ->type) ASN1_TYPE_set(typ, utype, NULL); opval = pval; pval = &typ->value.asn1_value; } switch (utype) { case V_ASN1_OBJECT: if (!c2i_ASN1_OBJECT((ASN1_OBJECT **)pval, &cont, len)) goto err; break; case V_ASN1_NULL: if (len) { ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_NULL_IS_WRONG_LENGTH); goto err; } *pval = (ASN1_VALUE *)1; break; case V_ASN1_BOOLEAN: if (len != 1) { ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_BOOLEAN_IS_WRONG_LENGTH); goto err; } else { ASN1_BOOLEAN *tbool; tbool = (ASN1_BOOLEAN *)pval; *tbool = *cont; } break; case V_ASN1_BIT_STRING: if (!c2i_ASN1_BIT_STRING((ASN1_BIT_STRING **)pval, &cont, len)) goto err; break; case V_ASN1_INTEGER: case V_ASN1_ENUMERATED: tint = (ASN1_INTEGER **)pval; if (!c2i_ASN1_INTEGER(tint, &cont, len)) goto err; if (!c2i_ASN1_INTEGER(tint, &cont, len)) goto err; /* Fixup type to match the expected form */ (*tint)->type = utype | ((*tint)->type & V_ASN1_NEG); break; case V_ASN1_OCTET_STRING: case V_ASN1_NUMERICSTRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_T61STRING: case V_ASN1_VIDEOTEXSTRING: case V_ASN1_IA5STRING: case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: case V_ASN1_GRAPHICSTRING: case V_ASN1_VISIBLESTRING: case V_ASN1_GENERALSTRING: case V_ASN1_UNIVERSALSTRING: case V_ASN1_BMPSTRING: case V_ASN1_UTF8STRING: case V_ASN1_OTHER: case V_ASN1_SET: case V_ASN1_SEQUENCE: default: if (utype == V_ASN1_BMPSTRING && (len & 1)) { ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_BMPSTRING_IS_WRONG_LENGTH); goto err; } if (utype == V_ASN1_UNIVERSALSTRING && (len & 3)) { ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH); goto err; } /* All based on ASN1_STRING and handled the same */ if (!*pval) { stmp = ASN1_STRING_type_new(utype); if (!stmp) { ASN1err(ASN1_F_ASN1_EX_C2I, ERR_R_MALLOC_FAILURE); goto err; } *pval = (ASN1_VALUE *)stmp; } else { stmp = (ASN1_STRING *)*pval; stmp->type = utype; } /* If we've already allocated a buffer use it */ if (*free_cont) { if (stmp->data) OPENSSL_free(stmp->data); stmp->data = (unsigned char *)cont; /* UGLY CAST! RL */ stmp->length = len; *free_cont = 0; } else { if (!ASN1_STRING_set(stmp, cont, len)) { ASN1err(ASN1_F_ASN1_EX_C2I, ERR_R_MALLOC_FAILURE); ASN1_STRING_free(stmp); *pval = NULL; goto err; } } break; } /* If ASN1_ANY and NULL type fix up value */ if (typ && (utype == V_ASN1_NULL)) typ->value.ptr = NULL; ret = 1; err: if (!ret) { ASN1_TYPE_free(typ); if (opval) *opval = NULL; } return ret; }
165,212
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char header[MagickPathExtent]; const char *property; MagickBooleanType status; register const Quantum *p; register ssize_t i, x; size_t length; ssize_t count, y; unsigned char pixel[4], *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); if (IsRGBColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,RGBColorspace,exception); /* Write header. */ (void) ResetMagickMemory(header,' ',MagickPathExtent); length=CopyMagickString(header,"#?RGBE\n",MagickPathExtent); (void) WriteBlob(image,length,(unsigned char *) header); property=GetImageProperty(image,"comment",exception); if ((property != (const char *) NULL) && (strchr(property,'\n') == (char *) NULL)) { count=FormatLocaleString(header,MagickPathExtent,"#%s\n",property); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); } property=GetImageProperty(image,"hdr:exposure",exception); if (property != (const char *) NULL) { count=FormatLocaleString(header,MagickPathExtent,"EXPOSURE=%g\n", strtod(property,(char **) NULL)); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); } if (image->gamma != 0.0) { count=FormatLocaleString(header,MagickPathExtent,"GAMMA=%g\n",image->gamma); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); } count=FormatLocaleString(header,MagickPathExtent, "PRIMARIES=%g %g %g %g %g %g %g %g\n", image->chromaticity.red_primary.x,image->chromaticity.red_primary.y, image->chromaticity.green_primary.x,image->chromaticity.green_primary.y, image->chromaticity.blue_primary.x,image->chromaticity.blue_primary.y, image->chromaticity.white_point.x,image->chromaticity.white_point.y); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); length=CopyMagickString(header,"FORMAT=32-bit_rle_rgbe\n\n",MagickPathExtent); (void) WriteBlob(image,length,(unsigned char *) header); count=FormatLocaleString(header,MagickPathExtent,"-Y %.20g +X %.20g\n", (double) image->rows,(double) image->columns); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); /* Write HDR pixels. */ pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if ((image->columns >= 8) && (image->columns <= 0x7ffff)) { pixel[0]=2; pixel[1]=2; pixel[2]=(unsigned char) (image->columns >> 8); pixel[3]=(unsigned char) (image->columns & 0xff); count=WriteBlob(image,4*sizeof(*pixel),pixel); if (count != (ssize_t) (4*sizeof(*pixel))) break; } i=0; for (x=0; x < (ssize_t) image->columns; x++) { double gamma; pixel[0]=0; pixel[1]=0; pixel[2]=0; pixel[3]=0; gamma=QuantumScale*GetPixelRed(image,p); if ((QuantumScale*GetPixelGreen(image,p)) > gamma) gamma=QuantumScale*GetPixelGreen(image,p); if ((QuantumScale*GetPixelBlue(image,p)) > gamma) gamma=QuantumScale*GetPixelBlue(image,p); if (gamma > MagickEpsilon) { int exponent; gamma=frexp(gamma,&exponent)*256.0/gamma; pixel[0]=(unsigned char) (gamma*QuantumScale*GetPixelRed(image,p)); pixel[1]=(unsigned char) (gamma*QuantumScale*GetPixelGreen(image,p)); pixel[2]=(unsigned char) (gamma*QuantumScale*GetPixelBlue(image,p)); pixel[3]=(unsigned char) (exponent+128); } if ((image->columns >= 8) && (image->columns <= 0x7ffff)) { pixels[x]=pixel[0]; pixels[x+image->columns]=pixel[1]; pixels[x+2*image->columns]=pixel[2]; pixels[x+3*image->columns]=pixel[3]; } else { pixels[i++]=pixel[0]; pixels[i++]=pixel[1]; pixels[i++]=pixel[2]; pixels[i++]=pixel[3]; } p+=GetPixelChannels(image); } if ((image->columns >= 8) && (image->columns <= 0x7ffff)) { for (i=0; i < 4; i++) length=HDRWriteRunlengthPixels(image,&pixels[i*image->columns]); } else { count=WriteBlob(image,4*image->columns*sizeof(*pixels),pixels); if (count != (ssize_t) (4*image->columns*sizeof(*pixels))) break; } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); (void) CloseBlob(image); return(MagickTrue); } Commit Message: https://bugs.launchpad.net/ubuntu/+source/imagemagick/+bug/1537213 CWE ID: CWE-125
static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char header[MagickPathExtent]; const char *property; MagickBooleanType status; register const Quantum *p; register ssize_t i, x; size_t length; ssize_t count, y; unsigned char pixel[4], *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); if (IsRGBColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,RGBColorspace,exception); /* Write header. */ (void) ResetMagickMemory(header,' ',MagickPathExtent); length=CopyMagickString(header,"#?RGBE\n",MagickPathExtent); (void) WriteBlob(image,length,(unsigned char *) header); property=GetImageProperty(image,"comment",exception); if ((property != (const char *) NULL) && (strchr(property,'\n') == (char *) NULL)) { count=FormatLocaleString(header,MagickPathExtent,"#%s\n",property); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); } property=GetImageProperty(image,"hdr:exposure",exception); if (property != (const char *) NULL) { count=FormatLocaleString(header,MagickPathExtent,"EXPOSURE=%g\n", strtod(property,(char **) NULL)); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); } if (image->gamma != 0.0) { count=FormatLocaleString(header,MagickPathExtent,"GAMMA=%g\n", image->gamma); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); } count=FormatLocaleString(header,MagickPathExtent, "PRIMARIES=%g %g %g %g %g %g %g %g\n", image->chromaticity.red_primary.x,image->chromaticity.red_primary.y, image->chromaticity.green_primary.x,image->chromaticity.green_primary.y, image->chromaticity.blue_primary.x,image->chromaticity.blue_primary.y, image->chromaticity.white_point.x,image->chromaticity.white_point.y); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); length=CopyMagickString(header,"FORMAT=32-bit_rle_rgbe\n\n",MagickPathExtent); (void) WriteBlob(image,length,(unsigned char *) header); count=FormatLocaleString(header,MagickPathExtent,"-Y %.20g +X %.20g\n", (double) image->rows,(double) image->columns); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); /* Write HDR pixels. */ pixels=(unsigned char *) AcquireQuantumMemory(image->columns+128,4* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(pixels,0,4*(image->columns+128)*sizeof(*pixels)); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if ((image->columns >= 8) && (image->columns <= 0x7ffff)) { pixel[0]=2; pixel[1]=2; pixel[2]=(unsigned char) (image->columns >> 8); pixel[3]=(unsigned char) (image->columns & 0xff); count=WriteBlob(image,4*sizeof(*pixel),pixel); if (count != (ssize_t) (4*sizeof(*pixel))) break; } i=0; for (x=0; x < (ssize_t) image->columns; x++) { double gamma; pixel[0]=0; pixel[1]=0; pixel[2]=0; pixel[3]=0; gamma=QuantumScale*GetPixelRed(image,p); if ((QuantumScale*GetPixelGreen(image,p)) > gamma) gamma=QuantumScale*GetPixelGreen(image,p); if ((QuantumScale*GetPixelBlue(image,p)) > gamma) gamma=QuantumScale*GetPixelBlue(image,p); if (gamma > MagickEpsilon) { int exponent; gamma=frexp(gamma,&exponent)*256.0/gamma; pixel[0]=(unsigned char) (gamma*QuantumScale*GetPixelRed(image,p)); pixel[1]=(unsigned char) (gamma*QuantumScale*GetPixelGreen(image,p)); pixel[2]=(unsigned char) (gamma*QuantumScale*GetPixelBlue(image,p)); pixel[3]=(unsigned char) (exponent+128); } if ((image->columns >= 8) && (image->columns <= 0x7ffff)) { pixels[x]=pixel[0]; pixels[x+image->columns]=pixel[1]; pixels[x+2*image->columns]=pixel[2]; pixels[x+3*image->columns]=pixel[3]; } else { pixels[i++]=pixel[0]; pixels[i++]=pixel[1]; pixels[i++]=pixel[2]; pixels[i++]=pixel[3]; } p+=GetPixelChannels(image); } if ((image->columns >= 8) && (image->columns <= 0x7ffff)) { for (i=0; i < 4; i++) length=HDRWriteRunlengthPixels(image,&pixels[i*image->columns]); } else { count=WriteBlob(image,4*image->columns*sizeof(*pixels),pixels); if (count != (ssize_t) (4*image->columns*sizeof(*pixels))) break; } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); (void) CloseBlob(image); return(MagickTrue); }
168,807
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool TabLifecycleUnitSource::TabLifecycleUnit::CanFreeze( DecisionDetails* decision_details) const { DCHECK(decision_details->reasons().empty()); if (!IsValidStateChange(GetState(), LifecycleUnitState::PENDING_FREEZE, StateChangeReason::BROWSER_INITIATED)) { return false; } if (TabLoadTracker::Get()->GetLoadingState(GetWebContents()) != TabLoadTracker::LoadingState::LOADED) { return false; } if (GetWebContents()->GetVisibility() == content::Visibility::VISIBLE) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); IsMediaTabImpl(decision_details); if (decision_details->reasons().empty()) { decision_details->AddReason( DecisionSuccessReason::HEURISTIC_OBSERVED_TO_BE_SAFE); DCHECK(decision_details->IsPositive()); } return decision_details->IsPositive(); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
bool TabLifecycleUnitSource::TabLifecycleUnit::CanFreeze( DecisionDetails* decision_details) const { DCHECK(decision_details->reasons().empty()); if (!IsValidStateChange(GetState(), LifecycleUnitState::PENDING_FREEZE, StateChangeReason::BROWSER_INITIATED)) { return false; } if (TabLoadTracker::Get()->GetLoadingState(GetWebContents()) != TabLoadTracker::LoadingState::LOADED) { return false; } if (GetWebContents()->GetVisibility() == content::Visibility::VISIBLE) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); IsMediaTabImpl(decision_details); // Consult the local database to see if this tab could try to communicate with // the user while in background (don't check for the visibility here as // there's already a check for that above). CheckIfTabCanCommunicateWithUserWhileInBackground(GetWebContents(), decision_details); if (decision_details->reasons().empty()) { decision_details->AddReason( DecisionSuccessReason::HEURISTIC_OBSERVED_TO_BE_SAFE); } return decision_details->IsPositive(); }
172,219
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static OPJ_BOOL bmp_read_rle4_data(FILE* IN, OPJ_UINT8* pData, OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height) { OPJ_UINT32 x, y; OPJ_UINT8 *pix; const OPJ_UINT8 *beyond; beyond = pData + stride * height; pix = pData; x = y = 0U; while (y < height) { int c = getc(IN); if (c == EOF) { break; } if (c) { /* encoded mode */ int j; OPJ_UINT8 c1 = (OPJ_UINT8)getc(IN); for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { *pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU)); } } else { /* absolute mode */ c = getc(IN); if (c == EOF) { break; } if (c == 0x00) { /* EOL */ x = 0; y++; pix = pData + y * stride; } else if (c == 0x01) { /* EOP */ break; } else if (c == 0x02) { /* MOVE by dxdy */ c = getc(IN); x += (OPJ_UINT32)c; c = getc(IN); y += (OPJ_UINT32)c; pix = pData + y * stride + x; } else { /* 03 .. 255 : absolute mode */ int j; OPJ_UINT8 c1 = 0U; for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { if ((j & 1) == 0) { c1 = (OPJ_UINT8)getc(IN); } *pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU)); } if (((c & 3) == 1) || ((c & 3) == 2)) { /* skip padding byte */ getc(IN); } } } } /* while(y < height) */ return OPJ_TRUE; } Commit Message: convertbmp: detect invalid file dimensions early width/length dimensions read from bmp headers are not necessarily valid. For instance they may have been maliciously set to very large values with the intention to cause DoS (large memory allocation, stack overflow). In these cases we want to detect the invalid size as early as possible. This commit introduces a counter which verifies that the number of written bytes corresponds to the advertized width/length. See commit 8ee335227bbc for details. Signed-off-by: Young Xiao <[email protected]> CWE ID: CWE-400
static OPJ_BOOL bmp_read_rle4_data(FILE* IN, OPJ_UINT8* pData, OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height) { OPJ_UINT32 x, y, written; OPJ_UINT8 *pix; const OPJ_UINT8 *beyond; beyond = pData + stride * height; pix = pData; x = y = written = 0U; while (y < height) { int c = getc(IN); if (c == EOF) { break; } if (c) { /* encoded mode */ int j; OPJ_UINT8 c1 = (OPJ_UINT8)getc(IN); for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { *pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU)); written++; } } else { /* absolute mode */ c = getc(IN); if (c == EOF) { break; } if (c == 0x00) { /* EOL */ x = 0; y++; pix = pData + y * stride; } else if (c == 0x01) { /* EOP */ break; } else if (c == 0x02) { /* MOVE by dxdy */ c = getc(IN); x += (OPJ_UINT32)c; c = getc(IN); y += (OPJ_UINT32)c; pix = pData + y * stride + x; } else { /* 03 .. 255 : absolute mode */ int j; OPJ_UINT8 c1 = 0U; for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { if ((j & 1) == 0) { c1 = (OPJ_UINT8)getc(IN); } *pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU)); written++; } if (((c & 3) == 1) || ((c & 3) == 2)) { /* skip padding byte */ getc(IN); } } } } /* while(y < height) */ if (written != width * height) { fprintf(stderr, "warning, image's actual size does not match advertized one\n"); return OPJ_FALSE; } return OPJ_TRUE; }
170,210
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: wb_prep(netdissect_options *ndo, const struct pkt_prep *prep, u_int len) { int n; const struct pgstate *ps; const u_char *ep = ndo->ndo_snapend; ND_PRINT((ndo, " wb-prep:")); if (len < sizeof(*prep)) { return (-1); } n = EXTRACT_32BITS(&prep->pp_n); ps = (const struct pgstate *)(prep + 1); while (--n >= 0 && ND_TTEST(*ps)) { const struct id_off *io, *ie; char c = '<'; ND_PRINT((ndo, " %u/%s:%u", EXTRACT_32BITS(&ps->slot), ipaddr_string(ndo, &ps->page.p_sid), EXTRACT_32BITS(&ps->page.p_uid))); io = (const struct id_off *)(ps + 1); for (ie = io + ps->nid; io < ie && ND_TTEST(*io); ++io) { ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off))); c = ','; } ND_PRINT((ndo, ">")); ps = (const struct pgstate *)io; } return ((const u_char *)ps <= ep? 0 : -1); } Commit Message: CVE-2017-13014/White Board: Do more bounds checks. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). While we're at it, print a truncation error if the packets are truncated, rather than just, in effect, ignoring the result of the routines that print particular packet types. CWE ID: CWE-125
wb_prep(netdissect_options *ndo, const struct pkt_prep *prep, u_int len) { int n; const struct pgstate *ps; const u_char *ep = ndo->ndo_snapend; ND_PRINT((ndo, " wb-prep:")); if (len < sizeof(*prep) || !ND_TTEST(*prep)) return (-1); n = EXTRACT_32BITS(&prep->pp_n); ps = (const struct pgstate *)(prep + 1); while (--n >= 0 && ND_TTEST(*ps)) { const struct id_off *io, *ie; char c = '<'; ND_PRINT((ndo, " %u/%s:%u", EXTRACT_32BITS(&ps->slot), ipaddr_string(ndo, &ps->page.p_sid), EXTRACT_32BITS(&ps->page.p_uid))); io = (const struct id_off *)(ps + 1); for (ie = io + ps->nid; io < ie && ND_TTEST(*io); ++io) { ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off))); c = ','; } ND_PRINT((ndo, ">")); ps = (const struct pgstate *)io; } return ((const u_char *)ps <= ep? 0 : -1); }
167,878
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintPreviewUI::SetPrintPreviewDataForIndex( int index, const base::RefCountedBytes* data) { print_preview_data_service()->SetDataEntry(preview_ui_addr_str_, index, data); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewUI::SetPrintPreviewDataForIndex( int index, const base::RefCountedBytes* data) { print_preview_data_service()->SetDataEntry(id_, index, data); }
170,843
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: TaskService::TaskService() : next_instance_id_(0), bound_instance_id_(kInvalidInstanceId) {} Commit Message: Change ReadWriteLock to Lock+ConditionVariable in TaskService There are non-trivial performance implications of using shared SRWLocking on Windows as more state has to be checked. Since there are only two uses of the ReadWriteLock in Chromium after over 1 year, the decision is to remove it. BUG=758721 Change-Id: I84d1987d7b624a89e896eb37184ee50845c39d80 Reviewed-on: https://chromium-review.googlesource.com/634423 Commit-Queue: Robert Liao <[email protected]> Reviewed-by: Takashi Toyoshima <[email protected]> Reviewed-by: Francois Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#497632} CWE ID: CWE-20
TaskService::TaskService()
172,213
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mark_desktop_file_trusted (CommonJob *common, GCancellable *cancellable, GFile *file, gboolean interactive) { char *contents, *new_contents; gsize length, new_length; GError *error; guint32 current_perms, new_perms; int response; GFileInfo *info; retry: error = NULL; if (!g_file_load_contents (file, cancellable, &contents, &length, NULL, &error)) { if (interactive) { response = run_error (common, g_strdup (_("Unable to mark launcher trusted (executable)")), error->message, NULL, FALSE, CANCEL, RETRY, NULL); } else { response = 0; } if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT) { abort_job (common); } else if (response == 1) { goto retry; } else { g_assert_not_reached (); } goto out; } if (!g_str_has_prefix (contents, "#!")) { new_length = length + strlen (TRUSTED_SHEBANG); new_contents = g_malloc (new_length); strcpy (new_contents, TRUSTED_SHEBANG); memcpy (new_contents + strlen (TRUSTED_SHEBANG), contents, length); if (!g_file_replace_contents (file, new_contents, new_length, NULL, FALSE, 0, NULL, cancellable, &error)) { g_free (contents); g_free (new_contents); if (interactive) { response = run_error (common, g_strdup (_("Unable to mark launcher trusted (executable)")), error->message, NULL, FALSE, CANCEL, RETRY, NULL); } else { response = 0; } if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT) { abort_job (common); } else if (response == 1) { goto retry; } else { g_assert_not_reached (); } goto out; } g_free (new_contents); } g_free (contents); info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_UNIX_MODE, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, common->cancellable, &error); if (info == NULL) { if (interactive) { response = run_error (common, g_strdup (_("Unable to mark launcher trusted (executable)")), error->message, NULL, FALSE, CANCEL, RETRY, NULL); } else { response = 0; } if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT) { abort_job (common); } else if (response == 1) { goto retry; } else { g_assert_not_reached (); } goto out; } if (g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_UNIX_MODE)) { current_perms = g_file_info_get_attribute_uint32 (info, G_FILE_ATTRIBUTE_UNIX_MODE); new_perms = current_perms | S_IXGRP | S_IXUSR | S_IXOTH; if ((current_perms != new_perms) && !g_file_set_attribute_uint32 (file, G_FILE_ATTRIBUTE_UNIX_MODE, new_perms, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, common->cancellable, &error)) { g_object_unref (info); if (interactive) { response = run_error (common, g_strdup (_("Unable to mark launcher trusted (executable)")), error->message, NULL, FALSE, CANCEL, RETRY, NULL); } else { response = 0; } if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT) { abort_job (common); } else if (response == 1) { goto retry; } else { g_assert_not_reached (); } goto out; } } g_object_unref (info); out: ; } Commit Message: mime-actions: use file metadata for trusting desktop files Currently we only trust desktop files that have the executable bit set, and don't replace the displayed icon or the displayed name until it's trusted, which prevents for running random programs by a malicious desktop file. However, the executable permission is preserved if the desktop file comes from a compressed file. To prevent this, add a metadata::trusted metadata to the file once the user acknowledges the file as trusted. This adds metadata to the file, which cannot be added unless it has access to the computer. Also remove the SHEBANG "trusted" content we were putting inside the desktop file, since that doesn't add more security since it can come with the file itself. https://bugzilla.gnome.org/show_bug.cgi?id=777991 CWE ID: CWE-20
mark_desktop_file_trusted (CommonJob *common, mark_desktop_file_executable (CommonJob *common, GCancellable *cancellable, GFile *file, gboolean interactive) { GError *error; guint32 current_perms, new_perms; int response; GFileInfo *info; retry: error = NULL; info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_UNIX_MODE, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, common->cancellable, &error); if (info == NULL) { if (interactive) { response = run_error (common, g_strdup (_("Unable to mark launcher trusted (executable)")), error->message, NULL, FALSE, CANCEL, RETRY, NULL); } else { response = 0; } if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT) { abort_job (common); } else if (response == 1) { goto retry; } else { g_assert_not_reached (); } goto out; } if (g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_UNIX_MODE)) { current_perms = g_file_info_get_attribute_uint32 (info, G_FILE_ATTRIBUTE_UNIX_MODE); new_perms = current_perms | S_IXGRP | S_IXUSR | S_IXOTH; if ((current_perms != new_perms) && !g_file_set_attribute_uint32 (file, G_FILE_ATTRIBUTE_UNIX_MODE, new_perms, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, common->cancellable, &error)) { g_object_unref (info); if (interactive) { response = run_error (common, g_strdup (_("Unable to mark launcher trusted (executable)")), error->message, NULL, FALSE, CANCEL, RETRY, NULL); } else { response = 0; } if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT) { abort_job (common); } else if (response == 1) { goto retry; } else { g_assert_not_reached (); } goto out; } } g_object_unref (info); out: ; }
167,748
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: kex_input_kexinit(int type, u_int32_t seq, void *ctxt) { struct ssh *ssh = ctxt; struct kex *kex = ssh->kex; const u_char *ptr; u_int i; size_t dlen; int r; debug("SSH2_MSG_KEXINIT received"); if (kex == NULL) return SSH_ERR_INVALID_ARGUMENT; ptr = sshpkt_ptr(ssh, &dlen); if ((r = sshbuf_put(kex->peer, ptr, dlen)) != 0) return r; /* discard packet */ for (i = 0; i < KEX_COOKIE_LEN; i++) if ((r = sshpkt_get_u8(ssh, NULL)) != 0) return r; for (i = 0; i < PROPOSAL_MAX; i++) if ((r = sshpkt_get_string(ssh, NULL, NULL)) != 0) return r; /* * XXX RFC4253 sec 7: "each side MAY guess" - currently no supported * KEX method has the server move first, but a server might be using * a custom method or one that we otherwise don't support. We should * be prepared to remember first_kex_follows here so we can eat a * packet later. * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means * for cases where the server *doesn't* go first. I guess we should * ignore it when it is set for these cases, which is what we do now. */ if ((r = sshpkt_get_u8(ssh, NULL)) != 0 || /* first_kex_follows */ (r = sshpkt_get_u32(ssh, NULL)) != 0 || /* reserved */ (r = sshpkt_get_end(ssh)) != 0) return r; if (!(kex->flags & KEX_INIT_SENT)) if ((r = kex_send_kexinit(ssh)) != 0) return r; if ((r = kex_choose_conf(ssh)) != 0) return r; if (kex->kex_type < KEX_MAX && kex->kex[kex->kex_type] != NULL) return (kex->kex[kex->kex_type])(ssh); return SSH_ERR_INTERNAL_ERROR; } Commit Message: upstream commit Unregister the KEXINIT handler after message has been received. Otherwise an unauthenticated peer can repeat the KEXINIT and cause allocation of up to 128MB -- until the connection is closed. Reported by shilei-c at 360.cn Upstream-ID: 43649ae12a27ef94290db16d1a98294588b75c05 CWE ID: CWE-399
kex_input_kexinit(int type, u_int32_t seq, void *ctxt) { struct ssh *ssh = ctxt; struct kex *kex = ssh->kex; const u_char *ptr; u_int i; size_t dlen; int r; debug("SSH2_MSG_KEXINIT received"); if (kex == NULL) return SSH_ERR_INVALID_ARGUMENT; ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, NULL); ptr = sshpkt_ptr(ssh, &dlen); if ((r = sshbuf_put(kex->peer, ptr, dlen)) != 0) return r; /* discard packet */ for (i = 0; i < KEX_COOKIE_LEN; i++) if ((r = sshpkt_get_u8(ssh, NULL)) != 0) return r; for (i = 0; i < PROPOSAL_MAX; i++) if ((r = sshpkt_get_string(ssh, NULL, NULL)) != 0) return r; /* * XXX RFC4253 sec 7: "each side MAY guess" - currently no supported * KEX method has the server move first, but a server might be using * a custom method or one that we otherwise don't support. We should * be prepared to remember first_kex_follows here so we can eat a * packet later. * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means * for cases where the server *doesn't* go first. I guess we should * ignore it when it is set for these cases, which is what we do now. */ if ((r = sshpkt_get_u8(ssh, NULL)) != 0 || /* first_kex_follows */ (r = sshpkt_get_u32(ssh, NULL)) != 0 || /* reserved */ (r = sshpkt_get_end(ssh)) != 0) return r; if (!(kex->flags & KEX_INIT_SENT)) if ((r = kex_send_kexinit(ssh)) != 0) return r; if ((r = kex_choose_conf(ssh)) != 0) return r; if (kex->kex_type < KEX_MAX && kex->kex[kex->kex_type] != NULL) return (kex->kex[kex->kex_type])(ssh); return SSH_ERR_INTERNAL_ERROR; }
166,902
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebRunnerMainDelegate::CreateContentBrowserClient() { DCHECK(!browser_client_); browser_client_ = std::make_unique<WebRunnerContentBrowserClient>( std::move(context_channel_)); return browser_client_.get(); } Commit Message: [fuchsia] Implement browser tests for WebRunner Context service. Tests may interact with the WebRunner FIDL services and the underlying browser objects for end to end testing of service and browser functionality. * Add a browser test launcher main() for WebRunner. * Add some simple navigation tests. * Wire up GoBack()/GoForward() FIDL calls. * Add embedded test server resources and initialization logic. * Add missing deletion & notification calls to BrowserContext dtor. * Use FIDL events for navigation state changes. * Bug fixes: ** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(), so that they may use the MessageLoop during teardown. ** Fix Frame dtor to allow for null WindowTreeHosts (headless case) ** Fix std::move logic in Frame ctor which lead to no WebContents observer being registered. Bug: 871594 Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac Reviewed-on: https://chromium-review.googlesource.com/1164539 Commit-Queue: Kevin Marshall <[email protected]> Reviewed-by: Wez <[email protected]> Reviewed-by: Fabrice de Gans-Riberi <[email protected]> Reviewed-by: Scott Violet <[email protected]> Cr-Commit-Position: refs/heads/master@{#584155} CWE ID: CWE-264
WebRunnerMainDelegate::CreateContentBrowserClient() { DCHECK(context_channel_); DCHECK(!browser_client_); browser_client_ = std::make_unique<WebRunnerContentBrowserClient>( std::move(context_channel_)); return browser_client_.get(); }
172,159
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltDocumentFunctionLoadDocument(xmlXPathParserContextPtr ctxt, xmlChar* URI) { xsltTransformContextPtr tctxt; xmlURIPtr uri; xmlChar *fragment; xsltDocumentPtr idoc; /* document info */ xmlDocPtr doc; xmlXPathContextPtr xptrctxt = NULL; xmlXPathObjectPtr resObj = NULL; tctxt = xsltXPathGetTransformContext(ctxt); if (tctxt == NULL) { xsltTransformError(NULL, NULL, NULL, "document() : internal error tctxt == NULL\n"); valuePush(ctxt, xmlXPathNewNodeSet(NULL)); return; } uri = xmlParseURI((const char *) URI); if (uri == NULL) { xsltTransformError(tctxt, NULL, NULL, "document() : failed to parse URI\n"); valuePush(ctxt, xmlXPathNewNodeSet(NULL)); return; } /* * check for and remove fragment identifier */ fragment = (xmlChar *)uri->fragment; if (fragment != NULL) { xmlChar *newURI; uri->fragment = NULL; newURI = xmlSaveUri(uri); idoc = xsltLoadDocument(tctxt, newURI); xmlFree(newURI); } else idoc = xsltLoadDocument(tctxt, URI); xmlFreeURI(uri); if (idoc == NULL) { if ((URI == NULL) || (URI[0] == '#') || ((tctxt->style->doc != NULL) && (xmlStrEqual(tctxt->style->doc->URL, URI)))) { /* * This selects the stylesheet's doc itself. */ doc = tctxt->style->doc; } else { valuePush(ctxt, xmlXPathNewNodeSet(NULL)); if (fragment != NULL) xmlFree(fragment); return; } } else doc = idoc->doc; if (fragment == NULL) { valuePush(ctxt, xmlXPathNewNodeSet((xmlNodePtr) doc)); return; } /* use XPointer of HTML location for fragment ID */ #ifdef LIBXML_XPTR_ENABLED xptrctxt = xmlXPtrNewContext(doc, NULL, NULL); if (xptrctxt == NULL) { xsltTransformError(tctxt, NULL, NULL, "document() : internal error xptrctxt == NULL\n"); goto out_fragment; } resObj = xmlXPtrEval(fragment, xptrctxt); xmlXPathFreeContext(xptrctxt); #endif xmlFree(fragment); if (resObj == NULL) goto out_fragment; switch (resObj->type) { case XPATH_NODESET: break; case XPATH_UNDEFINED: case XPATH_BOOLEAN: case XPATH_NUMBER: case XPATH_STRING: case XPATH_POINT: case XPATH_USERS: case XPATH_XSLT_TREE: case XPATH_RANGE: case XPATH_LOCATIONSET: xsltTransformError(tctxt, NULL, NULL, "document() : XPointer does not select a node set: #%s\n", fragment); goto out_object; } valuePush(ctxt, resObj); return; out_object: xmlXPathFreeObject(resObj); out_fragment: valuePush(ctxt, xmlXPathNewNodeSet(NULL)); } 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
xsltDocumentFunctionLoadDocument(xmlXPathParserContextPtr ctxt, xmlChar* URI) { xsltTransformContextPtr tctxt; xmlURIPtr uri; xmlChar *fragment; xsltDocumentPtr idoc; /* document info */ xmlDocPtr doc; xmlXPathContextPtr xptrctxt = NULL; xmlXPathObjectPtr resObj = NULL; tctxt = xsltXPathGetTransformContext(ctxt); if (tctxt == NULL) { xsltTransformError(NULL, NULL, NULL, "document() : internal error tctxt == NULL\n"); valuePush(ctxt, xmlXPathNewNodeSet(NULL)); return; } uri = xmlParseURI((const char *) URI); if (uri == NULL) { xsltTransformError(tctxt, NULL, NULL, "document() : failed to parse URI\n"); valuePush(ctxt, xmlXPathNewNodeSet(NULL)); return; } /* * check for and remove fragment identifier */ fragment = (xmlChar *)uri->fragment; if (fragment != NULL) { xmlChar *newURI; uri->fragment = NULL; newURI = xmlSaveUri(uri); idoc = xsltLoadDocument(tctxt, newURI); xmlFree(newURI); } else idoc = xsltLoadDocument(tctxt, URI); xmlFreeURI(uri); if (idoc == NULL) { if ((URI == NULL) || (URI[0] == '#') || ((tctxt->style->doc != NULL) && (xmlStrEqual(tctxt->style->doc->URL, URI)))) { /* * This selects the stylesheet's doc itself. */ doc = tctxt->style->doc; } else { valuePush(ctxt, xmlXPathNewNodeSet(NULL)); if (fragment != NULL) xmlFree(fragment); return; } } else doc = idoc->doc; if (fragment == NULL) { valuePush(ctxt, xmlXPathNewNodeSet((xmlNodePtr) doc)); return; } /* use XPointer of HTML location for fragment ID */ #ifdef LIBXML_XPTR_ENABLED xptrctxt = xmlXPtrNewContext(doc, NULL, NULL); if (xptrctxt == NULL) { xsltTransformError(tctxt, NULL, NULL, "document() : internal error xptrctxt == NULL\n"); goto out_fragment; } resObj = xmlXPtrEval(fragment, xptrctxt); xmlXPathFreeContext(xptrctxt); #endif if (resObj == NULL) goto out_fragment; switch (resObj->type) { case XPATH_NODESET: break; case XPATH_UNDEFINED: case XPATH_BOOLEAN: case XPATH_NUMBER: case XPATH_STRING: case XPATH_POINT: case XPATH_USERS: case XPATH_XSLT_TREE: case XPATH_RANGE: case XPATH_LOCATIONSET: xsltTransformError(tctxt, NULL, NULL, "document() : XPointer does not select a node set: #%s\n", fragment); goto out_object; } valuePush(ctxt, resObj); xmlFree(fragment); return; out_object: xmlXPathFreeObject(resObj); out_fragment: valuePush(ctxt, xmlXPathNewNodeSet(NULL)); xmlFree(fragment); }
173,301
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: atol10(const char *p, size_t char_cnt) { uint64_t l; int digit; l = 0; digit = *p - '0'; while (digit >= 0 && digit < 10 && char_cnt-- > 0) { l = (l * 10) + digit; digit = *++p - '0'; } return (l); } Commit Message: Do something sensible for empty strings to make fuzzers happy. CWE ID: CWE-125
atol10(const char *p, size_t char_cnt) { uint64_t l; int digit; if (char_cnt == 0) return (0); l = 0; digit = *p - '0'; while (digit >= 0 && digit < 10 && char_cnt-- > 0) { l = (l * 10) + digit; digit = *++p - '0'; } return (l); }
167,767
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string SanitizeRemoteFrontendURL(const std::string& value) { GURL url(net::UnescapeURLComponent(value, net::UnescapeRule::SPACES | net::UnescapeRule::PATH_SEPARATORS | net::UnescapeRule::URL_SPECIAL_CHARS_EXCEPT_PATH_SEPARATORS | net::UnescapeRule::REPLACE_PLUS_WITH_SPACE)); std::string path = url.path(); std::vector<std::string> parts = base::SplitString( path, "/", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); std::string revision = parts.size() > 2 ? parts[2] : ""; revision = SanitizeRevision(revision); std::string filename = parts.size() ? parts[parts.size() - 1] : ""; if (filename != "devtools.html") filename = "inspector.html"; path = base::StringPrintf("/serve_rev/%s/%s", revision.c_str(), filename.c_str()); std::string sanitized = SanitizeFrontendURL(url, url::kHttpsScheme, kRemoteFrontendDomain, path, true).spec(); return net::EscapeQueryParamValue(sanitized, false); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
std::string SanitizeRemoteFrontendURL(const std::string& value) {
172,463
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: error::Error GLES2DecoderImpl::HandleBeginQueryEXT( uint32_t immediate_data_size, const volatile void* cmd_data) { const volatile gles2::cmds::BeginQueryEXT& c = *static_cast<const volatile gles2::cmds::BeginQueryEXT*>(cmd_data); GLenum target = static_cast<GLenum>(c.target); GLuint client_id = static_cast<GLuint>(c.id); int32_t sync_shm_id = static_cast<int32_t>(c.sync_data_shm_id); uint32_t sync_shm_offset = static_cast<uint32_t>(c.sync_data_shm_offset); switch (target) { case GL_COMMANDS_ISSUED_CHROMIUM: case GL_LATENCY_QUERY_CHROMIUM: case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM: case GL_GET_ERROR_QUERY_CHROMIUM: break; case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM: case GL_COMMANDS_COMPLETED_CHROMIUM: if (!features().chromium_sync_query) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for commands completed queries"); return error::kNoError; } break; case GL_SAMPLES_PASSED_ARB: if (!features().occlusion_query) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for occlusion queries"); return error::kNoError; } break; case GL_ANY_SAMPLES_PASSED: case GL_ANY_SAMPLES_PASSED_CONSERVATIVE: if (!features().occlusion_query_boolean) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for boolean occlusion queries"); return error::kNoError; } break; case GL_TIME_ELAPSED: if (!query_manager_->GPUTimingAvailable()) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for timing queries"); return error::kNoError; } break; case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: if (feature_info_->IsWebGL2OrES3Context()) { break; } FALLTHROUGH; default: LOCAL_SET_GL_ERROR( GL_INVALID_ENUM, "glBeginQueryEXT", "unknown query target"); return error::kNoError; } if (query_manager_->GetActiveQuery(target)) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, "glBeginQueryEXT", "query already in progress"); return error::kNoError; } if (client_id == 0) { LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "glBeginQueryEXT", "id is 0"); return error::kNoError; } scoped_refptr<gpu::Buffer> buffer = GetSharedMemoryBuffer(sync_shm_id); if (!buffer) return error::kInvalidArguments; QuerySync* sync = static_cast<QuerySync*>( buffer->GetDataAddress(sync_shm_offset, sizeof(QuerySync))); if (!sync) return error::kOutOfBounds; QueryManager::Query* query = query_manager_->GetQuery(client_id); if (!query) { if (!query_manager_->IsValidQuery(client_id)) { LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "glBeginQueryEXT", "id not made by glGenQueriesEXT"); return error::kNoError; } query = query_manager_->CreateQuery(target, client_id, std::move(buffer), sync); } else { if (query->target() != target) { LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "glBeginQueryEXT", "target does not match"); return error::kNoError; } else if (query->sync() != sync) { DLOG(ERROR) << "Shared memory used by query not the same as before"; return error::kInvalidArguments; } } query_manager_->BeginQuery(query); return error::kNoError; } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416
error::Error GLES2DecoderImpl::HandleBeginQueryEXT( uint32_t immediate_data_size, const volatile void* cmd_data) { const volatile gles2::cmds::BeginQueryEXT& c = *static_cast<const volatile gles2::cmds::BeginQueryEXT*>(cmd_data); GLenum target = static_cast<GLenum>(c.target); GLuint client_id = static_cast<GLuint>(c.id); int32_t sync_shm_id = static_cast<int32_t>(c.sync_data_shm_id); uint32_t sync_shm_offset = static_cast<uint32_t>(c.sync_data_shm_offset); switch (target) { case GL_COMMANDS_ISSUED_CHROMIUM: case GL_LATENCY_QUERY_CHROMIUM: case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM: case GL_GET_ERROR_QUERY_CHROMIUM: break; case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM: case GL_COMMANDS_COMPLETED_CHROMIUM: if (!features().chromium_sync_query) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for commands completed queries"); return error::kNoError; } break; case GL_PROGRAM_COMPLETION_QUERY_CHROMIUM: if (!features().chromium_completion_query) { LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for program completion queries"); return error::kNoError; } break; case GL_SAMPLES_PASSED_ARB: if (!features().occlusion_query) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for occlusion queries"); return error::kNoError; } break; case GL_ANY_SAMPLES_PASSED: case GL_ANY_SAMPLES_PASSED_CONSERVATIVE: if (!features().occlusion_query_boolean) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for boolean occlusion queries"); return error::kNoError; } break; case GL_TIME_ELAPSED: if (!query_manager_->GPUTimingAvailable()) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for timing queries"); return error::kNoError; } break; case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: if (feature_info_->IsWebGL2OrES3Context()) { break; } FALLTHROUGH; default: LOCAL_SET_GL_ERROR( GL_INVALID_ENUM, "glBeginQueryEXT", "unknown query target"); return error::kNoError; } if (query_manager_->GetActiveQuery(target)) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, "glBeginQueryEXT", "query already in progress"); return error::kNoError; } if (client_id == 0) { LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "glBeginQueryEXT", "id is 0"); return error::kNoError; } scoped_refptr<gpu::Buffer> buffer = GetSharedMemoryBuffer(sync_shm_id); if (!buffer) return error::kInvalidArguments; QuerySync* sync = static_cast<QuerySync*>( buffer->GetDataAddress(sync_shm_offset, sizeof(QuerySync))); if (!sync) return error::kOutOfBounds; QueryManager::Query* query = query_manager_->GetQuery(client_id); if (!query) { if (!query_manager_->IsValidQuery(client_id)) { LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "glBeginQueryEXT", "id not made by glGenQueriesEXT"); return error::kNoError; } query = query_manager_->CreateQuery(target, client_id, std::move(buffer), sync); } else { if (query->target() != target) { LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "glBeginQueryEXT", "target does not match"); return error::kNoError; } else if (query->sync() != sync) { DLOG(ERROR) << "Shared memory used by query not the same as before"; return error::kInvalidArguments; } } query_manager_->BeginQuery(query); return error::kNoError; }
172,529
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline void find_entity_for_char( unsigned int k, enum entity_charset charset, const entity_stage1_row *table, const unsigned char **entity, size_t *entity_len, unsigned char *old, size_t oldlen, size_t *cursor) { unsigned stage1_idx = ENT_STAGE1_INDEX(k); const entity_stage3_row *c; if (stage1_idx > 0x1D) { *entity = NULL; *entity_len = 0; return; } c = &table[stage1_idx][ENT_STAGE2_INDEX(k)][ENT_STAGE3_INDEX(k)]; if (!c->ambiguous) { *entity = (const unsigned char *)c->data.ent.entity; *entity_len = c->data.ent.entity_len; } else { /* peek at next char */ size_t cursor_before = *cursor; int status = SUCCESS; unsigned next_char; if (!(*cursor < oldlen)) goto no_suitable_2nd; next_char = get_next_char(charset, old, oldlen, cursor, &status); if (status == FAILURE) goto no_suitable_2nd; { const entity_multicodepoint_row *s, *e; s = &c->data.multicodepoint_table[1]; e = s - 1 + c->data.multicodepoint_table[0].leading_entry.size; /* we could do a binary search but it's not worth it since we have * at most two entries... */ for ( ; s <= e; s++) { if (s->normal_entry.second_cp == next_char) { *entity = s->normal_entry.entity; *entity_len = s->normal_entry.entity_len; return; } } } no_suitable_2nd: *cursor = cursor_before; *entity = (const unsigned char *) c->data.multicodepoint_table[0].leading_entry.default_entity; *entity_len = c->data.multicodepoint_table[0].leading_entry.default_entity_len; } } Commit Message: Fix bug #72135 - don't create strings with lengths outside int range CWE ID: CWE-190
static inline void find_entity_for_char( unsigned int k, enum entity_charset charset, const entity_stage1_row *table, const unsigned char **entity, size_t *entity_len, unsigned char *old, size_t oldlen, size_t *cursor) { unsigned stage1_idx = ENT_STAGE1_INDEX(k); const entity_stage3_row *c; if (stage1_idx > 0x1D) { *entity = NULL; *entity_len = 0; return; } c = &table[stage1_idx][ENT_STAGE2_INDEX(k)][ENT_STAGE3_INDEX(k)]; if (!c->ambiguous) { *entity = (const unsigned char *)c->data.ent.entity; *entity_len = c->data.ent.entity_len; } else { /* peek at next char */ size_t cursor_before = *cursor; int status = SUCCESS; unsigned next_char; if (!(*cursor < oldlen)) goto no_suitable_2nd; next_char = get_next_char(charset, old, oldlen, cursor, &status); if (status == FAILURE) goto no_suitable_2nd; { const entity_multicodepoint_row *s, *e; s = &c->data.multicodepoint_table[1]; e = s - 1 + c->data.multicodepoint_table[0].leading_entry.size; /* we could do a binary search but it's not worth it since we have * at most two entries... */ for ( ; s <= e; s++) { if (s->normal_entry.second_cp == next_char) { *entity = s->normal_entry.entity; *entity_len = s->normal_entry.entity_len; return; } } } no_suitable_2nd: *cursor = cursor_before; *entity = (const unsigned char *) c->data.multicodepoint_table[0].leading_entry.default_entity; *entity_len = c->data.multicodepoint_table[0].leading_entry.default_entity_len; } }
167,171
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: LayoutUnit LayoutBlockFlow::adjustBlockChildForPagination(LayoutUnit logicalTop, LayoutBox& child, bool atBeforeSideOfBlock) { LayoutBlockFlow* childBlockFlow = child.isLayoutBlockFlow() ? toLayoutBlockFlow(&child) : 0; LayoutUnit newLogicalTop = applyBeforeBreak(child, logicalTop); LayoutUnit logicalTopBeforeUnsplittableAdjustment = newLogicalTop; LayoutUnit logicalTopAfterUnsplittableAdjustment = adjustForUnsplittableChild(child, newLogicalTop); LayoutUnit paginationStrut = 0; LayoutUnit unsplittableAdjustmentDelta = logicalTopAfterUnsplittableAdjustment - logicalTopBeforeUnsplittableAdjustment; LayoutUnit childLogicalHeight = child.logicalHeight(); if (unsplittableAdjustmentDelta) { setPageBreak(newLogicalTop, childLogicalHeight - unsplittableAdjustmentDelta); paginationStrut = unsplittableAdjustmentDelta; } else if (childBlockFlow && childBlockFlow->paginationStrut()) { paginationStrut = childBlockFlow->paginationStrut(); } if (paginationStrut) { if (atBeforeSideOfBlock && logicalTop == newLogicalTop && !isOutOfFlowPositioned() && !isTableCell()) { paginationStrut += logicalTop; if (isFloating()) paginationStrut += marginBefore(); // Floats' margins do not collapse with page or column boundaries. setPaginationStrut(paginationStrut); if (childBlockFlow) childBlockFlow->setPaginationStrut(0); } else { newLogicalTop += paginationStrut; } } if (!unsplittableAdjustmentDelta) { if (LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(newLogicalTop)) { LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(newLogicalTop, AssociateWithLatterPage); LayoutUnit spaceShortage = childLogicalHeight - remainingLogicalHeight; if (spaceShortage > 0) { LayoutUnit spaceShortageInLastColumn = intMod(spaceShortage, pageLogicalHeight); setPageBreak(newLogicalTop, spaceShortageInLastColumn ? spaceShortageInLastColumn : spaceShortage); } else if (remainingLogicalHeight == pageLogicalHeight && offsetFromLogicalTopOfFirstPage() + child.logicalTop()) { setPageBreak(newLogicalTop, childLogicalHeight); } } } setLogicalHeight(logicalHeight() + (newLogicalTop - logicalTop)); return newLogicalTop; } Commit Message: Consistently check if a block can handle pagination strut propagation. https://codereview.chromium.org/1360753002 got it right for inline child layout, but did nothing for block child layout. BUG=329421 [email protected],[email protected] Review URL: https://codereview.chromium.org/1387553002 Cr-Commit-Position: refs/heads/master@{#352429} CWE ID: CWE-22
LayoutUnit LayoutBlockFlow::adjustBlockChildForPagination(LayoutUnit logicalTop, LayoutBox& child, bool atBeforeSideOfBlock) { LayoutBlockFlow* childBlockFlow = child.isLayoutBlockFlow() ? toLayoutBlockFlow(&child) : 0; LayoutUnit newLogicalTop = applyBeforeBreak(child, logicalTop); LayoutUnit logicalTopBeforeUnsplittableAdjustment = newLogicalTop; LayoutUnit logicalTopAfterUnsplittableAdjustment = adjustForUnsplittableChild(child, newLogicalTop); LayoutUnit paginationStrut = 0; LayoutUnit unsplittableAdjustmentDelta = logicalTopAfterUnsplittableAdjustment - logicalTopBeforeUnsplittableAdjustment; LayoutUnit childLogicalHeight = child.logicalHeight(); if (unsplittableAdjustmentDelta) { setPageBreak(newLogicalTop, childLogicalHeight - unsplittableAdjustmentDelta); paginationStrut = unsplittableAdjustmentDelta; } else if (childBlockFlow && childBlockFlow->paginationStrut()) { paginationStrut = childBlockFlow->paginationStrut(); } if (paginationStrut) { if (atBeforeSideOfBlock && logicalTop == newLogicalTop && allowsPaginationStrut()) { paginationStrut += logicalTop; if (isFloating()) paginationStrut += marginBefore(); // Floats' margins do not collapse with page or column boundaries. setPaginationStrut(paginationStrut); if (childBlockFlow) childBlockFlow->setPaginationStrut(0); } else { newLogicalTop += paginationStrut; } } if (!unsplittableAdjustmentDelta) { if (LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(newLogicalTop)) { LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(newLogicalTop, AssociateWithLatterPage); LayoutUnit spaceShortage = childLogicalHeight - remainingLogicalHeight; if (spaceShortage > 0) { LayoutUnit spaceShortageInLastColumn = intMod(spaceShortage, pageLogicalHeight); setPageBreak(newLogicalTop, spaceShortageInLastColumn ? spaceShortageInLastColumn : spaceShortage); } else if (remainingLogicalHeight == pageLogicalHeight && offsetFromLogicalTopOfFirstPage() + child.logicalTop()) { setPageBreak(newLogicalTop, childLogicalHeight); } } } setLogicalHeight(logicalHeight() + (newLogicalTop - logicalTop)); return newLogicalTop; }
171,693
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: UsbChooserContext::UsbChooserContext(Profile* profile) : ChooserContextBase(profile, CONTENT_SETTINGS_TYPE_USB_GUARD, CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA), is_incognito_(profile->IsOffTheRecord()), client_binding_(this), weak_factory_(this) {} Commit Message: Enforce the WebUsbAllowDevicesForUrls policy This change modifies UsbChooserContext to use the UsbAllowDevicesForUrls class to consider devices allowed by the WebUsbAllowDevicesForUrls policy. The WebUsbAllowDevicesForUrls policy overrides the other WebUSB policies. Unit tests are also added to ensure that the policy is being enforced correctly. The design document for this feature is found at: https://docs.google.com/document/d/1MPvsrWiVD_jAC8ELyk8njFpy6j1thfVU5aWT3TCWE8w Bug: 854329 Change-Id: I5f82e662ca9dc544da5918eae766b5535a31296b Reviewed-on: https://chromium-review.googlesource.com/c/1259289 Commit-Queue: Ovidio Henriquez <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Julian Pastarmov <[email protected]> Cr-Commit-Position: refs/heads/master@{#597926} CWE ID: CWE-119
UsbChooserContext::UsbChooserContext(Profile* profile) : ChooserContextBase(profile, CONTENT_SETTINGS_TYPE_USB_GUARD, CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA), is_incognito_(profile->IsOffTheRecord()), client_binding_(this),
173,336
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xdr_krb5_principal(XDR *xdrs, krb5_principal *objp) { int ret; char *p = NULL; krb5_principal pr = NULL; static krb5_context context = NULL; /* using a static context here is ugly, but should work ok, and the other solutions are even uglier */ if (!context && kadm5_init_krb5_context(&context)) return(FALSE); switch(xdrs->x_op) { case XDR_ENCODE: if (*objp) { if((ret = krb5_unparse_name(context, *objp, &p)) != 0) return FALSE; } if(!xdr_nullstring(xdrs, &p)) return FALSE; if (p) free(p); break; case XDR_DECODE: if(!xdr_nullstring(xdrs, &p)) return FALSE; if (p) { ret = krb5_parse_name(context, p, &pr); if(ret != 0) return FALSE; *objp = pr; free(p); } else *objp = NULL; break; case XDR_FREE: if(*objp != NULL) krb5_free_principal(context, *objp); break; } return TRUE; } Commit Message: Fix kadm5/gssrpc XDR double free [CVE-2014-9421] [MITKRB5-SA-2015-001] In auth_gssapi_unwrap_data(), do not free partial deserialization results upon failure to deserialize. This responsibility belongs to the callers, svctcp_getargs() and svcudp_getargs(); doing it in the unwrap function results in freeing the results twice. In xdr_krb5_tl_data() and xdr_krb5_principal(), null out the pointers we are freeing, as other XDR functions such as xdr_bytes() and xdr_string(). ticket: 8056 (new) target_version: 1.13.1 tags: pullup CWE ID:
xdr_krb5_principal(XDR *xdrs, krb5_principal *objp) { int ret; char *p = NULL; krb5_principal pr = NULL; static krb5_context context = NULL; /* using a static context here is ugly, but should work ok, and the other solutions are even uglier */ if (!context && kadm5_init_krb5_context(&context)) return(FALSE); switch(xdrs->x_op) { case XDR_ENCODE: if (*objp) { if((ret = krb5_unparse_name(context, *objp, &p)) != 0) return FALSE; } if(!xdr_nullstring(xdrs, &p)) return FALSE; if (p) free(p); break; case XDR_DECODE: if(!xdr_nullstring(xdrs, &p)) return FALSE; if (p) { ret = krb5_parse_name(context, p, &pr); if(ret != 0) return FALSE; *objp = pr; free(p); } else *objp = NULL; break; case XDR_FREE: if(*objp != NULL) krb5_free_principal(context, *objp); *objp = NULL; break; } return TRUE; }
166,790
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static InputMethodStatusConnection* GetConnection( void* language_library, LanguageCurrentInputMethodMonitorFunction current_input_method_changed, LanguageRegisterImePropertiesFunction register_ime_properties, LanguageUpdateImePropertyFunction update_ime_property, LanguageConnectionChangeMonitorFunction connection_change_handler) { DCHECK(language_library); DCHECK(current_input_method_changed), DCHECK(register_ime_properties); DCHECK(update_ime_property); InputMethodStatusConnection* object = GetInstance(); if (!object->language_library_) { object->language_library_ = language_library; object->current_input_method_changed_ = current_input_method_changed; object->register_ime_properties_= register_ime_properties; object->update_ime_property_ = update_ime_property; object->connection_change_handler_ = connection_change_handler; object->MaybeRestoreConnections(); } else if (object->language_library_ != language_library) { LOG(ERROR) << "Unknown language_library is passed"; } return object; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
static InputMethodStatusConnection* GetConnection( // TODO(satorux,yusukes): Remove use of singleton here. static IBusControllerImpl* GetInstance() { return Singleton<IBusControllerImpl, LeakySingletonTraits<IBusControllerImpl> >::get(); }
170,534
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void addDataToStreamTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); blobRegistry().addDataToStream(blobRegistryContext->url, blobRegistryContext->streamData); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static void addDataToStreamTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); if (WebBlobRegistry* registry = blobRegistry()) { WebThreadSafeData webThreadSafeData(blobRegistryContext->streamData); registry->addDataToStream(blobRegistryContext->url, webThreadSafeData); } }
170,681
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx); static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx); static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, /* tags 4- 7 */ B_ASN1_OCTET_STRING, 0, 0, B_ASN1_UNKNOWN, /* tags 8-11 */ B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 12-15 */ B_ASN1_UTF8STRING, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 16-19 */ B_ASN1_SEQUENCE, 0, B_ASN1_NUMERICSTRING, B_ASN1_PRINTABLESTRING, /* tags 20-22 */ B_ASN1_T61STRING, B_ASN1_VIDEOTEXSTRING, B_ASN1_IA5STRING, /* tags 23-24 */ B_ASN1_UTCTIME, B_ASN1_GENERALIZEDTIME, /* tags 25-27 */ B_ASN1_GRAPHICSTRING, B_ASN1_ISO64STRING, B_ASN1_GENERALSTRING, /* tags 28-31 */ B_ASN1_UNIVERSALSTRING, B_ASN1_UNKNOWN, B_ASN1_BMPSTRING, B_ASN1_UNKNOWN, }; unsigned long ASN1_tag2bit(int tag) { Commit Message: CWE ID: CWE-400
static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx, int depth); static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx, int depth); static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, /* tags 4- 7 */ B_ASN1_OCTET_STRING, 0, 0, B_ASN1_UNKNOWN, /* tags 8-11 */ B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 12-15 */ B_ASN1_UTF8STRING, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 16-19 */ B_ASN1_SEQUENCE, 0, B_ASN1_NUMERICSTRING, B_ASN1_PRINTABLESTRING, /* tags 20-22 */ B_ASN1_T61STRING, B_ASN1_VIDEOTEXSTRING, B_ASN1_IA5STRING, /* tags 23-24 */ B_ASN1_UTCTIME, B_ASN1_GENERALIZEDTIME, /* tags 25-27 */ B_ASN1_GRAPHICSTRING, B_ASN1_ISO64STRING, B_ASN1_GENERALSTRING, /* tags 28-31 */ B_ASN1_UNIVERSALSTRING, B_ASN1_UNKNOWN, B_ASN1_BMPSTRING, B_ASN1_UNKNOWN, }; unsigned long ASN1_tag2bit(int tag) {
165,326
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const char* SegmentInfo::GetTitleAsUTF8() const { return m_pTitleAsUTF8; } 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
const char* SegmentInfo::GetTitleAsUTF8() const
174,369
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected 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. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltStylePreCompute(xsltStylesheetPtr style, xmlNodePtr inst) { /* * URGENT TODO: Normally inst->psvi Should never be reserved here, * BUT: since if we include the same stylesheet from * multiple imports, then the stylesheet will be parsed * again. We simply must not try to compute the stylesheet again. * TODO: Get to the point where we don't need to query the * namespace- and local-name of the node, but can evaluate this * using cctxt->style->inode->category; */ if ((inst == NULL) || (inst->type != XML_ELEMENT_NODE) || (inst->psvi != NULL)) return; if (IS_XSLT_ELEM(inst)) { xsltStylePreCompPtr cur; if (IS_XSLT_NAME(inst, "apply-templates")) { xsltCheckInstructionElement(style, inst); xsltApplyTemplatesComp(style, inst); } else if (IS_XSLT_NAME(inst, "with-param")) { xsltCheckParentElement(style, inst, BAD_CAST "apply-templates", BAD_CAST "call-template"); xsltWithParamComp(style, inst); } else if (IS_XSLT_NAME(inst, "value-of")) { xsltCheckInstructionElement(style, inst); xsltValueOfComp(style, inst); } else if (IS_XSLT_NAME(inst, "copy")) { xsltCheckInstructionElement(style, inst); xsltCopyComp(style, inst); } else if (IS_XSLT_NAME(inst, "copy-of")) { xsltCheckInstructionElement(style, inst); xsltCopyOfComp(style, inst); } else if (IS_XSLT_NAME(inst, "if")) { xsltCheckInstructionElement(style, inst); xsltIfComp(style, inst); } else if (IS_XSLT_NAME(inst, "when")) { xsltCheckParentElement(style, inst, BAD_CAST "choose", NULL); xsltWhenComp(style, inst); } else if (IS_XSLT_NAME(inst, "choose")) { xsltCheckInstructionElement(style, inst); xsltChooseComp(style, inst); } else if (IS_XSLT_NAME(inst, "for-each")) { xsltCheckInstructionElement(style, inst); xsltForEachComp(style, inst); } else if (IS_XSLT_NAME(inst, "apply-imports")) { xsltCheckInstructionElement(style, inst); xsltApplyImportsComp(style, inst); } else if (IS_XSLT_NAME(inst, "attribute")) { xmlNodePtr parent = inst->parent; if ((parent == NULL) || (parent->ns == NULL) || ((parent->ns != inst->ns) && (!xmlStrEqual(parent->ns->href, inst->ns->href))) || (!xmlStrEqual(parent->name, BAD_CAST "attribute-set"))) { xsltCheckInstructionElement(style, inst); } xsltAttributeComp(style, inst); } else if (IS_XSLT_NAME(inst, "element")) { xsltCheckInstructionElement(style, inst); xsltElementComp(style, inst); } else if (IS_XSLT_NAME(inst, "text")) { xsltCheckInstructionElement(style, inst); xsltTextComp(style, inst); } else if (IS_XSLT_NAME(inst, "sort")) { xsltCheckParentElement(style, inst, BAD_CAST "apply-templates", BAD_CAST "for-each"); xsltSortComp(style, inst); } else if (IS_XSLT_NAME(inst, "comment")) { xsltCheckInstructionElement(style, inst); xsltCommentComp(style, inst); } else if (IS_XSLT_NAME(inst, "number")) { xsltCheckInstructionElement(style, inst); xsltNumberComp(style, inst); } else if (IS_XSLT_NAME(inst, "processing-instruction")) { xsltCheckInstructionElement(style, inst); xsltProcessingInstructionComp(style, inst); } else if (IS_XSLT_NAME(inst, "call-template")) { xsltCheckInstructionElement(style, inst); xsltCallTemplateComp(style, inst); } else if (IS_XSLT_NAME(inst, "param")) { if (xsltCheckTopLevelElement(style, inst, 0) == 0) xsltCheckInstructionElement(style, inst); xsltParamComp(style, inst); } else if (IS_XSLT_NAME(inst, "variable")) { if (xsltCheckTopLevelElement(style, inst, 0) == 0) xsltCheckInstructionElement(style, inst); xsltVariableComp(style, inst); } else if (IS_XSLT_NAME(inst, "otherwise")) { xsltCheckParentElement(style, inst, BAD_CAST "choose", NULL); xsltCheckInstructionElement(style, inst); return; } else if (IS_XSLT_NAME(inst, "template")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "output")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "preserve-space")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "strip-space")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if ((IS_XSLT_NAME(inst, "stylesheet")) || (IS_XSLT_NAME(inst, "transform"))) { xmlNodePtr parent = inst->parent; if ((parent == NULL) || (parent->type != XML_DOCUMENT_NODE)) { xsltTransformError(NULL, style, inst, "element %s only allowed only as root element\n", inst->name); style->errors++; } return; } else if (IS_XSLT_NAME(inst, "key")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "message")) { xsltCheckInstructionElement(style, inst); return; } else if (IS_XSLT_NAME(inst, "attribute-set")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "namespace-alias")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "include")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "import")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "decimal-format")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "fallback")) { xsltCheckInstructionElement(style, inst); return; } else if (IS_XSLT_NAME(inst, "document")) { xsltCheckInstructionElement(style, inst); inst->psvi = (void *) xsltDocumentComp(style, inst, (xsltTransformFunction) xsltDocumentElem); } else { xsltTransformError(NULL, style, inst, "xsltStylePreCompute: unknown xsl:%s\n", inst->name); if (style != NULL) style->warnings++; } cur = (xsltStylePreCompPtr) inst->psvi; /* * A ns-list is build for every XSLT item in the * node-tree. This is needed for XPath expressions. */ if (cur != NULL) { int i = 0; cur->nsList = xmlGetNsList(inst->doc, inst); if (cur->nsList != NULL) { while (cur->nsList[i] != NULL) i++; } cur->nsNr = i; } } else { inst->psvi = (void *) xsltPreComputeExtModuleElement(style, inst); /* * Unknown element, maybe registered at the context * level. Mark it for later recognition. */ if (inst->psvi == NULL) inst->psvi = (void *) xsltExtMarker; } } 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
xsltStylePreCompute(xsltStylesheetPtr style, xmlNodePtr inst) { /* * URGENT TODO: Normally inst->psvi Should never be reserved here, * BUT: since if we include the same stylesheet from * multiple imports, then the stylesheet will be parsed * again. We simply must not try to compute the stylesheet again. * TODO: Get to the point where we don't need to query the * namespace- and local-name of the node, but can evaluate this * using cctxt->style->inode->category; */ if ((inst == NULL) || (inst->type != XML_ELEMENT_NODE) || (inst->psvi != NULL)) return; if (IS_XSLT_ELEM(inst)) { xsltStylePreCompPtr cur; if (IS_XSLT_NAME(inst, "apply-templates")) { xsltCheckInstructionElement(style, inst); xsltApplyTemplatesComp(style, inst); } else if (IS_XSLT_NAME(inst, "with-param")) { xsltCheckParentElement(style, inst, BAD_CAST "apply-templates", BAD_CAST "call-template"); xsltWithParamComp(style, inst); } else if (IS_XSLT_NAME(inst, "value-of")) { xsltCheckInstructionElement(style, inst); xsltValueOfComp(style, inst); } else if (IS_XSLT_NAME(inst, "copy")) { xsltCheckInstructionElement(style, inst); xsltCopyComp(style, inst); } else if (IS_XSLT_NAME(inst, "copy-of")) { xsltCheckInstructionElement(style, inst); xsltCopyOfComp(style, inst); } else if (IS_XSLT_NAME(inst, "if")) { xsltCheckInstructionElement(style, inst); xsltIfComp(style, inst); } else if (IS_XSLT_NAME(inst, "when")) { xsltCheckParentElement(style, inst, BAD_CAST "choose", NULL); xsltWhenComp(style, inst); } else if (IS_XSLT_NAME(inst, "choose")) { xsltCheckInstructionElement(style, inst); xsltChooseComp(style, inst); } else if (IS_XSLT_NAME(inst, "for-each")) { xsltCheckInstructionElement(style, inst); xsltForEachComp(style, inst); } else if (IS_XSLT_NAME(inst, "apply-imports")) { xsltCheckInstructionElement(style, inst); xsltApplyImportsComp(style, inst); } else if (IS_XSLT_NAME(inst, "attribute")) { xmlNodePtr parent = inst->parent; if ((parent == NULL) || (parent->type != XML_ELEMENT_NODE) || (parent->ns == NULL) || ((parent->ns != inst->ns) && (!xmlStrEqual(parent->ns->href, inst->ns->href))) || (!xmlStrEqual(parent->name, BAD_CAST "attribute-set"))) { xsltCheckInstructionElement(style, inst); } xsltAttributeComp(style, inst); } else if (IS_XSLT_NAME(inst, "element")) { xsltCheckInstructionElement(style, inst); xsltElementComp(style, inst); } else if (IS_XSLT_NAME(inst, "text")) { xsltCheckInstructionElement(style, inst); xsltTextComp(style, inst); } else if (IS_XSLT_NAME(inst, "sort")) { xsltCheckParentElement(style, inst, BAD_CAST "apply-templates", BAD_CAST "for-each"); xsltSortComp(style, inst); } else if (IS_XSLT_NAME(inst, "comment")) { xsltCheckInstructionElement(style, inst); xsltCommentComp(style, inst); } else if (IS_XSLT_NAME(inst, "number")) { xsltCheckInstructionElement(style, inst); xsltNumberComp(style, inst); } else if (IS_XSLT_NAME(inst, "processing-instruction")) { xsltCheckInstructionElement(style, inst); xsltProcessingInstructionComp(style, inst); } else if (IS_XSLT_NAME(inst, "call-template")) { xsltCheckInstructionElement(style, inst); xsltCallTemplateComp(style, inst); } else if (IS_XSLT_NAME(inst, "param")) { if (xsltCheckTopLevelElement(style, inst, 0) == 0) xsltCheckInstructionElement(style, inst); xsltParamComp(style, inst); } else if (IS_XSLT_NAME(inst, "variable")) { if (xsltCheckTopLevelElement(style, inst, 0) == 0) xsltCheckInstructionElement(style, inst); xsltVariableComp(style, inst); } else if (IS_XSLT_NAME(inst, "otherwise")) { xsltCheckParentElement(style, inst, BAD_CAST "choose", NULL); xsltCheckInstructionElement(style, inst); return; } else if (IS_XSLT_NAME(inst, "template")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "output")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "preserve-space")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "strip-space")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if ((IS_XSLT_NAME(inst, "stylesheet")) || (IS_XSLT_NAME(inst, "transform"))) { xmlNodePtr parent = inst->parent; if ((parent == NULL) || (parent->type != XML_DOCUMENT_NODE)) { xsltTransformError(NULL, style, inst, "element %s only allowed only as root element\n", inst->name); style->errors++; } return; } else if (IS_XSLT_NAME(inst, "key")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "message")) { xsltCheckInstructionElement(style, inst); return; } else if (IS_XSLT_NAME(inst, "attribute-set")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "namespace-alias")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "include")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "import")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "decimal-format")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "fallback")) { xsltCheckInstructionElement(style, inst); return; } else if (IS_XSLT_NAME(inst, "document")) { xsltCheckInstructionElement(style, inst); inst->psvi = (void *) xsltDocumentComp(style, inst, (xsltTransformFunction) xsltDocumentElem); } else { xsltTransformError(NULL, style, inst, "xsltStylePreCompute: unknown xsl:%s\n", inst->name); if (style != NULL) style->warnings++; } cur = (xsltStylePreCompPtr) inst->psvi; /* * A ns-list is build for every XSLT item in the * node-tree. This is needed for XPath expressions. */ if (cur != NULL) { int i = 0; cur->nsList = xmlGetNsList(inst->doc, inst); if (cur->nsList != NULL) { while (cur->nsList[i] != NULL) i++; } cur->nsNr = i; } } else { inst->psvi = (void *) xsltPreComputeExtModuleElement(style, inst); /* * Unknown element, maybe registered at the context * level. Mark it for later recognition. */ if (inst->psvi == NULL) inst->psvi = (void *) xsltExtMarker; } }
173,318
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Chapters::~Chapters() { while (m_editions_count > 0) { Edition& e = m_editions[--m_editions_count]; e.Clear(); } } 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
Chapters::~Chapters()
174,457
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: arp_print(netdissect_options *ndo, const u_char *bp, u_int length, u_int caplen) { const struct arp_pkthdr *ap; u_short pro, hrd, op, linkaddr; ap = (const struct arp_pkthdr *)bp; ND_TCHECK(*ap); hrd = HRD(ap); pro = PRO(ap); op = OP(ap); /* if its ATM then call the ATM ARP printer for Frame-relay ARP most of the fields are similar to Ethernet so overload the Ethernet Printer and set the linkaddr type for linkaddr_string(ndo, ) accordingly */ switch(hrd) { case ARPHRD_ATM2225: atmarp_print(ndo, bp, length, caplen); return; case ARPHRD_FRELAY: linkaddr = LINKADDR_FRELAY; break; default: linkaddr = LINKADDR_ETHER; break; } if (!ND_TTEST2(*ar_tpa(ap), PROTO_LEN(ap))) { ND_PRINT((ndo, "%s", tstr)); ND_DEFAULTPRINT((const u_char *)ap, length); return; } if (!ndo->ndo_eflag) { ND_PRINT((ndo, "ARP, ")); } /* print hardware type/len and proto type/len */ if ((pro != ETHERTYPE_IP && pro != ETHERTYPE_TRAIL) || PROTO_LEN(ap) != 4 || HRD_LEN(ap) == 0 || ndo->ndo_vflag) { ND_PRINT((ndo, "%s (len %u), %s (len %u)", tok2str(arphrd_values, "Unknown Hardware (%u)", hrd), HRD_LEN(ap), tok2str(ethertype_values, "Unknown Protocol (0x%04x)", pro), PROTO_LEN(ap))); /* don't know know about the address formats */ if (!ndo->ndo_vflag) { goto out; } } /* print operation */ ND_PRINT((ndo, "%s%s ", ndo->ndo_vflag ? ", " : "", tok2str(arpop_values, "Unknown (%u)", op))); switch (op) { case ARPOP_REQUEST: ND_PRINT((ndo, "who-has %s", ipaddr_string(ndo, TPA(ap)))); if (isnonzero((const u_char *)THA(ap), HRD_LEN(ap))) ND_PRINT((ndo, " (%s)", linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)))); ND_PRINT((ndo, " tell %s", ipaddr_string(ndo, SPA(ap)))); break; case ARPOP_REPLY: ND_PRINT((ndo, "%s is-at %s", ipaddr_string(ndo, SPA(ap)), linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap)))); break; case ARPOP_REVREQUEST: ND_PRINT((ndo, "who-is %s tell %s", linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)), linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap)))); break; case ARPOP_REVREPLY: ND_PRINT((ndo, "%s at %s", linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)), ipaddr_string(ndo, TPA(ap)))); break; case ARPOP_INVREQUEST: ND_PRINT((ndo, "who-is %s tell %s", linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)), linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap)))); break; case ARPOP_INVREPLY: ND_PRINT((ndo,"%s at %s", linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap)), ipaddr_string(ndo, SPA(ap)))); break; default: ND_DEFAULTPRINT((const u_char *)ap, caplen); return; } out: ND_PRINT((ndo, ", length %u", length)); return; trunc: ND_PRINT((ndo, "%s", tstr)); } Commit Message: CVE-2017-13013/ARP: Fix printing of ARP protocol addresses. If the protocol type isn't ETHERTYPE_IP or ETHERTYPE_TRAIL, or if the protocol address length isn't 4, don't print the address as an IPv4 address. 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), modified so the capture file won't be rejected as an invalid capture. Update another test file's tcpdump output to reflect this change. CWE ID: CWE-125
arp_print(netdissect_options *ndo, const u_char *bp, u_int length, u_int caplen) { const struct arp_pkthdr *ap; u_short pro, hrd, op, linkaddr; ap = (const struct arp_pkthdr *)bp; ND_TCHECK(*ap); hrd = HRD(ap); pro = PRO(ap); op = OP(ap); /* if its ATM then call the ATM ARP printer for Frame-relay ARP most of the fields are similar to Ethernet so overload the Ethernet Printer and set the linkaddr type for linkaddr_string(ndo, ) accordingly */ switch(hrd) { case ARPHRD_ATM2225: atmarp_print(ndo, bp, length, caplen); return; case ARPHRD_FRELAY: linkaddr = LINKADDR_FRELAY; break; default: linkaddr = LINKADDR_ETHER; break; } if (!ND_TTEST2(*TPA(ap), PROTO_LEN(ap))) { ND_PRINT((ndo, "%s", tstr)); ND_DEFAULTPRINT((const u_char *)ap, length); return; } if (!ndo->ndo_eflag) { ND_PRINT((ndo, "ARP, ")); } /* print hardware type/len and proto type/len */ if ((pro != ETHERTYPE_IP && pro != ETHERTYPE_TRAIL) || PROTO_LEN(ap) != 4 || HRD_LEN(ap) == 0 || ndo->ndo_vflag) { ND_PRINT((ndo, "%s (len %u), %s (len %u)", tok2str(arphrd_values, "Unknown Hardware (%u)", hrd), HRD_LEN(ap), tok2str(ethertype_values, "Unknown Protocol (0x%04x)", pro), PROTO_LEN(ap))); /* don't know know about the address formats */ if (!ndo->ndo_vflag) { goto out; } } /* print operation */ ND_PRINT((ndo, "%s%s ", ndo->ndo_vflag ? ", " : "", tok2str(arpop_values, "Unknown (%u)", op))); switch (op) { case ARPOP_REQUEST: ND_PRINT((ndo, "who-has ")); tpaddr_print_ip(ndo, ap, pro); if (isnonzero((const u_char *)THA(ap), HRD_LEN(ap))) ND_PRINT((ndo, " (%s)", linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)))); ND_PRINT((ndo, " tell ")); spaddr_print_ip(ndo, ap, pro); break; case ARPOP_REPLY: spaddr_print_ip(ndo, ap, pro); ND_PRINT((ndo, " is-at %s", linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap)))); break; case ARPOP_REVREQUEST: ND_PRINT((ndo, "who-is %s tell %s", linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)), linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap)))); break; case ARPOP_REVREPLY: ND_PRINT((ndo, "%s at ", linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)))); tpaddr_print_ip(ndo, ap, pro); break; case ARPOP_INVREQUEST: ND_PRINT((ndo, "who-is %s tell %s", linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)), linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap)))); break; case ARPOP_INVREPLY: ND_PRINT((ndo,"%s at ", linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap)))); spaddr_print_ip(ndo, ap, pro); break; default: ND_DEFAULTPRINT((const u_char *)ap, caplen); return; } out: ND_PRINT((ndo, ", length %u", length)); return; trunc: ND_PRINT((ndo, "%s", tstr)); }
167,880
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: jas_image_t *bmp_decode(jas_stream_t *in, char *optstr) { jas_image_t *image; bmp_hdr_t hdr; bmp_info_t *info; uint_fast16_t cmptno; jas_image_cmptparm_t cmptparms[3]; jas_image_cmptparm_t *cmptparm; uint_fast16_t numcmpts; long n; if (optstr) { jas_eprintf("warning: ignoring BMP decoder options\n"); } jas_eprintf( "THE BMP FORMAT IS NOT FULLY SUPPORTED!\n" "THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n" "IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n" "TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n" ); /* Read the bitmap header. */ if (bmp_gethdr(in, &hdr)) { jas_eprintf("cannot get header\n"); return 0; } /* Read the bitmap information. */ if (!(info = bmp_getinfo(in))) { jas_eprintf("cannot get info\n"); return 0; } /* Ensure that we support this type of BMP file. */ if (!bmp_issupported(&hdr, info)) { jas_eprintf("error: unsupported BMP encoding\n"); bmp_info_destroy(info); return 0; } /* Skip over any useless data between the end of the palette and start of the bitmap data. */ if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) { jas_eprintf("error: possibly bad bitmap offset?\n"); return 0; } if (n > 0) { jas_eprintf("skipping unknown data in BMP file\n"); if (bmp_gobble(in, n)) { bmp_info_destroy(info); return 0; } } /* Get the number of components. */ numcmpts = bmp_numcmpts(info); for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, ++cmptparm) { cmptparm->tlx = 0; cmptparm->tly = 0; cmptparm->hstep = 1; cmptparm->vstep = 1; cmptparm->width = info->width; cmptparm->height = info->height; cmptparm->prec = 8; cmptparm->sgnd = false; } /* Create image object. */ if (!(image = jas_image_create(numcmpts, cmptparms, JAS_CLRSPC_UNKNOWN))) { bmp_info_destroy(info); return 0; } if (numcmpts == 3) { jas_image_setclrspc(image, JAS_CLRSPC_SRGB); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); } else { jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } /* Read the bitmap data. */ if (bmp_getdata(in, info, image)) { bmp_info_destroy(info); jas_image_destroy(image); return 0; } bmp_info_destroy(info); return image; } Commit Message: Fixed a sanitizer failure in the BMP codec. Also, added a --debug-level command line option to the imginfo command for debugging purposes. CWE ID: CWE-476
jas_image_t *bmp_decode(jas_stream_t *in, char *optstr) { jas_image_t *image; bmp_hdr_t hdr; bmp_info_t *info; uint_fast16_t cmptno; jas_image_cmptparm_t cmptparms[3]; jas_image_cmptparm_t *cmptparm; uint_fast16_t numcmpts; long n; if (optstr) { jas_eprintf("warning: ignoring BMP decoder options\n"); } jas_eprintf( "THE BMP FORMAT IS NOT FULLY SUPPORTED!\n" "THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n" "IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n" "TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n" ); /* Read the bitmap header. */ if (bmp_gethdr(in, &hdr)) { jas_eprintf("cannot get header\n"); return 0; } JAS_DBGLOG(1, ( "BMP header: magic 0x%x; siz %d; res1 %d; res2 %d; off %d\n", hdr.magic, hdr.siz, hdr.reserved1, hdr.reserved2, hdr.off )); /* Read the bitmap information. */ if (!(info = bmp_getinfo(in))) { jas_eprintf("cannot get info\n"); return 0; } JAS_DBGLOG(1, ("BMP information: len %d; width %d; height %d; numplanes %d; " "depth %d; enctype %d; siz %d; hres %d; vres %d; numcolors %d; " "mincolors %d\n", info->len, info->width, info->height, info->numplanes, info->depth, info->enctype, info->siz, info->hres, info->vres, info->numcolors, info->mincolors)); /* Ensure that we support this type of BMP file. */ if (!bmp_issupported(&hdr, info)) { jas_eprintf("error: unsupported BMP encoding\n"); bmp_info_destroy(info); return 0; } /* Skip over any useless data between the end of the palette and start of the bitmap data. */ if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) { jas_eprintf("error: possibly bad bitmap offset?\n"); return 0; } if (n > 0) { jas_eprintf("skipping unknown data in BMP file\n"); if (bmp_gobble(in, n)) { bmp_info_destroy(info); return 0; } } /* Get the number of components. */ numcmpts = bmp_numcmpts(info); for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, ++cmptparm) { cmptparm->tlx = 0; cmptparm->tly = 0; cmptparm->hstep = 1; cmptparm->vstep = 1; cmptparm->width = info->width; cmptparm->height = info->height; cmptparm->prec = 8; cmptparm->sgnd = false; } /* Create image object. */ if (!(image = jas_image_create(numcmpts, cmptparms, JAS_CLRSPC_UNKNOWN))) { bmp_info_destroy(info); return 0; } if (numcmpts == 3) { jas_image_setclrspc(image, JAS_CLRSPC_SRGB); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); } else { jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } /* Read the bitmap data. */ if (bmp_getdata(in, info, image)) { bmp_info_destroy(info); jas_image_destroy(image); return 0; } bmp_info_destroy(info); return image; }
168,762
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct sock *dccp_v6_request_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct inet_sock *newinet; struct dccp6_sock *newdp6; struct sock *newsk; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = dccp_v4_request_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (newsk == NULL) return NULL; newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped; newsk->sk_backlog_rcv = dccp_v4_do_rcv; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, dccp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { struct flowi6 fl6; dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP); if (!dst) goto out; } newsk = dccp_create_openreq_child(sk, req, skb); if (newsk == NULL) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, dccp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ __ip6_dst_store(newsk, dst, NULL, NULL); newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM | NETIF_F_TSO); newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * Clone native IPv6 options from listening socket (if any) * * Yes, keeping reference count would be much more clever, but we make * one more one thing there: reattach optmem to newsk. */ if (np->opt != NULL) newnp->opt = ipv6_dup_options(newsk, np->opt); inet_csk(newsk)->icsk_ext_hdr_len = 0; if (newnp->opt != NULL) inet_csk(newsk)->icsk_ext_hdr_len = (newnp->opt->opt_nflen + newnp->opt->opt_flen); dccp_sync_mss(newsk, dst_mtu(dst)); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); dccp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); /* Clone pktoptions received with SYN, if we own the req */ if (*own_req && ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } return newsk; out_overflow: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
static struct sock *dccp_v6_request_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt; struct inet_sock *newinet; struct dccp6_sock *newdp6; struct sock *newsk; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = dccp_v4_request_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (newsk == NULL) return NULL; newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped; newsk->sk_backlog_rcv = dccp_v4_do_rcv; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, dccp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { struct flowi6 fl6; dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP); if (!dst) goto out; } newsk = dccp_create_openreq_child(sk, req, skb); if (newsk == NULL) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, dccp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ __ip6_dst_store(newsk, dst, NULL, NULL); newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM | NETIF_F_TSO); newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * Clone native IPv6 options from listening socket (if any) * * Yes, keeping reference count would be much more clever, but we make * one more one thing there: reattach optmem to newsk. */ opt = rcu_dereference(np->opt); if (opt) { opt = ipv6_dup_options(newsk, opt); RCU_INIT_POINTER(newnp->opt, opt); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (opt) inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen + opt->opt_flen; dccp_sync_mss(newsk, dst_mtu(dst)); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); dccp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); /* Clone pktoptions received with SYN, if we own the req */ if (*own_req && ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } return newsk; out_overflow: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; }
167,325