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: OMX_ERRORTYPE SoftVorbis::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.vorbis",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioVorbis:
{
const OMX_AUDIO_PARAM_VORBISTYPE *vorbisParams =
(const OMX_AUDIO_PARAM_VORBISTYPE *)params;
if (vorbisParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::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 SoftVorbis::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.vorbis",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioVorbis:
{
const OMX_AUDIO_PARAM_VORBISTYPE *vorbisParams =
(const OMX_AUDIO_PARAM_VORBISTYPE *)params;
if (!isValidOMXParam(vorbisParams)) {
return OMX_ErrorBadParameter;
}
if (vorbisParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,221 |
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 js_RegExp_prototype_exec(js_State *J, js_Regexp *re, const char *text)
{
int i;
int opts;
Resub m;
opts = 0;
if (re->flags & JS_REGEXP_G) {
if (re->last > strlen(text)) {
re->last = 0;
js_pushnull(J);
return;
}
if (re->last > 0) {
text += re->last;
opts |= REG_NOTBOL;
}
}
if (!js_regexec(re->prog, text, &m, opts)) {
js_newarray(J);
js_pushstring(J, text);
js_setproperty(J, -2, "input");
js_pushnumber(J, js_utfptrtoidx(text, m.sub[0].sp));
js_setproperty(J, -2, "index");
for (i = 0; i < m.nsub; ++i) {
js_pushlstring(J, m.sub[i].sp, m.sub[i].ep - m.sub[i].sp);
js_setindex(J, -2, i);
}
if (re->flags & JS_REGEXP_G)
re->last = re->last + (m.sub[0].ep - text);
return;
}
if (re->flags & JS_REGEXP_G)
re->last = 0;
js_pushnull(J);
}
Commit Message: Bug 700937: Limit recursion in regexp matcher.
Also handle negative return code as an error in the JS bindings.
CWE ID: CWE-400 | void js_RegExp_prototype_exec(js_State *J, js_Regexp *re, const char *text)
{
int result;
int i;
int opts;
Resub m;
opts = 0;
if (re->flags & JS_REGEXP_G) {
if (re->last > strlen(text)) {
re->last = 0;
js_pushnull(J);
return;
}
if (re->last > 0) {
text += re->last;
opts |= REG_NOTBOL;
}
}
result = js_regexec(re->prog, text, &m, opts);
if (result < 0)
js_error(J, "regexec failed");
if (result == 0) {
js_newarray(J);
js_pushstring(J, text);
js_setproperty(J, -2, "input");
js_pushnumber(J, js_utfptrtoidx(text, m.sub[0].sp));
js_setproperty(J, -2, "index");
for (i = 0; i < m.nsub; ++i) {
js_pushlstring(J, m.sub[i].sp, m.sub[i].ep - m.sub[i].sp);
js_setindex(J, -2, i);
}
if (re->flags & JS_REGEXP_G)
re->last = re->last + (m.sub[0].ep - text);
return;
}
if (re->flags & JS_REGEXP_G)
re->last = 0;
js_pushnull(J);
}
| 169,697 |
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: RenderFrameImpl::RenderFrameImpl(const CreateParams& params)
: frame_(NULL),
is_subframe_(false),
is_local_root_(false),
render_view_(params.render_view->AsWeakPtr()),
routing_id_(params.routing_id),
is_swapped_out_(false),
render_frame_proxy_(NULL),
is_detaching_(false),
proxy_routing_id_(MSG_ROUTING_NONE),
#if defined(ENABLE_PLUGINS)
plugin_power_saver_helper_(NULL),
#endif
cookie_jar_(this),
selection_text_offset_(0),
selection_range_(gfx::Range::InvalidRange()),
handling_select_range_(false),
notification_permission_dispatcher_(NULL),
web_user_media_client_(NULL),
media_permission_dispatcher_(NULL),
midi_dispatcher_(NULL),
#if defined(OS_ANDROID)
media_player_manager_(NULL),
#endif
#if defined(ENABLE_BROWSER_CDMS)
cdm_manager_(NULL),
#endif
#if defined(VIDEO_HOLE)
contains_media_player_(false),
#endif
has_played_media_(false),
devtools_agent_(nullptr),
geolocation_dispatcher_(NULL),
push_messaging_dispatcher_(NULL),
presentation_dispatcher_(NULL),
screen_orientation_dispatcher_(NULL),
manifest_manager_(NULL),
accessibility_mode_(AccessibilityModeOff),
renderer_accessibility_(NULL),
weak_factory_(this) {
std::pair<RoutingIDFrameMap::iterator, bool> result =
g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this));
CHECK(result.second) << "Inserting a duplicate item.";
RenderThread::Get()->AddRoute(routing_id_, this);
render_view_->RegisterRenderFrame(this);
#if defined(OS_ANDROID)
new GinJavaBridgeDispatcher(this);
#endif
#if defined(ENABLE_PLUGINS)
plugin_power_saver_helper_ = new PluginPowerSaverHelper(this);
#endif
manifest_manager_ = new ManifestManager(this);
}
Commit Message: Connect WebUSB client interface to the devices app
This provides a basic WebUSB client interface in
content/renderer. Most of the interface is unimplemented,
but this CL hooks up navigator.usb.getDevices() to the
browser's Mojo devices app to enumerate available USB
devices.
BUG=492204
Review URL: https://codereview.chromium.org/1293253002
Cr-Commit-Position: refs/heads/master@{#344881}
CWE ID: CWE-399 | RenderFrameImpl::RenderFrameImpl(const CreateParams& params)
: frame_(NULL),
is_subframe_(false),
is_local_root_(false),
render_view_(params.render_view->AsWeakPtr()),
routing_id_(params.routing_id),
is_swapped_out_(false),
render_frame_proxy_(NULL),
is_detaching_(false),
proxy_routing_id_(MSG_ROUTING_NONE),
#if defined(ENABLE_PLUGINS)
plugin_power_saver_helper_(NULL),
#endif
cookie_jar_(this),
selection_text_offset_(0),
selection_range_(gfx::Range::InvalidRange()),
handling_select_range_(false),
notification_permission_dispatcher_(NULL),
web_user_media_client_(NULL),
media_permission_dispatcher_(NULL),
midi_dispatcher_(NULL),
#if defined(OS_ANDROID)
media_player_manager_(NULL),
#endif
#if defined(ENABLE_BROWSER_CDMS)
cdm_manager_(NULL),
#endif
#if defined(VIDEO_HOLE)
contains_media_player_(false),
#endif
has_played_media_(false),
devtools_agent_(nullptr),
geolocation_dispatcher_(NULL),
push_messaging_dispatcher_(NULL),
presentation_dispatcher_(NULL),
screen_orientation_dispatcher_(NULL),
manifest_manager_(NULL),
accessibility_mode_(AccessibilityModeOff),
renderer_accessibility_(NULL),
weak_factory_(this) {
std::pair<RoutingIDFrameMap::iterator, bool> result =
g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this));
CHECK(result.second) << "Inserting a duplicate item.";
RenderThread::Get()->AddRoute(routing_id_, this);
render_view_->RegisterRenderFrame(this);
#if defined(OS_ANDROID)
new GinJavaBridgeDispatcher(this);
#endif
#if defined(ENABLE_PLUGINS)
plugin_power_saver_helper_ = new PluginPowerSaverHelper(this);
#endif
manifest_manager_ = new ManifestManager(this);
GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&mojo_shell_));
}
| 171,697 |
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 webkit_web_view_update_settings(WebKitWebView* webView)
{
WebKitWebViewPrivate* priv = webView->priv;
WebKitWebSettings* webSettings = priv->webSettings.get();
Settings* settings = core(webView)->settings();
gchar* defaultEncoding, *cursiveFontFamily, *defaultFontFamily, *fantasyFontFamily, *monospaceFontFamily, *sansSerifFontFamily, *serifFontFamily, *userStylesheetUri, *defaultSpellCheckingLanguages;
gboolean autoLoadImages, autoShrinkImages, printBackgrounds,
enableScripts, enablePlugins, enableDeveloperExtras, resizableTextAreas,
enablePrivateBrowsing, enableCaretBrowsing, enableHTML5Database, enableHTML5LocalStorage,
enableXSSAuditor, enableSpatialNavigation, enableFrameFlattening, javascriptCanOpenWindows,
javaScriptCanAccessClipboard, enableOfflineWebAppCache,
enableUniversalAccessFromFileURI, enableFileAccessFromFileURI,
enableDOMPaste, tabKeyCyclesThroughElements, enableWebGL,
enableSiteSpecificQuirks, usePageCache, enableJavaApplet,
enableHyperlinkAuditing, enableFullscreen, enableDNSPrefetching;
WebKitEditingBehavior editingBehavior;
g_object_get(webSettings,
"default-encoding", &defaultEncoding,
"cursive-font-family", &cursiveFontFamily,
"default-font-family", &defaultFontFamily,
"fantasy-font-family", &fantasyFontFamily,
"monospace-font-family", &monospaceFontFamily,
"sans-serif-font-family", &sansSerifFontFamily,
"serif-font-family", &serifFontFamily,
"auto-load-images", &autoLoadImages,
"auto-shrink-images", &autoShrinkImages,
"print-backgrounds", &printBackgrounds,
"enable-scripts", &enableScripts,
"enable-plugins", &enablePlugins,
"resizable-text-areas", &resizableTextAreas,
"user-stylesheet-uri", &userStylesheetUri,
"enable-developer-extras", &enableDeveloperExtras,
"enable-private-browsing", &enablePrivateBrowsing,
"enable-caret-browsing", &enableCaretBrowsing,
"enable-html5-database", &enableHTML5Database,
"enable-html5-local-storage", &enableHTML5LocalStorage,
"enable-xss-auditor", &enableXSSAuditor,
"enable-spatial-navigation", &enableSpatialNavigation,
"enable-frame-flattening", &enableFrameFlattening,
"javascript-can-open-windows-automatically", &javascriptCanOpenWindows,
"javascript-can-access-clipboard", &javaScriptCanAccessClipboard,
"enable-offline-web-application-cache", &enableOfflineWebAppCache,
"editing-behavior", &editingBehavior,
"enable-universal-access-from-file-uris", &enableUniversalAccessFromFileURI,
"enable-file-access-from-file-uris", &enableFileAccessFromFileURI,
"enable-dom-paste", &enableDOMPaste,
"tab-key-cycles-through-elements", &tabKeyCyclesThroughElements,
"enable-site-specific-quirks", &enableSiteSpecificQuirks,
"enable-page-cache", &usePageCache,
"enable-java-applet", &enableJavaApplet,
"enable-hyperlink-auditing", &enableHyperlinkAuditing,
"spell-checking-languages", &defaultSpellCheckingLanguages,
"enable-fullscreen", &enableFullscreen,
"enable-dns-prefetching", &enableDNSPrefetching,
"enable-webgl", &enableWebGL,
NULL);
settings->setDefaultTextEncodingName(defaultEncoding);
settings->setCursiveFontFamily(cursiveFontFamily);
settings->setStandardFontFamily(defaultFontFamily);
settings->setFantasyFontFamily(fantasyFontFamily);
settings->setFixedFontFamily(monospaceFontFamily);
settings->setSansSerifFontFamily(sansSerifFontFamily);
settings->setSerifFontFamily(serifFontFamily);
settings->setLoadsImagesAutomatically(autoLoadImages);
settings->setShrinksStandaloneImagesToFit(autoShrinkImages);
settings->setShouldPrintBackgrounds(printBackgrounds);
settings->setJavaScriptEnabled(enableScripts);
settings->setPluginsEnabled(enablePlugins);
settings->setTextAreasAreResizable(resizableTextAreas);
settings->setUserStyleSheetLocation(KURL(KURL(), userStylesheetUri));
settings->setDeveloperExtrasEnabled(enableDeveloperExtras);
settings->setPrivateBrowsingEnabled(enablePrivateBrowsing);
settings->setCaretBrowsingEnabled(enableCaretBrowsing);
#if ENABLE(DATABASE)
AbstractDatabase::setIsAvailable(enableHTML5Database);
#endif
settings->setLocalStorageEnabled(enableHTML5LocalStorage);
settings->setXSSAuditorEnabled(enableXSSAuditor);
settings->setSpatialNavigationEnabled(enableSpatialNavigation);
settings->setFrameFlatteningEnabled(enableFrameFlattening);
settings->setJavaScriptCanOpenWindowsAutomatically(javascriptCanOpenWindows);
settings->setJavaScriptCanAccessClipboard(javaScriptCanAccessClipboard);
settings->setOfflineWebApplicationCacheEnabled(enableOfflineWebAppCache);
settings->setEditingBehaviorType(static_cast<WebCore::EditingBehaviorType>(editingBehavior));
settings->setAllowUniversalAccessFromFileURLs(enableUniversalAccessFromFileURI);
settings->setAllowFileAccessFromFileURLs(enableFileAccessFromFileURI);
settings->setDOMPasteAllowed(enableDOMPaste);
settings->setNeedsSiteSpecificQuirks(enableSiteSpecificQuirks);
settings->setUsesPageCache(usePageCache);
settings->setJavaEnabled(enableJavaApplet);
settings->setHyperlinkAuditingEnabled(enableHyperlinkAuditing);
settings->setDNSPrefetchingEnabled(enableDNSPrefetching);
#if ENABLE(FULLSCREEN_API)
settings->setFullScreenEnabled(enableFullscreen);
#endif
#if ENABLE(SPELLCHECK)
WebKit::EditorClient* client = static_cast<WebKit::EditorClient*>(core(webView)->editorClient());
static_cast<WebKit::TextCheckerClientEnchant*>(client->textChecker())->updateSpellCheckingLanguage(defaultSpellCheckingLanguages);
#endif
#if ENABLE(WEBGL)
settings->setWebGLEnabled(enableWebGL);
#endif
Page* page = core(webView);
if (page)
page->setTabKeyCyclesThroughElements(tabKeyCyclesThroughElements);
g_free(defaultEncoding);
g_free(cursiveFontFamily);
g_free(defaultFontFamily);
g_free(fantasyFontFamily);
g_free(monospaceFontFamily);
g_free(sansSerifFontFamily);
g_free(serifFontFamily);
g_free(userStylesheetUri);
webkit_web_view_screen_changed(GTK_WIDGET(webView), NULL);
}
Commit Message: 2011-06-02 Joone Hur <[email protected]>
Reviewed by Martin Robinson.
[GTK] Only load dictionaries if spell check is enabled
https://bugs.webkit.org/show_bug.cgi?id=32879
We don't need to call enchant if enable-spell-checking is false.
* webkit/webkitwebview.cpp:
(webkit_web_view_update_settings): Skip loading dictionaries when enable-spell-checking is false.
(webkit_web_view_settings_notify): Ditto.
git-svn-id: svn://svn.chromium.org/blink/trunk@87925 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | static void webkit_web_view_update_settings(WebKitWebView* webView)
{
WebKitWebViewPrivate* priv = webView->priv;
WebKitWebSettings* webSettings = priv->webSettings.get();
Settings* settings = core(webView)->settings();
gchar* defaultEncoding, *cursiveFontFamily, *defaultFontFamily, *fantasyFontFamily, *monospaceFontFamily, *sansSerifFontFamily, *serifFontFamily, *userStylesheetUri, *defaultSpellCheckingLanguages;
gboolean autoLoadImages, autoShrinkImages, printBackgrounds,
enableScripts, enablePlugins, enableDeveloperExtras, resizableTextAreas,
enablePrivateBrowsing, enableCaretBrowsing, enableHTML5Database, enableHTML5LocalStorage,
enableXSSAuditor, enableSpatialNavigation, enableFrameFlattening, javascriptCanOpenWindows,
javaScriptCanAccessClipboard, enableOfflineWebAppCache,
enableUniversalAccessFromFileURI, enableFileAccessFromFileURI,
enableDOMPaste, tabKeyCyclesThroughElements, enableWebGL,
enableSiteSpecificQuirks, usePageCache, enableJavaApplet,
enableHyperlinkAuditing, enableFullscreen, enableDNSPrefetching,
enableSpellChecking;
WebKitEditingBehavior editingBehavior;
g_object_get(webSettings,
"default-encoding", &defaultEncoding,
"cursive-font-family", &cursiveFontFamily,
"default-font-family", &defaultFontFamily,
"fantasy-font-family", &fantasyFontFamily,
"monospace-font-family", &monospaceFontFamily,
"sans-serif-font-family", &sansSerifFontFamily,
"serif-font-family", &serifFontFamily,
"auto-load-images", &autoLoadImages,
"auto-shrink-images", &autoShrinkImages,
"print-backgrounds", &printBackgrounds,
"enable-scripts", &enableScripts,
"enable-plugins", &enablePlugins,
"resizable-text-areas", &resizableTextAreas,
"user-stylesheet-uri", &userStylesheetUri,
"enable-developer-extras", &enableDeveloperExtras,
"enable-private-browsing", &enablePrivateBrowsing,
"enable-caret-browsing", &enableCaretBrowsing,
"enable-html5-database", &enableHTML5Database,
"enable-html5-local-storage", &enableHTML5LocalStorage,
"enable-xss-auditor", &enableXSSAuditor,
"enable-spatial-navigation", &enableSpatialNavigation,
"enable-frame-flattening", &enableFrameFlattening,
"javascript-can-open-windows-automatically", &javascriptCanOpenWindows,
"javascript-can-access-clipboard", &javaScriptCanAccessClipboard,
"enable-offline-web-application-cache", &enableOfflineWebAppCache,
"editing-behavior", &editingBehavior,
"enable-universal-access-from-file-uris", &enableUniversalAccessFromFileURI,
"enable-file-access-from-file-uris", &enableFileAccessFromFileURI,
"enable-dom-paste", &enableDOMPaste,
"tab-key-cycles-through-elements", &tabKeyCyclesThroughElements,
"enable-site-specific-quirks", &enableSiteSpecificQuirks,
"enable-page-cache", &usePageCache,
"enable-java-applet", &enableJavaApplet,
"enable-hyperlink-auditing", &enableHyperlinkAuditing,
"enable-spell-checking", &enableSpellChecking,
"spell-checking-languages", &defaultSpellCheckingLanguages,
"enable-fullscreen", &enableFullscreen,
"enable-dns-prefetching", &enableDNSPrefetching,
"enable-webgl", &enableWebGL,
NULL);
settings->setDefaultTextEncodingName(defaultEncoding);
settings->setCursiveFontFamily(cursiveFontFamily);
settings->setStandardFontFamily(defaultFontFamily);
settings->setFantasyFontFamily(fantasyFontFamily);
settings->setFixedFontFamily(monospaceFontFamily);
settings->setSansSerifFontFamily(sansSerifFontFamily);
settings->setSerifFontFamily(serifFontFamily);
settings->setLoadsImagesAutomatically(autoLoadImages);
settings->setShrinksStandaloneImagesToFit(autoShrinkImages);
settings->setShouldPrintBackgrounds(printBackgrounds);
settings->setJavaScriptEnabled(enableScripts);
settings->setPluginsEnabled(enablePlugins);
settings->setTextAreasAreResizable(resizableTextAreas);
settings->setUserStyleSheetLocation(KURL(KURL(), userStylesheetUri));
settings->setDeveloperExtrasEnabled(enableDeveloperExtras);
settings->setPrivateBrowsingEnabled(enablePrivateBrowsing);
settings->setCaretBrowsingEnabled(enableCaretBrowsing);
#if ENABLE(DATABASE)
AbstractDatabase::setIsAvailable(enableHTML5Database);
#endif
settings->setLocalStorageEnabled(enableHTML5LocalStorage);
settings->setXSSAuditorEnabled(enableXSSAuditor);
settings->setSpatialNavigationEnabled(enableSpatialNavigation);
settings->setFrameFlatteningEnabled(enableFrameFlattening);
settings->setJavaScriptCanOpenWindowsAutomatically(javascriptCanOpenWindows);
settings->setJavaScriptCanAccessClipboard(javaScriptCanAccessClipboard);
settings->setOfflineWebApplicationCacheEnabled(enableOfflineWebAppCache);
settings->setEditingBehaviorType(static_cast<WebCore::EditingBehaviorType>(editingBehavior));
settings->setAllowUniversalAccessFromFileURLs(enableUniversalAccessFromFileURI);
settings->setAllowFileAccessFromFileURLs(enableFileAccessFromFileURI);
settings->setDOMPasteAllowed(enableDOMPaste);
settings->setNeedsSiteSpecificQuirks(enableSiteSpecificQuirks);
settings->setUsesPageCache(usePageCache);
settings->setJavaEnabled(enableJavaApplet);
settings->setHyperlinkAuditingEnabled(enableHyperlinkAuditing);
settings->setDNSPrefetchingEnabled(enableDNSPrefetching);
#if ENABLE(FULLSCREEN_API)
settings->setFullScreenEnabled(enableFullscreen);
#endif
#if ENABLE(SPELLCHECK)
if (enableSpellChecking) {
WebKit::EditorClient* client = static_cast<WebKit::EditorClient*>(core(webView)->editorClient());
static_cast<WebKit::TextCheckerClientEnchant*>(client->textChecker())->updateSpellCheckingLanguage(defaultSpellCheckingLanguages);
}
#endif
#if ENABLE(WEBGL)
settings->setWebGLEnabled(enableWebGL);
#endif
Page* page = core(webView);
if (page)
page->setTabKeyCyclesThroughElements(tabKeyCyclesThroughElements);
g_free(defaultEncoding);
g_free(cursiveFontFamily);
g_free(defaultFontFamily);
g_free(fantasyFontFamily);
g_free(monospaceFontFamily);
g_free(sansSerifFontFamily);
g_free(serifFontFamily);
g_free(userStylesheetUri);
webkit_web_view_screen_changed(GTK_WIDGET(webView), NULL);
}
| 170,450 |
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: ip_optprint(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int option_len;
const char *sep = "";
for (; length > 0; cp += option_len, length -= option_len) {
u_int option_code;
ND_PRINT((ndo, "%s", sep));
sep = ",";
ND_TCHECK(*cp);
option_code = *cp;
ND_PRINT((ndo, "%s",
tok2str(ip_option_values,"unknown %u",option_code)));
if (option_code == IPOPT_NOP ||
option_code == IPOPT_EOL)
option_len = 1;
else {
ND_TCHECK(cp[1]);
option_len = cp[1];
if (option_len < 2) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
}
if (option_len > length) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
ND_TCHECK2(*cp, option_len);
switch (option_code) {
case IPOPT_EOL:
return;
case IPOPT_TS:
ip_printts(ndo, cp, option_len);
break;
case IPOPT_RR: /* fall through */
case IPOPT_SSRR:
case IPOPT_LSRR:
if (ip_printroute(ndo, cp, option_len) == -1)
goto trunc;
break;
case IPOPT_RA:
if (option_len < 4) {
ND_PRINT((ndo, " [bad length %u]", option_len));
break;
}
ND_TCHECK(cp[3]);
if (EXTRACT_16BITS(&cp[2]) != 0)
ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2])));
break;
case IPOPT_NOP: /* nothing to print - fall through */
case IPOPT_SECURITY:
default:
break;
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
Commit Message: CVE-2017-13037/IP: Add bounds checks when printing time stamp options.
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.
CWE ID: CWE-125 | ip_optprint(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int option_len;
const char *sep = "";
for (; length > 0; cp += option_len, length -= option_len) {
u_int option_code;
ND_PRINT((ndo, "%s", sep));
sep = ",";
ND_TCHECK(*cp);
option_code = *cp;
ND_PRINT((ndo, "%s",
tok2str(ip_option_values,"unknown %u",option_code)));
if (option_code == IPOPT_NOP ||
option_code == IPOPT_EOL)
option_len = 1;
else {
ND_TCHECK(cp[1]);
option_len = cp[1];
if (option_len < 2) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
}
if (option_len > length) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
ND_TCHECK2(*cp, option_len);
switch (option_code) {
case IPOPT_EOL:
return;
case IPOPT_TS:
if (ip_printts(ndo, cp, option_len) == -1)
goto trunc;
break;
case IPOPT_RR: /* fall through */
case IPOPT_SSRR:
case IPOPT_LSRR:
if (ip_printroute(ndo, cp, option_len) == -1)
goto trunc;
break;
case IPOPT_RA:
if (option_len < 4) {
ND_PRINT((ndo, " [bad length %u]", option_len));
break;
}
ND_TCHECK(cp[3]);
if (EXTRACT_16BITS(&cp[2]) != 0)
ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2])));
break;
case IPOPT_NOP: /* nothing to print - fall through */
case IPOPT_SECURITY:
default:
break;
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| 167,845 |
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::ClearForHosts(
const base::Callback<bool(const std::string&)>& host_filter) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (host_filter.is_null()) {
clear();
return;
}
base::TimeTicks now = base::TimeTicks::Now();
for (EntryMap::iterator it = entries_.begin(); it != entries_.end();) {
EntryMap::iterator next_it = std::next(it);
if (host_filter.Run(it->first.hostname)) {
RecordErase(ERASE_CLEAR, now, it->second);
entries_.erase(it);
}
it = next_it;
}
}
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::ClearForHosts(
const base::Callback<bool(const std::string&)>& host_filter) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (host_filter.is_null()) {
clear();
return;
}
bool changed = false;
base::TimeTicks now = base::TimeTicks::Now();
for (EntryMap::iterator it = entries_.begin(); it != entries_.end();) {
EntryMap::iterator next_it = std::next(it);
if (host_filter.Run(it->first.hostname)) {
RecordErase(ERASE_CLEAR, now, it->second);
entries_.erase(it);
changed = true;
}
it = next_it;
}
if (delegate_ && changed)
delegate_->ScheduleWrite();
}
| 172,006 |
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: print_ccp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
switch (opt) {
case CCPOPT_BSDCOMP:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return len;
}
ND_TCHECK2(*(p + 2), 1);
ND_PRINT((ndo, ": Version: %u, Dictionary Bits: %u",
p[2] >> 5, p[2] & 0x1f));
break;
case CCPOPT_MVRCA:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK2(*(p + 2), 1);
ND_PRINT((ndo, ": Features: %u, PxP: %s, History: %u, #CTX-ID: %u",
(p[2] & 0xc0) >> 6,
(p[2] & 0x20) ? "Enabled" : "Disabled",
p[2] & 0x1f, p[3]));
break;
case CCPOPT_DEFLATE:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK2(*(p + 2), 1);
ND_PRINT((ndo, ": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u",
(p[2] & 0xf0) >> 4,
((p[2] & 0x0f) == 8) ? "zlib" : "unknown",
p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03));
break;
/* XXX: to be supported */
#if 0
case CCPOPT_OUI:
case CCPOPT_PRED1:
case CCPOPT_PRED2:
case CCPOPT_PJUMP:
case CCPOPT_HPPPC:
case CCPOPT_STACLZS:
case CCPOPT_MPPC:
case CCPOPT_GFZA:
case CCPOPT_V42BIS:
case CCPOPT_LZSDCP:
case CCPOPT_DEC:
case CCPOPT_RESV:
break;
#endif
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ccp]"));
return 0;
}
Commit Message: CVE-2017-13029/PPP: Fix a bounds check, and clean up other bounds checks.
For configuration protocol options, use ND_TCHECK() and
ND_TCHECK_nBITS() macros, passing them the appropriate pointer argument.
This fixes one case where the ND_TCHECK2() call they replace was not
checking enough bytes.
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.
CWE ID: CWE-125 | print_ccp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
switch (opt) {
case CCPOPT_BSDCOMP:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return len;
}
ND_TCHECK(p[2]);
ND_PRINT((ndo, ": Version: %u, Dictionary Bits: %u",
p[2] >> 5, p[2] & 0x1f));
break;
case CCPOPT_MVRCA:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK(p[3]);
ND_PRINT((ndo, ": Features: %u, PxP: %s, History: %u, #CTX-ID: %u",
(p[2] & 0xc0) >> 6,
(p[2] & 0x20) ? "Enabled" : "Disabled",
p[2] & 0x1f, p[3]));
break;
case CCPOPT_DEFLATE:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK(p[3]);
ND_PRINT((ndo, ": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u",
(p[2] & 0xf0) >> 4,
((p[2] & 0x0f) == 8) ? "zlib" : "unknown",
p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03));
break;
/* XXX: to be supported */
#if 0
case CCPOPT_OUI:
case CCPOPT_PRED1:
case CCPOPT_PRED2:
case CCPOPT_PJUMP:
case CCPOPT_HPPPC:
case CCPOPT_STACLZS:
case CCPOPT_MPPC:
case CCPOPT_GFZA:
case CCPOPT_V42BIS:
case CCPOPT_LZSDCP:
case CCPOPT_DEC:
case CCPOPT_RESV:
break;
#endif
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ccp]"));
return 0;
}
| 167,860 |
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 JBIG2Stream::readSegments() {
Guint segNum, segFlags, segType, page, segLength;
Guint refFlags, nRefSegs;
Guint *refSegs;
Goffset segDataPos;
int c1, c2, c3;
Guint i;
while (readULong(&segNum)) {
if (!readUByte(&segFlags)) {
goto eofError1;
}
segType = segFlags & 0x3f;
if (!readUByte(&refFlags)) {
goto eofError1;
}
nRefSegs = refFlags >> 5;
if (nRefSegs == 7) {
if ((c1 = curStr->getChar()) == EOF ||
(c2 = curStr->getChar()) == EOF ||
(c3 = curStr->getChar()) == EOF) {
goto eofError1;
}
refFlags = (refFlags << 24) | (c1 << 16) | (c2 << 8) | c3;
nRefSegs = refFlags & 0x1fffffff;
for (i = 0; i < (nRefSegs + 9) >> 3; ++i) {
if ((c1 = curStr->getChar()) == EOF) {
goto eofError1;
}
}
}
refSegs = (Guint *)gmallocn(nRefSegs, sizeof(Guint));
if (segNum <= 256) {
for (i = 0; i < nRefSegs; ++i) {
if (!readUByte(&refSegs[i])) {
goto eofError2;
}
}
} else if (segNum <= 65536) {
for (i = 0; i < nRefSegs; ++i) {
if (!readUWord(&refSegs[i])) {
goto eofError2;
}
}
} else {
for (i = 0; i < nRefSegs; ++i) {
if (!readULong(&refSegs[i])) {
goto eofError2;
}
}
}
if (segFlags & 0x40) {
if (!readULong(&page)) {
goto eofError2;
}
} else {
if (!readUByte(&page)) {
goto eofError2;
}
}
if (!readULong(&segLength)) {
goto eofError2;
}
segDataPos = curStr->getPos();
if (!pageBitmap && ((segType >= 4 && segType <= 7) ||
(segType >= 20 && segType <= 43))) {
error(errSyntaxError, curStr->getPos(), "First JBIG2 segment associated with a page must be a page information segment");
goto syntaxError;
}
switch (segType) {
case 0:
if (!readSymbolDictSeg(segNum, segLength, refSegs, nRefSegs)) {
goto syntaxError;
}
break;
case 4:
readTextRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs);
break;
case 6:
readTextRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs);
break;
case 7:
readTextRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs);
break;
case 16:
readPatternDictSeg(segNum, segLength);
break;
case 20:
readHalftoneRegionSeg(segNum, gFalse, gFalse, segLength,
refSegs, nRefSegs);
break;
case 22:
readHalftoneRegionSeg(segNum, gTrue, gFalse, segLength,
refSegs, nRefSegs);
break;
case 23:
readHalftoneRegionSeg(segNum, gTrue, gTrue, segLength,
refSegs, nRefSegs);
break;
case 36:
readGenericRegionSeg(segNum, gFalse, gFalse, segLength);
break;
case 38:
readGenericRegionSeg(segNum, gTrue, gFalse, segLength);
break;
case 39:
readGenericRegionSeg(segNum, gTrue, gTrue, segLength);
break;
case 40:
readGenericRefinementRegionSeg(segNum, gFalse, gFalse, segLength,
refSegs, nRefSegs);
break;
case 42:
readGenericRefinementRegionSeg(segNum, gTrue, gFalse, segLength,
refSegs, nRefSegs);
break;
case 43:
readGenericRefinementRegionSeg(segNum, gTrue, gTrue, segLength,
refSegs, nRefSegs);
break;
case 48:
readPageInfoSeg(segLength);
break;
case 50:
readEndOfStripeSeg(segLength);
break;
case 52:
readProfilesSeg(segLength);
break;
case 53:
readCodeTableSeg(segNum, segLength);
break;
case 62:
readExtensionSeg(segLength);
break;
default:
error(errSyntaxError, curStr->getPos(), "Unknown segment type in JBIG2 stream");
for (i = 0; i < segLength; ++i) {
if ((c1 = curStr->getChar()) == EOF) {
goto eofError2;
}
}
break;
}
if (segLength != 0xffffffff) {
Goffset segExtraBytes = segDataPos + segLength - curStr->getPos();
if (segExtraBytes > 0) {
error(errSyntaxError, curStr->getPos(), "{0:d} extraneous byte{1:s} after segment",
segExtraBytes, (segExtraBytes > 1) ? "s" : "");
int trash;
for (Goffset i = segExtraBytes; i > 0; i--) {
readByte(&trash);
}
} else if (segExtraBytes < 0) {
error(errSyntaxError, curStr->getPos(), "Previous segment handler read too many bytes");
}
}
gfree(refSegs);
}
return;
syntaxError:
gfree(refSegs);
return;
eofError2:
gfree(refSegs);
eofError1:
error(errSyntaxError, curStr->getPos(), "Unexpected EOF in JBIG2 stream");
}
Commit Message:
CWE ID: CWE-119 | void JBIG2Stream::readSegments() {
Guint segNum, segFlags, segType, page, segLength;
Guint refFlags, nRefSegs;
Guint *refSegs;
Goffset segDataPos;
int c1, c2, c3;
Guint i;
while (readULong(&segNum)) {
if (!readUByte(&segFlags)) {
goto eofError1;
}
segType = segFlags & 0x3f;
if (!readUByte(&refFlags)) {
goto eofError1;
}
nRefSegs = refFlags >> 5;
if (nRefSegs == 7) {
if ((c1 = curStr->getChar()) == EOF ||
(c2 = curStr->getChar()) == EOF ||
(c3 = curStr->getChar()) == EOF) {
goto eofError1;
}
refFlags = (refFlags << 24) | (c1 << 16) | (c2 << 8) | c3;
nRefSegs = refFlags & 0x1fffffff;
for (i = 0; i < (nRefSegs + 9) >> 3; ++i) {
if ((c1 = curStr->getChar()) == EOF) {
goto eofError1;
}
}
}
refSegs = (Guint *)gmallocn(nRefSegs, sizeof(Guint));
if (segNum <= 256) {
for (i = 0; i < nRefSegs; ++i) {
if (!readUByte(&refSegs[i])) {
goto eofError2;
}
}
} else if (segNum <= 65536) {
for (i = 0; i < nRefSegs; ++i) {
if (!readUWord(&refSegs[i])) {
goto eofError2;
}
}
} else {
for (i = 0; i < nRefSegs; ++i) {
if (!readULong(&refSegs[i])) {
goto eofError2;
}
}
}
if (segFlags & 0x40) {
if (!readULong(&page)) {
goto eofError2;
}
} else {
if (!readUByte(&page)) {
goto eofError2;
}
}
if (!readULong(&segLength)) {
goto eofError2;
}
segDataPos = curStr->getPos();
if (!pageBitmap && ((segType >= 4 && segType <= 7) ||
(segType >= 20 && segType <= 43))) {
error(errSyntaxError, curStr->getPos(), "First JBIG2 segment associated with a page must be a page information segment");
goto syntaxError;
}
switch (segType) {
case 0:
if (!readSymbolDictSeg(segNum, segLength, refSegs, nRefSegs)) {
goto syntaxError;
}
break;
case 4:
readTextRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs);
break;
case 6:
readTextRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs);
break;
case 7:
readTextRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs);
break;
case 16:
readPatternDictSeg(segNum, segLength);
break;
case 20:
readHalftoneRegionSeg(segNum, gFalse, gFalse, segLength,
refSegs, nRefSegs);
break;
case 22:
readHalftoneRegionSeg(segNum, gTrue, gFalse, segLength,
refSegs, nRefSegs);
break;
case 23:
readHalftoneRegionSeg(segNum, gTrue, gTrue, segLength,
refSegs, nRefSegs);
break;
case 36:
readGenericRegionSeg(segNum, gFalse, gFalse, segLength);
break;
case 38:
readGenericRegionSeg(segNum, gTrue, gFalse, segLength);
break;
case 39:
readGenericRegionSeg(segNum, gTrue, gTrue, segLength);
break;
case 40:
readGenericRefinementRegionSeg(segNum, gFalse, gFalse, segLength,
refSegs, nRefSegs);
break;
case 42:
readGenericRefinementRegionSeg(segNum, gTrue, gFalse, segLength,
refSegs, nRefSegs);
break;
case 43:
readGenericRefinementRegionSeg(segNum, gTrue, gTrue, segLength,
refSegs, nRefSegs);
break;
case 48:
readPageInfoSeg(segLength);
break;
case 50:
readEndOfStripeSeg(segLength);
break;
case 52:
readProfilesSeg(segLength);
break;
case 53:
readCodeTableSeg(segNum, segLength);
break;
case 62:
readExtensionSeg(segLength);
break;
default:
error(errSyntaxError, curStr->getPos(), "Unknown segment type in JBIG2 stream");
for (i = 0; i < segLength; ++i) {
if ((c1 = curStr->getChar()) == EOF) {
goto eofError2;
}
}
break;
}
if (segLength != 0xffffffff) {
Goffset segExtraBytes = segDataPos + segLength - curStr->getPos();
if (segExtraBytes > 0) {
error(errSyntaxError, curStr->getPos(), "{0:lld} extraneous byte{1:s} after segment",
segExtraBytes, (segExtraBytes > 1) ? "s" : "");
int trash;
for (Goffset i = segExtraBytes; i > 0; i--) {
readByte(&trash);
}
} else if (segExtraBytes < 0) {
error(errSyntaxError, curStr->getPos(), "Previous segment handler read too many bytes");
}
}
gfree(refSegs);
}
return;
syntaxError:
gfree(refSegs);
return;
eofError2:
gfree(refSegs);
eofError1:
error(errSyntaxError, curStr->getPos(), "Unexpected EOF in JBIG2 stream");
}
| 165,299 |
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 addr_t* MACH0_(get_entrypoint)(struct MACH0_(obj_t)* bin) {
struct addr_t *entry;
int i;
if (!bin->entry && !bin->sects) {
return NULL;
}
if (!(entry = calloc (1, sizeof (struct addr_t)))) {
return NULL;
}
if (bin->entry) {
entry->addr = entry_to_vaddr (bin);
entry->offset = addr_to_offset (bin, entry->addr);
entry->haddr = sdb_num_get (bin->kv, "mach0.entry.offset", 0);
}
if (!bin->entry || entry->offset == 0) {
for (i = 0; i < bin->nsects; i++) {
if (!strncmp (bin->sects[i].sectname, "__text", 6)) {
entry->offset = (ut64)bin->sects[i].offset;
sdb_num_set (bin->kv, "mach0.entry", entry->offset, 0);
entry->addr = (ut64)bin->sects[i].addr;
if (!entry->addr) { // workaround for object files
entry->addr = entry->offset;
}
break;
}
}
bin->entry = entry->addr;
}
return entry;
}
Commit Message: Fix null deref and uaf in mach0 parser
CWE ID: CWE-416 | struct addr_t* MACH0_(get_entrypoint)(struct MACH0_(obj_t)* bin) {
struct addr_t *entry;
int i;
if (!bin->entry && !bin->sects) {
return NULL;
}
if (!(entry = calloc (1, sizeof (struct addr_t)))) {
return NULL;
}
if (bin->entry) {
entry->addr = entry_to_vaddr (bin);
entry->offset = addr_to_offset (bin, entry->addr);
entry->haddr = sdb_num_get (bin->kv, "mach0.entry.offset", 0);
}
if (!bin->entry || entry->offset == 0) {
for (i = 0; i < bin->nsects; i++) {
if (!strncmp (bin->sects[i].sectname, "__text", 6)) {
entry->offset = (ut64)bin->sects[i].offset;
sdb_num_set (bin->kv, "mach0.entry", entry->offset, 0);
entry->addr = (ut64)bin->sects[i].addr;
if (!entry->addr) { // workaround for object files
entry->addr = entry->offset;
}
break;
}
}
bin->entry = entry->addr;
}
return entry;
}
| 168,233 |
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: ScriptPromise VRDisplay::exitPresent(ScriptState* script_state) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
if (!is_presenting_) {
DOMException* exception = DOMException::Create(
kInvalidStateError, "VRDisplay is not presenting.");
resolver->Reject(exception);
return promise;
}
if (!display_) {
DOMException* exception =
DOMException::Create(kInvalidStateError, "VRService is not available.");
resolver->Reject(exception);
return promise;
}
display_->ExitPresent();
resolver->Resolve();
StopPresenting();
return promise;
}
Commit Message: WebVR: fix initial vsync
Applications sometimes use window.rAF while not presenting, then switch to
vrDisplay.rAF after presentation starts. Depending on the animation loop's
timing, this can cause a race condition where presentation has been started
but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync
being processed after presentation starts so that a queued window.rAF
can run and schedule a vrDisplay.rAF.
BUG=711789
Review-Url: https://codereview.chromium.org/2848483003
Cr-Commit-Position: refs/heads/master@{#468167}
CWE ID: | ScriptPromise VRDisplay::exitPresent(ScriptState* script_state) {
DVLOG(1) << __FUNCTION__;
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
if (!is_presenting_) {
DOMException* exception = DOMException::Create(
kInvalidStateError, "VRDisplay is not presenting.");
resolver->Reject(exception);
return promise;
}
if (!display_) {
DOMException* exception =
DOMException::Create(kInvalidStateError, "VRService is not available.");
resolver->Reject(exception);
return promise;
}
display_->ExitPresent();
resolver->Resolve();
StopPresenting();
return promise;
}
| 172,001 |
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 *cJSON_GetErrorPtr( void )
{
return ep;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | const char *cJSON_GetErrorPtr( void )
| 167,288 |
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 StopCastCallback(
CastConfigDelegate* cast_config,
const CastConfigDelegate::ReceiversAndActivites& receivers_activities) {
for (auto& item : receivers_activities) {
CastConfigDelegate::Activity activity = item.second.activity;
if (activity.allow_stop && activity.id.empty() == false)
cast_config->StopCasting(activity.id);
}
}
Commit Message: Allow the cast tray to function as expected when the installed extension is missing API methods.
BUG=489445
Review URL: https://codereview.chromium.org/1145833003
Cr-Commit-Position: refs/heads/master@{#330663}
CWE ID: CWE-79 | void StopCastCallback(
| 171,626 |
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: InterstitialPage* WebContentsImpl::GetInterstitialPage() const {
return GetRenderManager()->interstitial_page();
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20 | InterstitialPage* WebContentsImpl::GetInterstitialPage() const {
return interstitial_page_;
}
| 172,329 |
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: my_object_many_stringify (MyObject *obj, GHashTable /* char * -> GValue * */ *vals, GHashTable /* char * -> GValue * */ **ret, GError **error)
{
*ret = g_hash_table_new_full (g_str_hash, g_str_equal,
g_free, unset_and_free_gvalue);
g_hash_table_foreach (vals, hash_foreach_stringify, *ret);
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_many_stringify (MyObject *obj, GHashTable /* char * -> GValue * */ *vals, GHashTable /* char * -> GValue * */ **ret, GError **error)
| 165,112 |
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 OMXCodec::configureCodec(const sp<MetaData> &meta) {
ALOGV("configureCodec protected=%d",
(mFlags & kEnableGrallocUsageProtected) ? 1 : 0);
if (!(mFlags & kIgnoreCodecSpecificData)) {
uint32_t type;
const void *data;
size_t size;
if (meta->findData(kKeyESDS, &type, &data, &size)) {
ESDS esds((const char *)data, size);
CHECK_EQ(esds.InitCheck(), (status_t)OK);
const void *codec_specific_data;
size_t codec_specific_data_size;
esds.getCodecSpecificInfo(
&codec_specific_data, &codec_specific_data_size);
addCodecSpecificData(
codec_specific_data, codec_specific_data_size);
} else if (meta->findData(kKeyAVCC, &type, &data, &size)) {
unsigned profile, level;
status_t err;
if ((err = parseAVCCodecSpecificData(
data, size, &profile, &level)) != OK) {
ALOGE("Malformed AVC codec specific data.");
return err;
}
CODEC_LOGI(
"AVC profile = %u (%s), level = %u",
profile, AVCProfileToString(profile), level);
} else if (meta->findData(kKeyHVCC, &type, &data, &size)) {
unsigned profile, level;
status_t err;
if ((err = parseHEVCCodecSpecificData(
data, size, &profile, &level)) != OK) {
ALOGE("Malformed HEVC codec specific data.");
return err;
}
CODEC_LOGI(
"HEVC profile = %u , level = %u",
profile, level);
} else if (meta->findData(kKeyVorbisInfo, &type, &data, &size)) {
addCodecSpecificData(data, size);
CHECK(meta->findData(kKeyVorbisBooks, &type, &data, &size));
addCodecSpecificData(data, size);
} else if (meta->findData(kKeyOpusHeader, &type, &data, &size)) {
addCodecSpecificData(data, size);
CHECK(meta->findData(kKeyOpusCodecDelay, &type, &data, &size));
addCodecSpecificData(data, size);
CHECK(meta->findData(kKeyOpusSeekPreRoll, &type, &data, &size));
addCodecSpecificData(data, size);
}
}
int32_t bitRate = 0;
if (mIsEncoder) {
CHECK(meta->findInt32(kKeyBitRate, &bitRate));
}
if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_NB, mMIME)) {
setAMRFormat(false /* isWAMR */, bitRate);
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_WB, mMIME)) {
setAMRFormat(true /* isWAMR */, bitRate);
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mMIME)) {
int32_t numChannels, sampleRate, aacProfile;
CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
if (!meta->findInt32(kKeyAACProfile, &aacProfile)) {
aacProfile = OMX_AUDIO_AACObjectNull;
}
int32_t isADTS;
if (!meta->findInt32(kKeyIsADTS, &isADTS)) {
isADTS = false;
}
status_t err = setAACFormat(numChannels, sampleRate, bitRate, aacProfile, isADTS);
if (err != OK) {
CODEC_LOGE("setAACFormat() failed (err = %d)", err);
return err;
}
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_MPEG, mMIME)) {
int32_t numChannels, sampleRate;
if (meta->findInt32(kKeyChannelCount, &numChannels)
&& meta->findInt32(kKeySampleRate, &sampleRate)) {
setRawAudioFormat(
mIsEncoder ? kPortIndexInput : kPortIndexOutput,
sampleRate,
numChannels);
}
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AC3, mMIME)) {
int32_t numChannels;
int32_t sampleRate;
CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
status_t err = setAC3Format(numChannels, sampleRate);
if (err != OK) {
CODEC_LOGE("setAC3Format() failed (err = %d)", err);
return err;
}
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_G711_ALAW, mMIME)
|| !strcasecmp(MEDIA_MIMETYPE_AUDIO_G711_MLAW, mMIME)) {
int32_t sampleRate;
int32_t numChannels;
CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
if (!meta->findInt32(kKeySampleRate, &sampleRate)) {
sampleRate = 8000;
}
setG711Format(sampleRate, numChannels);
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_RAW, mMIME)) {
CHECK(!mIsEncoder);
int32_t numChannels, sampleRate;
CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
}
if (!strncasecmp(mMIME, "video/", 6)) {
if (mIsEncoder) {
setVideoInputFormat(mMIME, meta);
} else {
status_t err = setVideoOutputFormat(
mMIME, meta);
if (err != OK) {
return err;
}
}
}
int32_t maxInputSize;
if (meta->findInt32(kKeyMaxInputSize, &maxInputSize)) {
setMinBufferSize(kPortIndexInput, (OMX_U32)maxInputSize);
}
initOutputFormat(meta);
if ((mFlags & kClientNeedsFramebuffer)
&& !strncmp(mComponentName, "OMX.SEC.", 8)) {
OMX_INDEXTYPE index;
status_t err =
mOMX->getExtensionIndex(
mNode,
"OMX.SEC.index.ThumbnailMode",
&index);
if (err != OK) {
return err;
}
OMX_BOOL enable = OMX_TRUE;
err = mOMX->setConfig(mNode, index, &enable, sizeof(enable));
if (err != OK) {
CODEC_LOGE("setConfig('OMX.SEC.index.ThumbnailMode') "
"returned error 0x%08x", err);
return err;
}
mQuirks &= ~kOutputBuffersAreUnreadable;
}
if (mNativeWindow != NULL
&& !mIsEncoder
&& !strncasecmp(mMIME, "video/", 6)
&& !strncmp(mComponentName, "OMX.", 4)) {
status_t err = initNativeWindow();
if (err != OK) {
return err;
}
}
return OK;
}
Commit Message: Fix size check for OMX_IndexParamConsumerUsageBits
since it doesn't follow the OMX convention. And remove support
for the kClientNeedsFrameBuffer flag.
Bug: 27207275
Change-Id: Ia2c119e2456ebf9e2f4e1de5104ef9032a212255
CWE ID: CWE-119 | status_t OMXCodec::configureCodec(const sp<MetaData> &meta) {
ALOGV("configureCodec protected=%d",
(mFlags & kEnableGrallocUsageProtected) ? 1 : 0);
if (!(mFlags & kIgnoreCodecSpecificData)) {
uint32_t type;
const void *data;
size_t size;
if (meta->findData(kKeyESDS, &type, &data, &size)) {
ESDS esds((const char *)data, size);
CHECK_EQ(esds.InitCheck(), (status_t)OK);
const void *codec_specific_data;
size_t codec_specific_data_size;
esds.getCodecSpecificInfo(
&codec_specific_data, &codec_specific_data_size);
addCodecSpecificData(
codec_specific_data, codec_specific_data_size);
} else if (meta->findData(kKeyAVCC, &type, &data, &size)) {
unsigned profile, level;
status_t err;
if ((err = parseAVCCodecSpecificData(
data, size, &profile, &level)) != OK) {
ALOGE("Malformed AVC codec specific data.");
return err;
}
CODEC_LOGI(
"AVC profile = %u (%s), level = %u",
profile, AVCProfileToString(profile), level);
} else if (meta->findData(kKeyHVCC, &type, &data, &size)) {
unsigned profile, level;
status_t err;
if ((err = parseHEVCCodecSpecificData(
data, size, &profile, &level)) != OK) {
ALOGE("Malformed HEVC codec specific data.");
return err;
}
CODEC_LOGI(
"HEVC profile = %u , level = %u",
profile, level);
} else if (meta->findData(kKeyVorbisInfo, &type, &data, &size)) {
addCodecSpecificData(data, size);
CHECK(meta->findData(kKeyVorbisBooks, &type, &data, &size));
addCodecSpecificData(data, size);
} else if (meta->findData(kKeyOpusHeader, &type, &data, &size)) {
addCodecSpecificData(data, size);
CHECK(meta->findData(kKeyOpusCodecDelay, &type, &data, &size));
addCodecSpecificData(data, size);
CHECK(meta->findData(kKeyOpusSeekPreRoll, &type, &data, &size));
addCodecSpecificData(data, size);
}
}
int32_t bitRate = 0;
if (mIsEncoder) {
CHECK(meta->findInt32(kKeyBitRate, &bitRate));
}
if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_NB, mMIME)) {
setAMRFormat(false /* isWAMR */, bitRate);
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_WB, mMIME)) {
setAMRFormat(true /* isWAMR */, bitRate);
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mMIME)) {
int32_t numChannels, sampleRate, aacProfile;
CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
if (!meta->findInt32(kKeyAACProfile, &aacProfile)) {
aacProfile = OMX_AUDIO_AACObjectNull;
}
int32_t isADTS;
if (!meta->findInt32(kKeyIsADTS, &isADTS)) {
isADTS = false;
}
status_t err = setAACFormat(numChannels, sampleRate, bitRate, aacProfile, isADTS);
if (err != OK) {
CODEC_LOGE("setAACFormat() failed (err = %d)", err);
return err;
}
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_MPEG, mMIME)) {
int32_t numChannels, sampleRate;
if (meta->findInt32(kKeyChannelCount, &numChannels)
&& meta->findInt32(kKeySampleRate, &sampleRate)) {
setRawAudioFormat(
mIsEncoder ? kPortIndexInput : kPortIndexOutput,
sampleRate,
numChannels);
}
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AC3, mMIME)) {
int32_t numChannels;
int32_t sampleRate;
CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
status_t err = setAC3Format(numChannels, sampleRate);
if (err != OK) {
CODEC_LOGE("setAC3Format() failed (err = %d)", err);
return err;
}
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_G711_ALAW, mMIME)
|| !strcasecmp(MEDIA_MIMETYPE_AUDIO_G711_MLAW, mMIME)) {
int32_t sampleRate;
int32_t numChannels;
CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
if (!meta->findInt32(kKeySampleRate, &sampleRate)) {
sampleRate = 8000;
}
setG711Format(sampleRate, numChannels);
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_RAW, mMIME)) {
CHECK(!mIsEncoder);
int32_t numChannels, sampleRate;
CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
}
if (!strncasecmp(mMIME, "video/", 6)) {
if (mIsEncoder) {
setVideoInputFormat(mMIME, meta);
} else {
status_t err = setVideoOutputFormat(
mMIME, meta);
if (err != OK) {
return err;
}
}
}
int32_t maxInputSize;
if (meta->findInt32(kKeyMaxInputSize, &maxInputSize)) {
setMinBufferSize(kPortIndexInput, (OMX_U32)maxInputSize);
}
initOutputFormat(meta);
if (mNativeWindow != NULL
&& !mIsEncoder
&& !strncasecmp(mMIME, "video/", 6)
&& !strncmp(mComponentName, "OMX.", 4)) {
status_t err = initNativeWindow();
if (err != OK) {
return err;
}
}
return OK;
}
| 173,800 |
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 gs_lib_ctx_init( gs_memory_t *mem )
{
gs_lib_ctx_t *pio = 0;
/* Check the non gc allocator is being passed in */
if (mem == 0 || mem != mem->non_gc_memory)
return_error(gs_error_Fatal);
#ifndef GS_THREADSAFE
mem_err_print = mem;
#endif
if (mem->gs_lib_ctx) /* one time initialization */
return 0;
pio = (gs_lib_ctx_t*)gs_alloc_bytes_immovable(mem,
sizeof(gs_lib_ctx_t),
"gs_lib_ctx_init");
if( pio == 0 )
return -1;
/* Wholesale blanking is cheaper than retail, and scales better when new
* fields are added. */
memset(pio, 0, sizeof(*pio));
/* Now set the non zero/false/NULL things */
pio->memory = mem;
gs_lib_ctx_get_real_stdio(&pio->fstdin, &pio->fstdout, &pio->fstderr );
pio->stdin_is_interactive = true;
/* id's 1 through 4 are reserved for Device color spaces; see gscspace.h */
pio->gs_next_id = 5; /* this implies that each thread has its own complete state */
/* Need to set this before calling gs_lib_ctx_set_icc_directory. */
mem->gs_lib_ctx = pio;
/* Initialize our default ICCProfilesDir */
pio->profiledir = NULL;
pio->profiledir_len = 0;
gs_lib_ctx_set_icc_directory(mem, DEFAULT_DIR_ICC, strlen(DEFAULT_DIR_ICC));
if (gs_lib_ctx_set_default_device_list(mem, gs_dev_defaults,
strlen(gs_dev_defaults)) < 0) {
gs_free_object(mem, pio, "gs_lib_ctx_init");
mem->gs_lib_ctx = NULL;
}
/* Initialise the underlying CMS. */
if (gscms_create(mem)) {
Failure:
gs_free_object(mem, mem->gs_lib_ctx->default_device_list,
"gs_lib_ctx_fin");
gs_free_object(mem, pio, "gs_lib_ctx_init");
mem->gs_lib_ctx = NULL;
return -1;
}
/* Initialise any lock required for the jpx codec */
if (sjpxd_create(mem)) {
gscms_destroy(mem);
goto Failure;
}
gp_get_realtime(pio->real_time_0);
/* Set scanconverter to 1 (default) */
pio->scanconverter = GS_SCANCONVERTER_DEFAULT;
return 0;
}
Commit Message:
CWE ID: CWE-20 | int gs_lib_ctx_init( gs_memory_t *mem )
{
gs_lib_ctx_t *pio = 0;
/* Check the non gc allocator is being passed in */
if (mem == 0 || mem != mem->non_gc_memory)
return_error(gs_error_Fatal);
#ifndef GS_THREADSAFE
mem_err_print = mem;
#endif
if (mem->gs_lib_ctx) /* one time initialization */
return 0;
pio = (gs_lib_ctx_t*)gs_alloc_bytes_immovable(mem,
sizeof(gs_lib_ctx_t),
"gs_lib_ctx_init");
if( pio == 0 )
return -1;
/* Wholesale blanking is cheaper than retail, and scales better when new
* fields are added. */
memset(pio, 0, sizeof(*pio));
/* Now set the non zero/false/NULL things */
pio->memory = mem;
gs_lib_ctx_get_real_stdio(&pio->fstdin, &pio->fstdout, &pio->fstderr );
pio->stdin_is_interactive = true;
/* id's 1 through 4 are reserved for Device color spaces; see gscspace.h */
pio->gs_next_id = 5; /* this implies that each thread has its own complete state */
/* Need to set this before calling gs_lib_ctx_set_icc_directory. */
mem->gs_lib_ctx = pio;
/* Initialize our default ICCProfilesDir */
pio->profiledir = NULL;
pio->profiledir_len = 0;
gs_lib_ctx_set_icc_directory(mem, DEFAULT_DIR_ICC, strlen(DEFAULT_DIR_ICC));
if (gs_lib_ctx_set_default_device_list(mem, gs_dev_defaults,
strlen(gs_dev_defaults)) < 0) {
gs_free_object(mem, pio, "gs_lib_ctx_init");
mem->gs_lib_ctx = NULL;
}
/* Initialise the underlying CMS. */
if (gscms_create(mem)) {
Failure:
gs_free_object(mem, mem->gs_lib_ctx->default_device_list,
"gs_lib_ctx_fin");
gs_free_object(mem, pio, "gs_lib_ctx_init");
mem->gs_lib_ctx = NULL;
return -1;
}
/* Initialise any lock required for the jpx codec */
if (sjpxd_create(mem)) {
gscms_destroy(mem);
goto Failure;
}
pio->client_check_file_permission = NULL;
gp_get_realtime(pio->real_time_0);
/* Set scanconverter to 1 (default) */
pio->scanconverter = GS_SCANCONVERTER_DEFAULT;
return 0;
}
| 165,266 |
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 *sctp_v6_create_accept_sk(struct sock *sk,
struct sctp_association *asoc,
bool kern)
{
struct sock *newsk;
struct ipv6_pinfo *newnp, *np = inet6_sk(sk);
struct sctp6_sock *newsctp6sk;
struct ipv6_txoptions *opt;
newsk = sk_alloc(sock_net(sk), PF_INET6, GFP_KERNEL, sk->sk_prot, kern);
if (!newsk)
goto out;
sock_init_data(NULL, newsk);
sctp_copy_sock(newsk, sk, asoc);
sock_reset_flag(sk, SOCK_ZAPPED);
newsctp6sk = (struct sctp6_sock *)newsk;
inet_sk(newsk)->pinet6 = &newsctp6sk->inet6;
sctp_sk(newsk)->v4mapped = sctp_sk(sk)->v4mapped;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
rcu_read_lock();
opt = rcu_dereference(np->opt);
if (opt)
opt = ipv6_dup_options(newsk, opt);
RCU_INIT_POINTER(newnp->opt, opt);
rcu_read_unlock();
/* Initialize sk's sport, dport, rcv_saddr and daddr for getsockname()
* and getpeername().
*/
sctp_v6_to_sk_daddr(&asoc->peer.primary_addr, newsk);
newsk->sk_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
sk_refcnt_debug_inc(newsk);
if (newsk->sk_prot->init(newsk)) {
sk_common_release(newsk);
newsk = NULL;
}
out:
return newsk;
}
Commit Message: sctp: do not inherit ipv6_{mc|ac|fl}_list from parent
SCTP needs fixes similar to 83eaddab4378 ("ipv6/dccp: do not inherit
ipv6_mc_list from parent"), otherwise bad things can happen.
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Andrey Konovalov <[email protected]>
Tested-by: Andrey Konovalov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static struct sock *sctp_v6_create_accept_sk(struct sock *sk,
struct sctp_association *asoc,
bool kern)
{
struct sock *newsk;
struct ipv6_pinfo *newnp, *np = inet6_sk(sk);
struct sctp6_sock *newsctp6sk;
struct ipv6_txoptions *opt;
newsk = sk_alloc(sock_net(sk), PF_INET6, GFP_KERNEL, sk->sk_prot, kern);
if (!newsk)
goto out;
sock_init_data(NULL, newsk);
sctp_copy_sock(newsk, sk, asoc);
sock_reset_flag(sk, SOCK_ZAPPED);
newsctp6sk = (struct sctp6_sock *)newsk;
inet_sk(newsk)->pinet6 = &newsctp6sk->inet6;
sctp_sk(newsk)->v4mapped = sctp_sk(sk)->v4mapped;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
newnp->ipv6_mc_list = NULL;
newnp->ipv6_ac_list = NULL;
newnp->ipv6_fl_list = NULL;
rcu_read_lock();
opt = rcu_dereference(np->opt);
if (opt)
opt = ipv6_dup_options(newsk, opt);
RCU_INIT_POINTER(newnp->opt, opt);
rcu_read_unlock();
/* Initialize sk's sport, dport, rcv_saddr and daddr for getsockname()
* and getpeername().
*/
sctp_v6_to_sk_daddr(&asoc->peer.primary_addr, newsk);
newsk->sk_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
sk_refcnt_debug_inc(newsk);
if (newsk->sk_prot->init(newsk)) {
sk_common_release(newsk);
newsk = NULL;
}
out:
return newsk;
}
| 168,129 |
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 crypto_report_kpp(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_kpp rkpp;
strlcpy(rkpp.type, "kpp", sizeof(rkpp.type));
if (nla_put(skb, CRYPTOCFGA_REPORT_KPP,
sizeof(struct crypto_report_kpp), &rkpp))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Commit Message: crypto: user - fix leaking uninitialized memory to userspace
All bytes of the NETLINK_CRYPTO report structures must be initialized,
since they are copied to userspace. The change from strncpy() to
strlcpy() broke this. As a minimal fix, change it back.
Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion")
Cc: <[email protected]> # v4.12+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: | static int crypto_report_kpp(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_kpp rkpp;
strncpy(rkpp.type, "kpp", sizeof(rkpp.type));
if (nla_put(skb, CRYPTOCFGA_REPORT_KPP,
sizeof(struct crypto_report_kpp), &rkpp))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
| 168,967 |
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 jpc_pi_nextrpcl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
int compno;
jpc_picomp_t *picomp;
int xstep;
int ystep;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
uint_fast32_t trx0;
uint_fast32_t try0;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->xstep = 0;
pi->ystep = 0;
for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
++compno, ++picomp) {
for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
picomp->numrlvls; ++rlvlno, ++pirlvl) {
if (pirlvl->prcwidthexpn + pi->picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2 ||
pirlvl->prcheightexpn + pi->picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2) {
return -1;
}
xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1));
ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1));
pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep);
pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep);
}
}
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend &&
pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) {
for (pi->y = pi->ystart; pi->y < pi->yend; pi->y +=
pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend; pi->x +=
pi->xstep - (pi->x % pi->xstep)) {
for (pi->compno = pchg->compnostart,
pi->picomp = &pi->picomps[pi->compno];
pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno <
pi->numcomps; ++pi->compno, ++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
if (((pi->x == pi->xstart &&
((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx)))
|| !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) &&
((pi->y == pi->ystart &&
((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy)))
|| !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x,
pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) -
JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y,
pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) -
JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn);
pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
assert(pi->prcno < pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno <
pi->numlyrs && pi->lyrno < JAS_CAST(int,
pchg->lyrnoend); ++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
Commit Message: Fixed a bug in the packet iterator code.
Added a new regression test case.
CWE ID: CWE-125 | static int jpc_pi_nextrpcl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
int compno;
jpc_picomp_t *picomp;
int xstep;
int ystep;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
uint_fast32_t trx0;
uint_fast32_t try0;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->xstep = 0;
pi->ystep = 0;
for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
++compno, ++picomp) {
for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
picomp->numrlvls; ++rlvlno, ++pirlvl) {
if (pirlvl->prcwidthexpn + picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2 ||
pirlvl->prcheightexpn + picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2) {
return -1;
}
xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1));
ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1));
pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep);
pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep);
}
}
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend &&
pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) {
for (pi->y = pi->ystart; pi->y < pi->yend; pi->y +=
pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend; pi->x +=
pi->xstep - (pi->x % pi->xstep)) {
for (pi->compno = pchg->compnostart,
pi->picomp = &pi->picomps[pi->compno];
pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno <
pi->numcomps; ++pi->compno, ++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
if (((pi->x == pi->xstart &&
((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx)))
|| !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) &&
((pi->y == pi->ystart &&
((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy)))
|| !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x,
pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) -
JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y,
pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) -
JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn);
pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
assert(pi->prcno < pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno <
pi->numlyrs && pi->lyrno < JAS_CAST(int,
pchg->lyrnoend); ++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
| 170,178 |
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: parserep(netdissect_options *ndo,
register const struct sunrpc_msg *rp, register u_int length)
{
register const uint32_t *dp;
u_int len;
enum sunrpc_accept_stat astat;
/*
* Portability note:
* Here we find the address of the ar_verf credentials.
* Originally, this calculation was
* dp = (uint32_t *)&rp->rm_reply.rp_acpt.ar_verf
* On the wire, the rp_acpt field starts immediately after
* the (32 bit) rp_stat field. However, rp_acpt (which is a
* "struct accepted_reply") contains a "struct opaque_auth",
* whose internal representation contains a pointer, so on a
* 64-bit machine the compiler inserts 32 bits of padding
* before rp->rm_reply.rp_acpt.ar_verf. So, we cannot use
* the internal representation to parse the on-the-wire
* representation. Instead, we skip past the rp_stat field,
* which is an "enum" and so occupies one 32-bit word.
*/
dp = ((const uint32_t *)&rp->rm_reply) + 1;
ND_TCHECK(dp[1]);
len = EXTRACT_32BITS(&dp[1]);
if (len >= length)
return (NULL);
/*
* skip past the ar_verf credentials.
*/
dp += (len + (2*sizeof(uint32_t) + 3)) / sizeof(uint32_t);
ND_TCHECK2(dp[0], 0);
/*
* now we can check the ar_stat field
*/
astat = (enum sunrpc_accept_stat) EXTRACT_32BITS(dp);
if (astat != SUNRPC_SUCCESS) {
ND_PRINT((ndo, " %s", tok2str(sunrpc_str, "ar_stat %d", astat)));
nfserr = 1; /* suppress trunc string */
return (NULL);
}
/* successful return */
ND_TCHECK2(*dp, sizeof(astat));
return ((const uint32_t *) (sizeof(astat) + ((const char *)dp)));
trunc:
return (0);
}
Commit Message: CVE-2017-12898/NFS: Fix bounds checking.
Fix the bounds checking for the NFSv3 WRITE procedure to check whether the
length of the opaque data being written is present in the captured data,
not just whether the byte count is present in the captured data.
furthest forward in the packet, not the item before it. (This also lets
us eliminate the check for the "stable" argument being present in the
captured data; rewrite the code to print that to make it a bit clearer.)
Check that the entire ar_stat field is present in the capture.
Note that parse_wcc_attr() is called after we've already checked whether
the wcc_data is present.
Check before fetching the "access" part of the NFSv3 ACCESS results.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Include a test for the "check before fetching the "access" part..." fix,
using the capture supplied by the reporter(s).
CWE ID: CWE-125 | parserep(netdissect_options *ndo,
register const struct sunrpc_msg *rp, register u_int length)
{
register const uint32_t *dp;
u_int len;
enum sunrpc_accept_stat astat;
/*
* Portability note:
* Here we find the address of the ar_verf credentials.
* Originally, this calculation was
* dp = (uint32_t *)&rp->rm_reply.rp_acpt.ar_verf
* On the wire, the rp_acpt field starts immediately after
* the (32 bit) rp_stat field. However, rp_acpt (which is a
* "struct accepted_reply") contains a "struct opaque_auth",
* whose internal representation contains a pointer, so on a
* 64-bit machine the compiler inserts 32 bits of padding
* before rp->rm_reply.rp_acpt.ar_verf. So, we cannot use
* the internal representation to parse the on-the-wire
* representation. Instead, we skip past the rp_stat field,
* which is an "enum" and so occupies one 32-bit word.
*/
dp = ((const uint32_t *)&rp->rm_reply) + 1;
ND_TCHECK(dp[1]);
len = EXTRACT_32BITS(&dp[1]);
if (len >= length)
return (NULL);
/*
* skip past the ar_verf credentials.
*/
dp += (len + (2*sizeof(uint32_t) + 3)) / sizeof(uint32_t);
/*
* now we can check the ar_stat field
*/
ND_TCHECK(dp[0]);
astat = (enum sunrpc_accept_stat) EXTRACT_32BITS(dp);
if (astat != SUNRPC_SUCCESS) {
ND_PRINT((ndo, " %s", tok2str(sunrpc_str, "ar_stat %d", astat)));
nfserr = 1; /* suppress trunc string */
return (NULL);
}
/* successful return */
ND_TCHECK2(*dp, sizeof(astat));
return ((const uint32_t *) (sizeof(astat) + ((const char *)dp)));
trunc:
return (0);
}
| 167,941 |
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 __ip6_datagram_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct sockaddr_in6 *usin = (struct sockaddr_in6 *) uaddr;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct in6_addr *daddr, *final_p, final;
struct dst_entry *dst;
struct flowi6 fl6;
struct ip6_flowlabel *flowlabel = NULL;
struct ipv6_txoptions *opt;
int addr_type;
int err;
if (usin->sin6_family == AF_INET) {
if (__ipv6_only_sock(sk))
return -EAFNOSUPPORT;
err = __ip4_datagram_connect(sk, uaddr, addr_len);
goto ipv4_connected;
}
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (usin->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
memset(&fl6, 0, sizeof(fl6));
if (np->sndflow) {
fl6.flowlabel = usin->sin6_flowinfo&IPV6_FLOWINFO_MASK;
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
}
}
addr_type = ipv6_addr_type(&usin->sin6_addr);
if (addr_type == IPV6_ADDR_ANY) {
/*
* connect to self
*/
usin->sin6_addr.s6_addr[15] = 0x01;
}
daddr = &usin->sin6_addr;
if (addr_type == IPV6_ADDR_MAPPED) {
struct sockaddr_in sin;
if (__ipv6_only_sock(sk)) {
err = -ENETUNREACH;
goto out;
}
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = daddr->s6_addr32[3];
sin.sin_port = usin->sin6_port;
err = __ip4_datagram_connect(sk,
(struct sockaddr *) &sin,
sizeof(sin));
ipv4_connected:
if (err)
goto out;
ipv6_addr_set_v4mapped(inet->inet_daddr, &sk->sk_v6_daddr);
if (ipv6_addr_any(&np->saddr) ||
ipv6_mapped_addr_any(&np->saddr))
ipv6_addr_set_v4mapped(inet->inet_saddr, &np->saddr);
if (ipv6_addr_any(&sk->sk_v6_rcv_saddr) ||
ipv6_mapped_addr_any(&sk->sk_v6_rcv_saddr)) {
ipv6_addr_set_v4mapped(inet->inet_rcv_saddr,
&sk->sk_v6_rcv_saddr);
if (sk->sk_prot->rehash)
sk->sk_prot->rehash(sk);
}
goto out;
}
if (__ipv6_addr_needs_scope_id(addr_type)) {
if (addr_len >= sizeof(struct sockaddr_in6) &&
usin->sin6_scope_id) {
if (sk->sk_bound_dev_if &&
sk->sk_bound_dev_if != usin->sin6_scope_id) {
err = -EINVAL;
goto out;
}
sk->sk_bound_dev_if = usin->sin6_scope_id;
}
if (!sk->sk_bound_dev_if && (addr_type & IPV6_ADDR_MULTICAST))
sk->sk_bound_dev_if = np->mcast_oif;
/* Connect to link-local address requires an interface */
if (!sk->sk_bound_dev_if) {
err = -EINVAL;
goto out;
}
}
sk->sk_v6_daddr = *daddr;
np->flow_label = fl6.flowlabel;
inet->inet_dport = usin->sin6_port;
/*
* Check for a route to destination an obtain the
* destination cache for it.
*/
fl6.flowi6_proto = sk->sk_protocol;
fl6.daddr = sk->sk_v6_daddr;
fl6.saddr = np->saddr;
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.flowi6_mark = sk->sk_mark;
fl6.fl6_dport = inet->inet_dport;
fl6.fl6_sport = inet->inet_sport;
if (!fl6.flowi6_oif && (addr_type&IPV6_ADDR_MULTICAST))
fl6.flowi6_oif = np->mcast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
opt = flowlabel ? flowlabel->opt : np->opt;
final_p = fl6_update_dst(&fl6, opt, &final);
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
err = 0;
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
/* source address lookup done in ip6_dst_lookup */
if (ipv6_addr_any(&np->saddr))
np->saddr = fl6.saddr;
if (ipv6_addr_any(&sk->sk_v6_rcv_saddr)) {
sk->sk_v6_rcv_saddr = fl6.saddr;
inet->inet_rcv_saddr = LOOPBACK4_IPV6;
if (sk->sk_prot->rehash)
sk->sk_prot->rehash(sk);
}
ip6_dst_store(sk, dst,
ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr) ?
&sk->sk_v6_daddr : NULL,
#ifdef CONFIG_IPV6_SUBTREES
ipv6_addr_equal(&fl6.saddr, &np->saddr) ?
&np->saddr :
#endif
NULL);
sk->sk_state = TCP_ESTABLISHED;
sk_set_txhash(sk);
out:
fl6_sock_release(flowlabel);
return err;
}
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 int __ip6_datagram_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct sockaddr_in6 *usin = (struct sockaddr_in6 *) uaddr;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct in6_addr *daddr, *final_p, final;
struct dst_entry *dst;
struct flowi6 fl6;
struct ip6_flowlabel *flowlabel = NULL;
struct ipv6_txoptions *opt;
int addr_type;
int err;
if (usin->sin6_family == AF_INET) {
if (__ipv6_only_sock(sk))
return -EAFNOSUPPORT;
err = __ip4_datagram_connect(sk, uaddr, addr_len);
goto ipv4_connected;
}
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (usin->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
memset(&fl6, 0, sizeof(fl6));
if (np->sndflow) {
fl6.flowlabel = usin->sin6_flowinfo&IPV6_FLOWINFO_MASK;
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
}
}
addr_type = ipv6_addr_type(&usin->sin6_addr);
if (addr_type == IPV6_ADDR_ANY) {
/*
* connect to self
*/
usin->sin6_addr.s6_addr[15] = 0x01;
}
daddr = &usin->sin6_addr;
if (addr_type == IPV6_ADDR_MAPPED) {
struct sockaddr_in sin;
if (__ipv6_only_sock(sk)) {
err = -ENETUNREACH;
goto out;
}
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = daddr->s6_addr32[3];
sin.sin_port = usin->sin6_port;
err = __ip4_datagram_connect(sk,
(struct sockaddr *) &sin,
sizeof(sin));
ipv4_connected:
if (err)
goto out;
ipv6_addr_set_v4mapped(inet->inet_daddr, &sk->sk_v6_daddr);
if (ipv6_addr_any(&np->saddr) ||
ipv6_mapped_addr_any(&np->saddr))
ipv6_addr_set_v4mapped(inet->inet_saddr, &np->saddr);
if (ipv6_addr_any(&sk->sk_v6_rcv_saddr) ||
ipv6_mapped_addr_any(&sk->sk_v6_rcv_saddr)) {
ipv6_addr_set_v4mapped(inet->inet_rcv_saddr,
&sk->sk_v6_rcv_saddr);
if (sk->sk_prot->rehash)
sk->sk_prot->rehash(sk);
}
goto out;
}
if (__ipv6_addr_needs_scope_id(addr_type)) {
if (addr_len >= sizeof(struct sockaddr_in6) &&
usin->sin6_scope_id) {
if (sk->sk_bound_dev_if &&
sk->sk_bound_dev_if != usin->sin6_scope_id) {
err = -EINVAL;
goto out;
}
sk->sk_bound_dev_if = usin->sin6_scope_id;
}
if (!sk->sk_bound_dev_if && (addr_type & IPV6_ADDR_MULTICAST))
sk->sk_bound_dev_if = np->mcast_oif;
/* Connect to link-local address requires an interface */
if (!sk->sk_bound_dev_if) {
err = -EINVAL;
goto out;
}
}
sk->sk_v6_daddr = *daddr;
np->flow_label = fl6.flowlabel;
inet->inet_dport = usin->sin6_port;
/*
* Check for a route to destination an obtain the
* destination cache for it.
*/
fl6.flowi6_proto = sk->sk_protocol;
fl6.daddr = sk->sk_v6_daddr;
fl6.saddr = np->saddr;
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.flowi6_mark = sk->sk_mark;
fl6.fl6_dport = inet->inet_dport;
fl6.fl6_sport = inet->inet_sport;
if (!fl6.flowi6_oif && (addr_type&IPV6_ADDR_MULTICAST))
fl6.flowi6_oif = np->mcast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
rcu_read_lock();
opt = flowlabel ? flowlabel->opt : rcu_dereference(np->opt);
final_p = fl6_update_dst(&fl6, opt, &final);
rcu_read_unlock();
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
err = 0;
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
/* source address lookup done in ip6_dst_lookup */
if (ipv6_addr_any(&np->saddr))
np->saddr = fl6.saddr;
if (ipv6_addr_any(&sk->sk_v6_rcv_saddr)) {
sk->sk_v6_rcv_saddr = fl6.saddr;
inet->inet_rcv_saddr = LOOPBACK4_IPV6;
if (sk->sk_prot->rehash)
sk->sk_prot->rehash(sk);
}
ip6_dst_store(sk, dst,
ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr) ?
&sk->sk_v6_daddr : NULL,
#ifdef CONFIG_IPV6_SUBTREES
ipv6_addr_equal(&fl6.saddr, &np->saddr) ?
&np->saddr :
#endif
NULL);
sk->sk_state = TCP_ESTABLISHED;
sk_set_txhash(sk);
out:
fl6_sock_release(flowlabel);
return err;
}
| 167,329 |
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: PP_Bool LaunchSelLdr(PP_Instance instance,
const char* alleged_url,
int socket_count,
void* imc_handles) {
std::vector<nacl::FileDescriptor> sockets;
IPC::Sender* sender = content::RenderThread::Get();
if (sender == NULL)
sender = g_background_thread_sender.Pointer()->get();
IPC::ChannelHandle channel_handle;
if (!sender->Send(new ChromeViewHostMsg_LaunchNaCl(
GURL(alleged_url), socket_count, &sockets,
&channel_handle))) {
return PP_FALSE;
}
bool invalid_handle = channel_handle.name.empty();
#if defined(OS_POSIX)
if (!invalid_handle)
invalid_handle = (channel_handle.socket.fd == -1);
#endif
if (!invalid_handle)
g_channel_handle_map.Get()[instance] = channel_handle;
CHECK(static_cast<int>(sockets.size()) == socket_count);
for (int i = 0; i < socket_count; i++) {
static_cast<nacl::Handle*>(imc_handles)[i] =
nacl::ToNativeHandle(sockets[i]);
}
return PP_TRUE;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | PP_Bool LaunchSelLdr(PP_Instance instance,
const char* alleged_url, int socket_count,
void* imc_handles) {
std::vector<nacl::FileDescriptor> sockets;
IPC::Sender* sender = content::RenderThread::Get();
if (sender == NULL)
sender = g_background_thread_sender.Pointer()->get();
if (!sender->Send(new ChromeViewHostMsg_LaunchNaCl(
GURL(alleged_url), socket_count, &sockets)))
return PP_FALSE;
CHECK(static_cast<int>(sockets.size()) == socket_count);
for (int i = 0; i < socket_count; i++) {
static_cast<nacl::Handle*>(imc_handles)[i] =
nacl::ToNativeHandle(sockets[i]);
}
return PP_TRUE;
}
| 170,736 |
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_sd_count_referred(Jbig2Ctx *ctx, Jbig2Segment *segment)
{
int index;
Jbig2Segment *rsegment;
int n_dicts = 0;
for (index = 0; index < segment->referred_to_segment_count; index++) {
rsegment = jbig2_find_segment(ctx, segment->referred_to_segments[index]);
if (rsegment && ((rsegment->flags & 63) == 0) &&
rsegment->result && (((Jbig2SymbolDict *) rsegment->result)->n_symbols > 0) && ((*((Jbig2SymbolDict *) rsegment->result)->glyphs) != NULL))
n_dicts++;
}
return (n_dicts);
}
Commit Message:
CWE ID: CWE-119 | jbig2_sd_count_referred(Jbig2Ctx *ctx, Jbig2Segment *segment)
{
int index;
Jbig2Segment *rsegment;
uint32_t n_dicts = 0;
for (index = 0; index < segment->referred_to_segment_count; index++) {
rsegment = jbig2_find_segment(ctx, segment->referred_to_segments[index]);
if (rsegment && ((rsegment->flags & 63) == 0) &&
rsegment->result && (((Jbig2SymbolDict *) rsegment->result)->n_symbols > 0) && ((*((Jbig2SymbolDict *) rsegment->result)->glyphs) != NULL))
n_dicts++;
}
return (n_dicts);
}
| 165,500 |
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 cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)
{
cJSON *current_element = NULL;
if ((object == NULL) || (name == NULL))
{
return NULL;
}
current_element = object->child;
if (case_sensitive)
{
while ((current_element != NULL) && (strcmp(name, current_element->string) != 0))
{
current_element = current_element->next;
}
}
else
{
while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0))
{
current_element = current_element->next;
}
}
return current_element;
}
Commit Message: Fix crash of cJSON_GetObjectItemCaseSensitive when calling it on arrays
CWE ID: CWE-754 | static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)
{
cJSON *current_element = NULL;
if ((object == NULL) || (name == NULL))
{
return NULL;
}
current_element = object->child;
if (case_sensitive)
{
while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0))
{
current_element = current_element->next;
}
}
else
{
while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0))
{
current_element = current_element->next;
}
}
if ((current_element == NULL) || (current_element->string == NULL)) {
return NULL;
}
return current_element;
}
| 169,480 |
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: my_object_increment_retval_error (MyObject *obj, gint32 x, GError **error)
{
if (x + 1 > 10)
{
g_set_error (error,
MY_OBJECT_ERROR,
MY_OBJECT_ERROR_FOO,
"%s",
"x is bigger than 9");
return FALSE;
}
return x + 1;
}
Commit Message:
CWE ID: CWE-264 | my_object_increment_retval_error (MyObject *obj, gint32 x, GError **error)
| 165,107 |
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 peer_recv_callback(rdpTransport* transport, wStream* s, void* extra)
{
freerdp_peer* client = (freerdp_peer*) extra;
rdpRdp* rdp = client->context->rdp;
switch (rdp->state)
{
case CONNECTION_STATE_INITIAL:
if (!rdp_server_accept_nego(rdp, s))
return -1;
if (rdp->nego->selected_protocol & PROTOCOL_NLA)
{
sspi_CopyAuthIdentity(&client->identity, &(rdp->nego->transport->credssp->identity));
IFCALLRET(client->Logon, client->authenticated, client, &client->identity, TRUE);
credssp_free(rdp->nego->transport->credssp);
}
else
{
IFCALLRET(client->Logon, client->authenticated, client, &client->identity, FALSE);
}
break;
case CONNECTION_STATE_NEGO:
if (!rdp_server_accept_mcs_connect_initial(rdp, s))
return -1;
break;
case CONNECTION_STATE_MCS_CONNECT:
if (!rdp_server_accept_mcs_erect_domain_request(rdp, s))
return -1;
break;
case CONNECTION_STATE_MCS_ERECT_DOMAIN:
if (!rdp_server_accept_mcs_attach_user_request(rdp, s))
return -1;
break;
case CONNECTION_STATE_MCS_ATTACH_USER:
if (!rdp_server_accept_mcs_channel_join_request(rdp, s))
return -1;
break;
case CONNECTION_STATE_MCS_CHANNEL_JOIN:
if (rdp->settings->DisableEncryption)
{
if (!rdp_server_accept_client_keys(rdp, s))
return -1;
break;
}
rdp->state = CONNECTION_STATE_ESTABLISH_KEYS;
/* FALLTHROUGH */
case CONNECTION_STATE_ESTABLISH_KEYS:
if (!rdp_server_accept_client_info(rdp, s))
return -1;
IFCALL(client->Capabilities, client);
if (!rdp_send_demand_active(rdp))
return -1;
break;
case CONNECTION_STATE_LICENSE:
if (!rdp_server_accept_confirm_active(rdp, s))
{
/**
* During reactivation sequence the client might sent some input or channel data
* before receiving the Deactivate All PDU. We need to process them as usual.
*/
Stream_SetPosition(s, 0);
return peer_recv_pdu(client, s);
}
break;
case CONNECTION_STATE_ACTIVE:
if (peer_recv_pdu(client, s) < 0)
return -1;
break;
default:
fprintf(stderr, "Invalid state %d\n", rdp->state);
return -1;
}
return 0;
}
Commit Message: nla: invalidate sec handle after creation
If sec pointer isn't invalidated after creation it is not possible
to check if the upper and lower pointers are valid.
This fixes a segfault in the server part if the client disconnects before
the authentication was finished.
CWE ID: CWE-476 | static int peer_recv_callback(rdpTransport* transport, wStream* s, void* extra)
{
freerdp_peer* client = (freerdp_peer*) extra;
rdpRdp* rdp = client->context->rdp;
switch (rdp->state)
{
case CONNECTION_STATE_INITIAL:
if (!rdp_server_accept_nego(rdp, s))
return -1;
if (rdp->nego->selected_protocol & PROTOCOL_NLA)
{
sspi_CopyAuthIdentity(&client->identity, &(rdp->nego->transport->credssp->identity));
IFCALLRET(client->Logon, client->authenticated, client, &client->identity, TRUE);
credssp_free(rdp->nego->transport->credssp);
rdp->nego->transport->credssp = NULL;
}
else
{
IFCALLRET(client->Logon, client->authenticated, client, &client->identity, FALSE);
}
break;
case CONNECTION_STATE_NEGO:
if (!rdp_server_accept_mcs_connect_initial(rdp, s))
return -1;
break;
case CONNECTION_STATE_MCS_CONNECT:
if (!rdp_server_accept_mcs_erect_domain_request(rdp, s))
return -1;
break;
case CONNECTION_STATE_MCS_ERECT_DOMAIN:
if (!rdp_server_accept_mcs_attach_user_request(rdp, s))
return -1;
break;
case CONNECTION_STATE_MCS_ATTACH_USER:
if (!rdp_server_accept_mcs_channel_join_request(rdp, s))
return -1;
break;
case CONNECTION_STATE_MCS_CHANNEL_JOIN:
if (rdp->settings->DisableEncryption)
{
if (!rdp_server_accept_client_keys(rdp, s))
return -1;
break;
}
rdp->state = CONNECTION_STATE_ESTABLISH_KEYS;
/* FALLTHROUGH */
case CONNECTION_STATE_ESTABLISH_KEYS:
if (!rdp_server_accept_client_info(rdp, s))
return -1;
IFCALL(client->Capabilities, client);
if (!rdp_send_demand_active(rdp))
return -1;
break;
case CONNECTION_STATE_LICENSE:
if (!rdp_server_accept_confirm_active(rdp, s))
{
/**
* During reactivation sequence the client might sent some input or channel data
* before receiving the Deactivate All PDU. We need to process them as usual.
*/
Stream_SetPosition(s, 0);
return peer_recv_pdu(client, s);
}
break;
case CONNECTION_STATE_ACTIVE:
if (peer_recv_pdu(client, s) < 0)
return -1;
break;
default:
fprintf(stderr, "Invalid state %d\n", rdp->state);
return -1;
}
return 0;
}
| 167,600 |
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: ReleaseAccelerator(ui::KeyboardCode keycode,
bool shift_pressed,
bool ctrl_pressed,
bool alt_pressed)
: ui::Accelerator(keycode, shift_pressed, ctrl_pressed, alt_pressed) {
set_type(ui::ET_KEY_RELEASED);
}
Commit Message: accelerators: Remove deprecated Accelerator ctor that takes booleans.
BUG=128242
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10399085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137957 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | ReleaseAccelerator(ui::KeyboardCode keycode,
ReleaseAccelerator(ui::KeyboardCode keycode, int modifiers)
: ui::Accelerator(keycode, modifiers) {
set_type(ui::ET_KEY_RELEASED);
}
| 170,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 inline long decode_twos_comp(ulong c, int prec)
{
long result;
assert(prec >= 2);
jas_eprintf("warning: support for signed data is untested\n");
result = (c & ((1 << (prec - 1)) - 1)) - (c & (1 << (prec - 1)));
return result;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | static inline long decode_twos_comp(ulong c, int prec)
static inline long decode_twos_comp(jas_ulong c, int prec)
{
long result;
assert(prec >= 2);
jas_eprintf("warning: support for signed data is untested\n");
result = (c & ((1 << (prec - 1)) - 1)) - (c & (1 << (prec - 1)));
return result;
}
| 168,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: exsltCryptoRc4DecryptFunction (xmlXPathParserContextPtr ctxt, int nargs) {
int key_len = 0, key_size = 0;
int str_len = 0, bin_len = 0, ret_len = 0;
xmlChar *key = NULL, *str = NULL, *padkey = NULL, *bin =
NULL, *ret = NULL;
xsltTransformContextPtr tctxt = NULL;
if (nargs != 2) {
xmlXPathSetArityError (ctxt);
return;
}
tctxt = xsltXPathGetTransformContext(ctxt);
str = xmlXPathPopString (ctxt);
str_len = xmlUTF8Strlen (str);
if (str_len == 0) {
xmlXPathReturnEmptyString (ctxt);
xmlFree (str);
return;
}
key = xmlXPathPopString (ctxt);
key_len = xmlUTF8Strlen (key);
if (key_len == 0) {
xmlXPathReturnEmptyString (ctxt);
xmlFree (key);
xmlFree (str);
return;
}
padkey = xmlMallocAtomic (RC4_KEY_LENGTH + 1);
if (padkey == NULL) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: Failed to allocate padkey\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
memset(padkey, 0, RC4_KEY_LENGTH + 1);
key_size = xmlUTF8Strsize (key, key_len);
if ((key_size > RC4_KEY_LENGTH) || (key_size < 0)) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: key size too long or key broken\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
memcpy (padkey, key, key_size);
/* decode hex to binary */
bin_len = str_len;
bin = xmlMallocAtomic (bin_len);
if (bin == NULL) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: Failed to allocate string\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
ret_len = exsltCryptoHex2Bin (str, str_len, bin, bin_len);
/* decrypt the binary blob */
ret = xmlMallocAtomic (ret_len + 1);
if (ret == NULL) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: Failed to allocate result\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
PLATFORM_RC4_DECRYPT (ctxt, padkey, bin, ret_len, ret, ret_len);
ret[ret_len] = 0;
xmlXPathReturnString (ctxt, ret);
done:
if (key != NULL)
xmlFree (key);
if (str != NULL)
xmlFree (str);
if (padkey != NULL)
xmlFree (padkey);
if (bin != NULL)
xmlFree (bin);
}
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 | exsltCryptoRc4DecryptFunction (xmlXPathParserContextPtr ctxt, int nargs) {
int key_len = 0;
int str_len = 0, bin_len = 0, ret_len = 0;
xmlChar *key = NULL, *str = NULL, *padkey = NULL, *bin =
NULL, *ret = NULL;
xsltTransformContextPtr tctxt = NULL;
if (nargs != 2) {
xmlXPathSetArityError (ctxt);
return;
}
tctxt = xsltXPathGetTransformContext(ctxt);
str = xmlXPathPopString (ctxt);
str_len = xmlStrlen (str);
if (str_len == 0) {
xmlXPathReturnEmptyString (ctxt);
xmlFree (str);
return;
}
key = xmlXPathPopString (ctxt);
key_len = xmlStrlen (key);
if (key_len == 0) {
xmlXPathReturnEmptyString (ctxt);
xmlFree (key);
xmlFree (str);
return;
}
padkey = xmlMallocAtomic (RC4_KEY_LENGTH + 1);
if (padkey == NULL) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: Failed to allocate padkey\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
memset(padkey, 0, RC4_KEY_LENGTH + 1);
if ((key_len > RC4_KEY_LENGTH) || (key_len < 0)) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: key size too long or key broken\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
memcpy (padkey, key, key_len);
/* decode hex to binary */
bin_len = str_len;
bin = xmlMallocAtomic (bin_len);
if (bin == NULL) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: Failed to allocate string\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
ret_len = exsltCryptoHex2Bin (str, str_len, bin, bin_len);
/* decrypt the binary blob */
ret = xmlMallocAtomic (ret_len + 1);
if (ret == NULL) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: Failed to allocate result\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
PLATFORM_RC4_DECRYPT (ctxt, padkey, bin, ret_len, ret, ret_len);
ret[ret_len] = 0;
xmlXPathReturnString (ctxt, ret);
done:
if (key != NULL)
xmlFree (key);
if (str != NULL)
xmlFree (str);
if (padkey != NULL)
xmlFree (padkey);
if (bin != NULL)
xmlFree (bin);
}
| 173,287 |
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: stringprep_strerror (Stringprep_rc rc)
{
const char *p;
bindtextdomain (PACKAGE, LOCALEDIR);
switch (rc)
{
case STRINGPREP_OK:
p = _("Success");
break;
case STRINGPREP_CONTAINS_UNASSIGNED:
p = _("Forbidden unassigned code points in input");
break;
case STRINGPREP_CONTAINS_PROHIBITED:
p = _("Prohibited code points in input");
break;
case STRINGPREP_BIDI_BOTH_L_AND_RAL:
p = _("Conflicting bidirectional properties in input");
break;
case STRINGPREP_BIDI_LEADTRAIL_NOT_RAL:
p = _("Malformed bidirectional string");
break;
case STRINGPREP_BIDI_CONTAINS_PROHIBITED:
p = _("Prohibited bidirectional code points in input");
break;
case STRINGPREP_TOO_SMALL_BUFFER:
p = _("Output would exceed the buffer space provided");
break;
case STRINGPREP_PROFILE_ERROR:
p = _("Error in stringprep profile definition");
break;
case STRINGPREP_FLAG_ERROR:
p = _("Flag conflict with profile");
break;
case STRINGPREP_UNKNOWN_PROFILE:
case STRINGPREP_UNKNOWN_PROFILE:
p = _("Unknown profile");
break;
case STRINGPREP_NFKC_FAILED:
p = _("Unicode normalization failed (internal error)");
break;
default:
p = _("Unknown error");
break;
}
return p;
}
Commit Message:
CWE ID: CWE-119 | stringprep_strerror (Stringprep_rc rc)
{
const char *p;
bindtextdomain (PACKAGE, LOCALEDIR);
switch (rc)
{
case STRINGPREP_OK:
p = _("Success");
break;
case STRINGPREP_CONTAINS_UNASSIGNED:
p = _("Forbidden unassigned code points in input");
break;
case STRINGPREP_CONTAINS_PROHIBITED:
p = _("Prohibited code points in input");
break;
case STRINGPREP_BIDI_BOTH_L_AND_RAL:
p = _("Conflicting bidirectional properties in input");
break;
case STRINGPREP_BIDI_LEADTRAIL_NOT_RAL:
p = _("Malformed bidirectional string");
break;
case STRINGPREP_BIDI_CONTAINS_PROHIBITED:
p = _("Prohibited bidirectional code points in input");
break;
case STRINGPREP_TOO_SMALL_BUFFER:
p = _("Output would exceed the buffer space provided");
break;
case STRINGPREP_PROFILE_ERROR:
p = _("Error in stringprep profile definition");
break;
case STRINGPREP_FLAG_ERROR:
p = _("Flag conflict with profile");
break;
case STRINGPREP_UNKNOWN_PROFILE:
case STRINGPREP_UNKNOWN_PROFILE:
p = _("Unknown profile");
break;
case STRINGPREP_ICONV_ERROR:
p = _("Could not convert string in locale encoding.");
break;
case STRINGPREP_NFKC_FAILED:
p = _("Unicode normalization failed (internal error)");
break;
default:
p = _("Unknown error");
break;
}
return p;
}
| 164,761 |
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: BlobStorageContext::BlobFlattener::BlobFlattener(
const BlobDataBuilder& input_builder,
BlobEntry* output_blob,
BlobStorageRegistry* registry) {
const std::string& uuid = input_builder.uuid_;
std::set<std::string> dependent_blob_uuids;
size_t num_files_with_unknown_size = 0;
size_t num_building_dependent_blobs = 0;
bool found_memory_transport = false;
bool found_file_transport = false;
base::CheckedNumeric<uint64_t> checked_total_size = 0;
base::CheckedNumeric<uint64_t> checked_total_memory_size = 0;
base::CheckedNumeric<uint64_t> checked_transport_quota_needed = 0;
base::CheckedNumeric<uint64_t> checked_copy_quota_needed = 0;
for (scoped_refptr<BlobDataItem> input_item : input_builder.items_) {
const DataElement& input_element = input_item->data_element();
DataElement::Type type = input_element.type();
uint64_t length = input_element.length();
RecordBlobItemSizeStats(input_element);
if (IsBytes(type)) {
DCHECK_NE(0 + DataElement::kUnknownSize, input_element.length());
found_memory_transport = true;
if (found_file_transport) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
contains_unpopulated_transport_items |=
(type == DataElement::TYPE_BYTES_DESCRIPTION);
checked_transport_quota_needed += length;
checked_total_size += length;
scoped_refptr<ShareableBlobDataItem> item = new ShareableBlobDataItem(
std::move(input_item), ShareableBlobDataItem::QUOTA_NEEDED);
pending_transport_items.push_back(item);
transport_items.push_back(item.get());
output_blob->AppendSharedBlobItem(std::move(item));
continue;
}
if (type == DataElement::TYPE_BLOB) {
BlobEntry* ref_entry = registry->GetEntry(input_element.blob_uuid());
if (!ref_entry || input_element.blob_uuid() == uuid) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
if (BlobStatusIsError(ref_entry->status())) {
status = BlobStatus::ERR_REFERENCED_BLOB_BROKEN;
return;
}
if (ref_entry->total_size() == DataElement::kUnknownSize) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
if (dependent_blob_uuids.find(input_element.blob_uuid()) ==
dependent_blob_uuids.end()) {
dependent_blobs.push_back(
std::make_pair(input_element.blob_uuid(), ref_entry));
dependent_blob_uuids.insert(input_element.blob_uuid());
if (BlobStatusIsPending(ref_entry->status())) {
num_building_dependent_blobs++;
}
}
length = length == DataElement::kUnknownSize ? ref_entry->total_size()
: input_element.length();
checked_total_size += length;
if (input_element.offset() == 0 && length == ref_entry->total_size()) {
for (const auto& shareable_item : ref_entry->items()) {
output_blob->AppendSharedBlobItem(shareable_item);
}
continue;
}
if (input_element.offset() + length > ref_entry->total_size()) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
BlobSlice slice(*ref_entry, input_element.offset(), length);
if (!slice.copying_memory_size.IsValid() ||
!slice.total_memory_size.IsValid()) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
checked_total_memory_size += slice.total_memory_size;
if (slice.first_source_item) {
copies.push_back(ItemCopyEntry(slice.first_source_item,
slice.first_item_slice_offset,
slice.dest_items.front()));
pending_copy_items.push_back(slice.dest_items.front());
}
if (slice.last_source_item) {
copies.push_back(
ItemCopyEntry(slice.last_source_item, 0, slice.dest_items.back()));
pending_copy_items.push_back(slice.dest_items.back());
}
checked_copy_quota_needed += slice.copying_memory_size;
for (auto& shareable_item : slice.dest_items) {
output_blob->AppendSharedBlobItem(std::move(shareable_item));
}
continue;
}
scoped_refptr<ShareableBlobDataItem> item;
if (BlobDataBuilder::IsFutureFileItem(input_element)) {
found_file_transport = true;
if (found_memory_transport) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
contains_unpopulated_transport_items = true;
item = new ShareableBlobDataItem(std::move(input_item),
ShareableBlobDataItem::QUOTA_NEEDED);
pending_transport_items.push_back(item);
transport_items.push_back(item.get());
checked_transport_quota_needed += length;
} else {
item = new ShareableBlobDataItem(
std::move(input_item),
ShareableBlobDataItem::POPULATED_WITHOUT_QUOTA);
}
if (length == DataElement::kUnknownSize)
num_files_with_unknown_size++;
checked_total_size += length;
output_blob->AppendSharedBlobItem(std::move(item));
}
if (num_files_with_unknown_size > 1 && input_builder.items_.size() > 1) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
if (!checked_total_size.IsValid() || !checked_total_memory_size.IsValid() ||
!checked_transport_quota_needed.IsValid() ||
!checked_copy_quota_needed.IsValid()) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
total_size = checked_total_size.ValueOrDie();
total_memory_size = checked_total_memory_size.ValueOrDie();
transport_quota_needed = checked_transport_quota_needed.ValueOrDie();
copy_quota_needed = checked_copy_quota_needed.ValueOrDie();
transport_quota_type = found_file_transport ? TransportQuotaType::FILE
: TransportQuotaType::MEMORY;
if (transport_quota_needed) {
status = BlobStatus::PENDING_QUOTA;
} else {
status = BlobStatus::PENDING_INTERNALS;
}
}
Commit Message: [BlobStorage] Fixing potential overflow
Bug: 779314
Change-Id: I74612639d20544e4c12230569c7b88fbe669ec03
Reviewed-on: https://chromium-review.googlesource.com/747725
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Daniel Murphy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#512977}
CWE ID: CWE-119 | BlobStorageContext::BlobFlattener::BlobFlattener(
const BlobDataBuilder& input_builder,
BlobEntry* output_blob,
BlobStorageRegistry* registry) {
const std::string& uuid = input_builder.uuid_;
std::set<std::string> dependent_blob_uuids;
size_t num_files_with_unknown_size = 0;
size_t num_building_dependent_blobs = 0;
bool found_memory_transport = false;
bool found_file_transport = false;
base::CheckedNumeric<uint64_t> checked_total_size = 0;
base::CheckedNumeric<uint64_t> checked_total_memory_size = 0;
base::CheckedNumeric<uint64_t> checked_transport_quota_needed = 0;
base::CheckedNumeric<uint64_t> checked_copy_quota_needed = 0;
for (scoped_refptr<BlobDataItem> input_item : input_builder.items_) {
const DataElement& input_element = input_item->data_element();
DataElement::Type type = input_element.type();
uint64_t length = input_element.length();
RecordBlobItemSizeStats(input_element);
if (IsBytes(type)) {
DCHECK_NE(0 + DataElement::kUnknownSize, input_element.length());
found_memory_transport = true;
if (found_file_transport) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
contains_unpopulated_transport_items |=
(type == DataElement::TYPE_BYTES_DESCRIPTION);
checked_transport_quota_needed += length;
checked_total_size += length;
scoped_refptr<ShareableBlobDataItem> item = new ShareableBlobDataItem(
std::move(input_item), ShareableBlobDataItem::QUOTA_NEEDED);
pending_transport_items.push_back(item);
transport_items.push_back(item.get());
output_blob->AppendSharedBlobItem(std::move(item));
continue;
}
if (type == DataElement::TYPE_BLOB) {
BlobEntry* ref_entry = registry->GetEntry(input_element.blob_uuid());
if (!ref_entry || input_element.blob_uuid() == uuid) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
if (BlobStatusIsError(ref_entry->status())) {
status = BlobStatus::ERR_REFERENCED_BLOB_BROKEN;
return;
}
if (ref_entry->total_size() == DataElement::kUnknownSize) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
if (dependent_blob_uuids.find(input_element.blob_uuid()) ==
dependent_blob_uuids.end()) {
dependent_blobs.push_back(
std::make_pair(input_element.blob_uuid(), ref_entry));
dependent_blob_uuids.insert(input_element.blob_uuid());
if (BlobStatusIsPending(ref_entry->status())) {
num_building_dependent_blobs++;
}
}
length = length == DataElement::kUnknownSize ? ref_entry->total_size()
: input_element.length();
checked_total_size += length;
if (input_element.offset() == 0 && length == ref_entry->total_size()) {
for (const auto& shareable_item : ref_entry->items()) {
output_blob->AppendSharedBlobItem(shareable_item);
}
continue;
}
uint64_t end_byte;
if (!base::CheckAdd(input_element.offset(), length)
.AssignIfValid(&end_byte) ||
end_byte > ref_entry->total_size()) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
BlobSlice slice(*ref_entry, input_element.offset(), length);
if (!slice.copying_memory_size.IsValid() ||
!slice.total_memory_size.IsValid()) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
checked_total_memory_size += slice.total_memory_size;
if (slice.first_source_item) {
copies.push_back(ItemCopyEntry(slice.first_source_item,
slice.first_item_slice_offset,
slice.dest_items.front()));
pending_copy_items.push_back(slice.dest_items.front());
}
if (slice.last_source_item) {
copies.push_back(
ItemCopyEntry(slice.last_source_item, 0, slice.dest_items.back()));
pending_copy_items.push_back(slice.dest_items.back());
}
checked_copy_quota_needed += slice.copying_memory_size;
for (auto& shareable_item : slice.dest_items) {
output_blob->AppendSharedBlobItem(std::move(shareable_item));
}
continue;
}
scoped_refptr<ShareableBlobDataItem> item;
if (BlobDataBuilder::IsFutureFileItem(input_element)) {
found_file_transport = true;
if (found_memory_transport) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
contains_unpopulated_transport_items = true;
item = new ShareableBlobDataItem(std::move(input_item),
ShareableBlobDataItem::QUOTA_NEEDED);
pending_transport_items.push_back(item);
transport_items.push_back(item.get());
checked_transport_quota_needed += length;
} else {
item = new ShareableBlobDataItem(
std::move(input_item),
ShareableBlobDataItem::POPULATED_WITHOUT_QUOTA);
}
if (length == DataElement::kUnknownSize)
num_files_with_unknown_size++;
checked_total_size += length;
output_blob->AppendSharedBlobItem(std::move(item));
}
if (num_files_with_unknown_size > 1 && input_builder.items_.size() > 1) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
if (!checked_total_size.IsValid() || !checked_total_memory_size.IsValid() ||
!checked_transport_quota_needed.IsValid() ||
!checked_copy_quota_needed.IsValid()) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
total_size = checked_total_size.ValueOrDie();
total_memory_size = checked_total_memory_size.ValueOrDie();
transport_quota_needed = checked_transport_quota_needed.ValueOrDie();
copy_quota_needed = checked_copy_quota_needed.ValueOrDie();
transport_quota_type = found_file_transport ? TransportQuotaType::FILE
: TransportQuotaType::MEMORY;
if (transport_quota_needed) {
status = BlobStatus::PENDING_QUOTA;
} else {
status = BlobStatus::PENDING_INTERNALS;
}
}
| 172,927 |
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: ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
struct pipe_inode_info *pipe, size_t len,
unsigned int flags)
{
struct sock *sk = sock->sk;
struct tcp_splice_state tss = {
.pipe = pipe,
.len = len,
.flags = flags,
};
long timeo;
ssize_t spliced;
int ret;
sock_rps_record_flow(sk);
/*
* We can't seek on a socket input
*/
if (unlikely(*ppos))
return -ESPIPE;
ret = spliced = 0;
lock_sock(sk);
timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK);
while (tss.len) {
ret = __tcp_splice_read(sk, &tss);
if (ret < 0)
break;
else if (!ret) {
if (spliced)
break;
if (sock_flag(sk, SOCK_DONE))
break;
if (sk->sk_err) {
ret = sock_error(sk);
break;
}
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
if (sk->sk_state == TCP_CLOSE) {
/*
* This occurs when user tries to read
* from never connected socket.
*/
if (!sock_flag(sk, SOCK_DONE))
ret = -ENOTCONN;
break;
}
if (!timeo) {
ret = -EAGAIN;
break;
}
sk_wait_data(sk, &timeo, NULL);
if (signal_pending(current)) {
ret = sock_intr_errno(timeo);
break;
}
continue;
}
tss.len -= ret;
spliced += ret;
if (!timeo)
break;
release_sock(sk);
lock_sock(sk);
if (sk->sk_err || sk->sk_state == TCP_CLOSE ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
signal_pending(current))
break;
}
release_sock(sk);
if (spliced)
return spliced;
return ret;
}
Commit Message: tcp: avoid infinite loop in tcp_splice_read()
Splicing from TCP socket is vulnerable when a packet with URG flag is
received and stored into receive queue.
__tcp_splice_read() returns 0, and sk_wait_data() immediately
returns since there is the problematic skb in queue.
This is a nice way to burn cpu (aka infinite loop) and trigger
soft lockups.
Again, this gem was found by syzkaller tool.
Fixes: 9c55e01c0cc8 ("[TCP]: Splice receive support.")
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Dmitry Vyukov <[email protected]>
Cc: Willy Tarreau <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-835 | ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
struct pipe_inode_info *pipe, size_t len,
unsigned int flags)
{
struct sock *sk = sock->sk;
struct tcp_splice_state tss = {
.pipe = pipe,
.len = len,
.flags = flags,
};
long timeo;
ssize_t spliced;
int ret;
sock_rps_record_flow(sk);
/*
* We can't seek on a socket input
*/
if (unlikely(*ppos))
return -ESPIPE;
ret = spliced = 0;
lock_sock(sk);
timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK);
while (tss.len) {
ret = __tcp_splice_read(sk, &tss);
if (ret < 0)
break;
else if (!ret) {
if (spliced)
break;
if (sock_flag(sk, SOCK_DONE))
break;
if (sk->sk_err) {
ret = sock_error(sk);
break;
}
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
if (sk->sk_state == TCP_CLOSE) {
/*
* This occurs when user tries to read
* from never connected socket.
*/
if (!sock_flag(sk, SOCK_DONE))
ret = -ENOTCONN;
break;
}
if (!timeo) {
ret = -EAGAIN;
break;
}
/* if __tcp_splice_read() got nothing while we have
* an skb in receive queue, we do not want to loop.
* This might happen with URG data.
*/
if (!skb_queue_empty(&sk->sk_receive_queue))
break;
sk_wait_data(sk, &timeo, NULL);
if (signal_pending(current)) {
ret = sock_intr_errno(timeo);
break;
}
continue;
}
tss.len -= ret;
spliced += ret;
if (!timeo)
break;
release_sock(sk);
lock_sock(sk);
if (sk->sk_err || sk->sk_state == TCP_CLOSE ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
signal_pending(current))
break;
}
release_sock(sk);
if (spliced)
return spliced;
return ret;
}
| 168,361 |
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: GDataFileError GDataWapiFeedProcessor::FeedToFileResourceMap(
const std::vector<DocumentFeed*>& feed_list,
FileResourceIdMap* file_map,
int64* feed_changestamp,
FeedToFileResourceMapUmaStats* uma_stats) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(uma_stats);
GDataFileError error = GDATA_FILE_OK;
uma_stats->num_regular_files = 0;
uma_stats->num_hosted_documents = 0;
uma_stats->num_files_with_entry_kind.clear();
for (size_t i = 0; i < feed_list.size(); ++i) {
const DocumentFeed* feed = feed_list[i];
if (i == 0) {
const Link* root_feed_upload_link =
feed->GetLinkByType(Link::RESUMABLE_CREATE_MEDIA);
if (root_feed_upload_link)
directory_service_->root()->set_upload_url(
root_feed_upload_link->href());
*feed_changestamp = feed->largest_changestamp();
DCHECK_GE(*feed_changestamp, 0);
}
for (ScopedVector<DocumentEntry>::const_iterator iter =
feed->entries().begin();
iter != feed->entries().end(); ++iter) {
DocumentEntry* doc = *iter;
GDataEntry* entry = GDataEntry::FromDocumentEntry(
NULL, doc, directory_service_);
if (!entry)
continue;
GDataFile* as_file = entry->AsGDataFile();
if (as_file) {
if (as_file->is_hosted_document())
++uma_stats->num_hosted_documents;
else
++uma_stats->num_regular_files;
++uma_stats->num_files_with_entry_kind[as_file->kind()];
}
FileResourceIdMap::iterator map_entry =
file_map->find(entry->resource_id());
if (map_entry != file_map->end()) {
LOG(WARNING) << "Found duplicate file "
<< map_entry->second->base_name();
delete map_entry->second;
file_map->erase(map_entry);
}
file_map->insert(
std::pair<std::string, GDataEntry*>(entry->resource_id(), entry));
}
}
if (error != GDATA_FILE_OK) {
STLDeleteValues(file_map);
}
return error;
}
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 | GDataFileError GDataWapiFeedProcessor::FeedToFileResourceMap(
const std::vector<DocumentFeed*>& feed_list,
FileResourceIdMap* file_map,
int64* feed_changestamp,
FeedToFileResourceMapUmaStats* uma_stats) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(uma_stats);
GDataFileError error = GDATA_FILE_OK;
uma_stats->num_regular_files = 0;
uma_stats->num_hosted_documents = 0;
uma_stats->num_files_with_entry_kind.clear();
for (size_t i = 0; i < feed_list.size(); ++i) {
const DocumentFeed* feed = feed_list[i];
if (i == 0) {
const Link* root_feed_upload_link =
feed->GetLinkByType(Link::RESUMABLE_CREATE_MEDIA);
if (root_feed_upload_link)
directory_service_->root()->set_upload_url(
root_feed_upload_link->href());
*feed_changestamp = feed->largest_changestamp();
DCHECK_GE(*feed_changestamp, 0);
}
for (ScopedVector<DocumentEntry>::const_iterator iter =
feed->entries().begin();
iter != feed->entries().end(); ++iter) {
DocumentEntry* doc = *iter;
GDataEntry* entry = directory_service_->FromDocumentEntry(doc);
if (!entry)
continue;
GDataFile* as_file = entry->AsGDataFile();
if (as_file) {
if (as_file->is_hosted_document())
++uma_stats->num_hosted_documents;
else
++uma_stats->num_regular_files;
++uma_stats->num_files_with_entry_kind[as_file->kind()];
}
FileResourceIdMap::iterator map_entry =
file_map->find(entry->resource_id());
if (map_entry != file_map->end()) {
LOG(WARNING) << "Found duplicate file "
<< map_entry->second->base_name();
delete map_entry->second;
file_map->erase(map_entry);
}
file_map->insert(
std::pair<std::string, GDataEntry*>(entry->resource_id(), entry));
}
}
if (error != GDATA_FILE_OK) {
STLDeleteValues(file_map);
}
return error;
}
| 171,496 |
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 PrintWebViewHelper::UpdatePrintSettings(
const DictionaryValue& job_settings, bool is_preview) {
PrintMsg_PrintPages_Params settings;
Send(new PrintHostMsg_UpdatePrintSettings(routing_id(),
print_pages_params_->params.document_cookie, job_settings, &settings));
if (settings.params.dpi < kMinDpi || !settings.params.document_cookie) {
print_preview_context_.set_error(PREVIEW_ERROR_UPDATING_PRINT_SETTINGS);
return false;
}
if (is_preview) {
if (!job_settings.GetString(printing::kPreviewUIAddr,
&(settings.params.preview_ui_addr)) ||
!job_settings.GetInteger(printing::kPreviewRequestID,
&(settings.params.preview_request_id)) ||
!job_settings.GetBoolean(printing::kIsFirstRequest,
&(settings.params.is_first_request))) {
NOTREACHED();
print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
return false;
}
if (settings.params.is_first_request &&
!print_preview_context_.IsModifiable()) {
settings.params.display_header_footer = false;
}
PageSizeMargins default_page_layout;
GetPageSizeAndMarginsInPoints(NULL, -1, settings.params,
&default_page_layout);
if (!old_print_pages_params_.get() ||
!PageLayoutIsEqual(*old_print_pages_params_, settings)) {
Send(new PrintHostMsg_DidGetDefaultPageLayout(routing_id(),
default_page_layout));
}
SetCustomMarginsIfSelected(job_settings, &settings);
if (settings.params.display_header_footer) {
header_footer_info_.reset(new DictionaryValue());
header_footer_info_->SetString(printing::kSettingHeaderFooterDate,
settings.params.date);
header_footer_info_->SetString(printing::kSettingHeaderFooterURL,
settings.params.url);
header_footer_info_->SetString(printing::kSettingHeaderFooterTitle,
settings.params.title);
}
}
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
settings.params.document_cookie));
return true;
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool PrintWebViewHelper::UpdatePrintSettings(
const DictionaryValue& job_settings, bool is_preview) {
if (job_settings.empty()) {
if (is_preview)
print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
return false;
}
// Send the cookie so that UpdatePrintSettings can reuse PrinterQuery when
// possible.
int cookie = print_pages_params_.get() ?
print_pages_params_->params.document_cookie : 0;
PrintMsg_PrintPages_Params settings;
Send(new PrintHostMsg_UpdatePrintSettings(routing_id(),
cookie, job_settings, &settings));
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
if (PrintMsg_Print_Params_IsEmpty(settings.params)) {
if (is_preview) {
print_preview_context_.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS);
} else {
WebKit::WebFrame* frame = print_preview_context_.frame();
if (!frame) {
GetPrintFrame(&frame);
}
if (frame) {
render_view()->runModalAlertDialog(
frame,
l10n_util::GetStringUTF16(
IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS));
}
}
return false;
}
if (settings.params.dpi < kMinDpi || !settings.params.document_cookie) {
print_preview_context_.set_error(PREVIEW_ERROR_UPDATING_PRINT_SETTINGS);
return false;
}
if (is_preview) {
if (!job_settings.GetString(printing::kPreviewUIAddr,
&(settings.params.preview_ui_addr)) ||
!job_settings.GetInteger(printing::kPreviewRequestID,
&(settings.params.preview_request_id)) ||
!job_settings.GetBoolean(printing::kIsFirstRequest,
&(settings.params.is_first_request))) {
NOTREACHED();
print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
return false;
}
if (settings.params.is_first_request &&
!print_preview_context_.IsModifiable()) {
settings.params.display_header_footer = false;
}
PageSizeMargins default_page_layout;
GetPageSizeAndMarginsInPoints(NULL, -1, settings.params,
&default_page_layout);
if (!old_print_pages_params_.get() ||
!PageLayoutIsEqual(*old_print_pages_params_, settings)) {
Send(new PrintHostMsg_DidGetDefaultPageLayout(routing_id(),
default_page_layout));
}
SetCustomMarginsIfSelected(job_settings, &settings);
if (settings.params.display_header_footer) {
header_footer_info_.reset(new DictionaryValue());
header_footer_info_->SetString(printing::kSettingHeaderFooterDate,
settings.params.date);
header_footer_info_->SetString(printing::kSettingHeaderFooterURL,
settings.params.url);
header_footer_info_->SetString(printing::kSettingHeaderFooterTitle,
settings.params.title);
}
}
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
settings.params.document_cookie));
return true;
}
| 170,264 |
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: char *path_name(struct strbuf *path, const char *name)
{
struct strbuf ret = STRBUF_INIT;
if (path)
strbuf_addbuf(&ret, path);
strbuf_addstr(&ret, name);
return strbuf_detach(&ret, NULL);
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[email protected]>
CWE ID: CWE-119 | char *path_name(struct strbuf *path, const char *name)
void show_object_with_name(FILE *out, struct object *obj, const char *name)
{
| 167,426 |
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[])
{
opj_dinfo_t* dinfo;
opj_event_mgr_t event_mgr; /* event manager */
int tnum;
unsigned int snum;
opj_mj2_t *movie;
mj2_tk_t *track;
mj2_sample_t *sample;
unsigned char* frame_codestream;
FILE *file, *outfile;
char outfilename[50];
mj2_dparameters_t parameters;
if (argc != 3) {
printf("Usage: %s mj2filename output_location\n", argv[0]);
printf("Example: %s foreman.mj2 output/foreman\n", argv[0]);
return 1;
}
file = fopen(argv[1], "rb");
if (!file) {
fprintf(stderr, "failed to open %s for reading\n", argv[1]);
return 1;
}
/*
configure the event callbacks (not required)
setting of each callback is optional
*/
memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
event_mgr.error_handler = error_callback;
event_mgr.warning_handler = warning_callback;
event_mgr.info_handler = info_callback;
/* get a MJ2 decompressor handle */
dinfo = mj2_create_decompress();
/* catch events using our callbacks and give a local context */
opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
/* setup the decoder decoding parameters using user parameters */
memset(¶meters, 0, sizeof(mj2_dparameters_t));
movie = (opj_mj2_t*) dinfo->mj2_handle;
mj2_setup_decoder(movie, ¶meters);
if (mj2_read_struct(file, movie)) { /* Creating the movie structure*/
return 1;
}
/* Decode first video track */
tnum = 0;
while (movie->tk[tnum].track_type != 0) {
tnum ++;
}
track = &movie->tk[tnum];
fprintf(stdout, "Extracting %d frames from file...\n", track->num_samples);
for (snum = 0; snum < track->num_samples; snum++) {
sample = &track->sample[snum];
frame_codestream = (unsigned char*) malloc(sample->sample_size -
8); /* Skipping JP2C marker*/
fseek(file, sample->offset + 8, SEEK_SET);
fread(frame_codestream, sample->sample_size - 8, 1,
file); /* Assuming that jp and ftyp markers size do*/
sprintf(outfilename, "%s_%05d.j2k", argv[2], snum);
outfile = fopen(outfilename, "wb");
if (!outfile) {
fprintf(stderr, "failed to open %s for writing\n", outfilename);
return 1;
}
fwrite(frame_codestream, sample->sample_size - 8, 1, outfile);
fclose(outfile);
free(frame_codestream);
}
fclose(file);
fprintf(stdout, "%d frames correctly extracted\n", snum);
/* free remaining structures */
if (dinfo) {
mj2_destroy_decompress((opj_mj2_t*)dinfo->mj2_handle);
}
return 0;
}
Commit Message: opj_mj2_extract: Check provided output prefix for length
This uses snprintf() with correct buffer length instead of sprintf(). This
prevents a buffer overflow when providing a long output prefix. Furthermore
the program exits with an error when the provided output prefix is too long.
Fixes #1088.
CWE ID: CWE-119 | int main(int argc, char *argv[])
{
opj_dinfo_t* dinfo;
opj_event_mgr_t event_mgr; /* event manager */
int tnum;
unsigned int snum;
opj_mj2_t *movie;
mj2_tk_t *track;
mj2_sample_t *sample;
unsigned char* frame_codestream;
FILE *file, *outfile;
char outfilename[50];
mj2_dparameters_t parameters;
if (argc != 3) {
printf("Usage: %s mj2filename output_location\n", argv[0]);
printf("Example: %s foreman.mj2 output/foreman\n", argv[0]);
return 1;
}
file = fopen(argv[1], "rb");
if (!file) {
fprintf(stderr, "failed to open %s for reading\n", argv[1]);
return 1;
}
/*
configure the event callbacks (not required)
setting of each callback is optional
*/
memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
event_mgr.error_handler = error_callback;
event_mgr.warning_handler = warning_callback;
event_mgr.info_handler = info_callback;
/* get a MJ2 decompressor handle */
dinfo = mj2_create_decompress();
/* catch events using our callbacks and give a local context */
opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
/* setup the decoder decoding parameters using user parameters */
memset(¶meters, 0, sizeof(mj2_dparameters_t));
movie = (opj_mj2_t*) dinfo->mj2_handle;
mj2_setup_decoder(movie, ¶meters);
if (mj2_read_struct(file, movie)) { /* Creating the movie structure*/
return 1;
}
/* Decode first video track */
tnum = 0;
while (movie->tk[tnum].track_type != 0) {
tnum ++;
}
track = &movie->tk[tnum];
fprintf(stdout, "Extracting %d frames from file...\n", track->num_samples);
for (snum = 0; snum < track->num_samples; snum++) {
sample = &track->sample[snum];
frame_codestream = (unsigned char*) malloc(sample->sample_size -
8); /* Skipping JP2C marker*/
fseek(file, sample->offset + 8, SEEK_SET);
fread(frame_codestream, sample->sample_size - 8, 1,
file); /* Assuming that jp and ftyp markers size do*/
int num = snprintf(outfilename, sizeof(outfilename), "%s_%05d.j2k", argv[2], snum);
if (num >= sizeof(outfilename)) {
fprintf(stderr, "maximum length of output prefix exceeded\n");
return 1;
}
outfile = fopen(outfilename, "wb");
if (!outfile) {
fprintf(stderr, "failed to open %s for writing\n", outfilename);
return 1;
}
fwrite(frame_codestream, sample->sample_size - 8, 1, outfile);
fclose(outfile);
free(frame_codestream);
}
fclose(file);
fprintf(stdout, "%d frames correctly extracted\n", snum);
/* free remaining structures */
if (dinfo) {
mj2_destroy_decompress((opj_mj2_t*)dinfo->mj2_handle);
}
return 0;
}
| 169,307 |
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 XMLHttpRequest::didFail(const ResourceError& error)
{
if (m_error)
return;
if (error.isCancellation()) {
m_exceptionCode = AbortError;
abortError();
return;
}
if (error.isTimeout()) {
didTimeout();
return;
}
if (error.domain() == errorDomainWebKitInternal)
logConsoleError(scriptExecutionContext(), "XMLHttpRequest cannot load " + error.failingURL() + ". " + error.localizedDescription());
m_exceptionCode = NetworkError;
networkError();
}
Commit Message: Don't dispatch events when XHR is set to sync mode
Any of readystatechange, progress, abort, error, timeout and loadend
event are not specified to be dispatched in sync mode in the latest
spec. Just an exception corresponding to the failure is thrown.
Clean up for readability done in this CL
- factor out dispatchEventAndLoadEnd calling code
- make didTimeout() private
- give error handling methods more descriptive names
- set m_exceptionCode in failure type specific methods
-- Note that for didFailRedirectCheck, m_exceptionCode was not set
in networkError(), but was set at the end of createRequest()
This CL is prep for fixing crbug.com/292422
BUG=292422
Review URL: https://chromiumcodereview.appspot.com/24225002
git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void XMLHttpRequest::didFail(const ResourceError& error)
{
if (m_error)
return;
if (error.isCancellation()) {
handleDidCancel();
return;
}
if (error.isTimeout()) {
handleDidTimeout();
return;
}
if (error.domain() == errorDomainWebKitInternal)
logConsoleError(scriptExecutionContext(), "XMLHttpRequest cannot load " + error.failingURL() + ". " + error.localizedDescription());
handleNetworkError();
}
| 171,165 |
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 ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
ssize_t size, void *private)
{
ext4_io_end_t *io_end = iocb->private;
struct workqueue_struct *wq;
/* if not async direct IO or dio with 0 bytes write, just return */
if (!io_end || !size)
return;
ext_debug("ext4_end_io_dio(): io_end 0x%p"
"for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
iocb->private, io_end->inode->i_ino, iocb, offset,
size);
/* if not aio dio with unwritten extents, just free io and return */
if (io_end->flag != EXT4_IO_UNWRITTEN){
ext4_free_io_end(io_end);
iocb->private = NULL;
return;
}
io_end->offset = offset;
io_end->size = size;
wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
/* queue the work to convert unwritten extents to written */
queue_work(wq, &io_end->work);
/* Add the io_end to per-inode completed aio dio list*/
list_add_tail(&io_end->list,
&EXT4_I(io_end->inode)->i_completed_io_list);
iocb->private = NULL;
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID: | static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
ssize_t size, void *private)
{
ext4_io_end_t *io_end = iocb->private;
struct workqueue_struct *wq;
unsigned long flags;
struct ext4_inode_info *ei;
/* if not async direct IO or dio with 0 bytes write, just return */
if (!io_end || !size)
return;
ext_debug("ext4_end_io_dio(): io_end 0x%p"
"for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
iocb->private, io_end->inode->i_ino, iocb, offset,
size);
/* if not aio dio with unwritten extents, just free io and return */
if (io_end->flag != EXT4_IO_UNWRITTEN){
ext4_free_io_end(io_end);
iocb->private = NULL;
return;
}
io_end->offset = offset;
io_end->size = size;
io_end->flag = EXT4_IO_UNWRITTEN;
wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
/* queue the work to convert unwritten extents to written */
queue_work(wq, &io_end->work);
/* Add the io_end to per-inode completed aio dio list*/
ei = EXT4_I(io_end->inode);
spin_lock_irqsave(&ei->i_completed_io_lock, flags);
list_add_tail(&io_end->list, &ei->i_completed_io_list);
spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
iocb->private = NULL;
}
| 167,540 |
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: sg_fill_request_table(Sg_fd *sfp, sg_req_info_t *rinfo)
{
Sg_request *srp;
int val;
unsigned int ms;
val = 0;
list_for_each_entry(srp, &sfp->rq_list, entry) {
if (val > SG_MAX_QUEUE)
break;
memset(&rinfo[val], 0, SZ_SG_REQ_INFO);
rinfo[val].req_state = srp->done + 1;
rinfo[val].problem =
srp->header.masked_status &
srp->header.host_status &
srp->header.driver_status;
if (srp->done)
rinfo[val].duration =
srp->header.duration;
else {
ms = jiffies_to_msecs(jiffies);
rinfo[val].duration =
(ms > srp->header.duration) ?
(ms - srp->header.duration) : 0;
}
rinfo[val].orphan = srp->orphan;
rinfo[val].sg_io_owned = srp->sg_io_owned;
rinfo[val].pack_id = srp->header.pack_id;
rinfo[val].usr_ptr = srp->header.usr_ptr;
val++;
}
}
Commit Message: scsi: sg: fixup infoleak when using SG_GET_REQUEST_TABLE
When calling SG_GET_REQUEST_TABLE ioctl only a half-filled table is
returned; the remaining part will then contain stale kernel memory
information. This patch zeroes out the entire table to avoid this
issue.
Signed-off-by: Hannes Reinecke <[email protected]>
Reviewed-by: Bart Van Assche <[email protected]>
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Eric Dumazet <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID: CWE-200 | sg_fill_request_table(Sg_fd *sfp, sg_req_info_t *rinfo)
{
Sg_request *srp;
int val;
unsigned int ms;
val = 0;
list_for_each_entry(srp, &sfp->rq_list, entry) {
if (val > SG_MAX_QUEUE)
break;
rinfo[val].req_state = srp->done + 1;
rinfo[val].problem =
srp->header.masked_status &
srp->header.host_status &
srp->header.driver_status;
if (srp->done)
rinfo[val].duration =
srp->header.duration;
else {
ms = jiffies_to_msecs(jiffies);
rinfo[val].duration =
(ms > srp->header.duration) ?
(ms - srp->header.duration) : 0;
}
rinfo[val].orphan = srp->orphan;
rinfo[val].sg_io_owned = srp->sg_io_owned;
rinfo[val].pack_id = srp->header.pack_id;
rinfo[val].usr_ptr = srp->header.usr_ptr;
val++;
}
}
| 167,740 |
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: ImageBitmapFactories::ImageBitmapLoader::ImageBitmapLoader(
ImageBitmapFactories& factory,
base::Optional<IntRect> crop_rect,
ScriptState* script_state,
const ImageBitmapOptions* options)
: loader_(
FileReaderLoader::Create(FileReaderLoader::kReadAsArrayBuffer, this)),
factory_(&factory),
resolver_(ScriptPromiseResolver::Create(script_state)),
crop_rect_(crop_rect),
options_(options) {}
Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader
FileReaderLoader stores its client as a raw pointer, so in cases like
ImageBitmapLoader where the FileReaderLoaderClient really is garbage
collected we have to make sure to destroy the FileReaderLoader when
the ExecutionContext that owns it is destroyed.
Bug: 913970
Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861
Reviewed-on: https://chromium-review.googlesource.com/c/1374511
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Marijn Kruisselbrink <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616342}
CWE ID: CWE-416 | ImageBitmapFactories::ImageBitmapLoader::ImageBitmapLoader(
ImageBitmapFactories& factory,
base::Optional<IntRect> crop_rect,
ScriptState* script_state,
const ImageBitmapOptions* options)
: ContextLifecycleObserver(ExecutionContext::From(script_state)),
loader_(
FileReaderLoader::Create(FileReaderLoader::kReadAsArrayBuffer, this)),
factory_(&factory),
resolver_(ScriptPromiseResolver::Create(script_state)),
crop_rect_(crop_rect),
options_(options) {}
| 173,067 |
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 set_geometry(unsigned int cmd, struct floppy_struct *g,
int drive, int type, struct block_device *bdev)
{
int cnt;
/* sanity checking for parameters. */
if (g->sect <= 0 ||
g->head <= 0 ||
/* check for zero in F_SECT_PER_TRACK */
(unsigned char)((g->sect << 2) >> FD_SIZECODE(g)) == 0 ||
g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||
/* check if reserved bits are set */
(g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)
return -EINVAL;
if (type) {
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
mutex_lock(&open_lock);
if (lock_fdc(drive)) {
mutex_unlock(&open_lock);
return -EINTR;
}
floppy_type[type] = *g;
floppy_type[type].name = "user format";
for (cnt = type << 2; cnt < (type << 2) + 4; cnt++)
floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =
floppy_type[type].size + 1;
process_fd_request();
for (cnt = 0; cnt < N_DRIVE; cnt++) {
struct block_device *bdev = opened_bdev[cnt];
if (!bdev || ITYPE(drive_state[cnt].fd_device) != type)
continue;
__invalidate_device(bdev, true);
}
mutex_unlock(&open_lock);
} else {
int oldStretch;
if (lock_fdc(drive))
return -EINTR;
if (cmd != FDDEFPRM) {
/* notice a disk change immediately, else
* we lose our settings immediately*/
if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
return -EINTR;
}
oldStretch = g->stretch;
user_params[drive] = *g;
if (buffer_drive == drive)
SUPBOUND(buffer_max, user_params[drive].sect);
current_type[drive] = &user_params[drive];
floppy_sizes[drive] = user_params[drive].size;
if (cmd == FDDEFPRM)
DRS->keep_data = -1;
else
DRS->keep_data = 1;
/* invalidation. Invalidate only when needed, i.e.
* when there are already sectors in the buffer cache
* whose number will change. This is useful, because
* mtools often changes the geometry of the disk after
* looking at the boot block */
if (DRS->maxblock > user_params[drive].sect ||
DRS->maxtrack ||
((user_params[drive].sect ^ oldStretch) &
(FD_SWAPSIDES | FD_SECTBASEMASK)))
invalidate_drive(bdev);
else
process_fd_request();
}
return 0;
}
Commit Message: floppy: fix out-of-bounds read in copy_buffer
This fixes a global out-of-bounds read access in the copy_buffer
function of the floppy driver.
The FDDEFPRM ioctl allows one to set the geometry of a disk. The sect
and head fields (unsigned int) of the floppy_drive structure are used to
compute the max_sector (int) in the make_raw_rw_request function. It is
possible to overflow the max_sector. Next, max_sector is passed to the
copy_buffer function and used in one of the memcpy calls.
An unprivileged user could trigger the bug if the device is accessible,
but requires a floppy disk to be inserted.
The patch adds the check for the .sect * .head multiplication for not
overflowing in the set_geometry function.
The bug was found by syzkaller.
Signed-off-by: Denis Efremov <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-125 | static int set_geometry(unsigned int cmd, struct floppy_struct *g,
int drive, int type, struct block_device *bdev)
{
int cnt;
/* sanity checking for parameters. */
if ((int)g->sect <= 0 ||
(int)g->head <= 0 ||
/* check for overflow in max_sector */
(int)(g->sect * g->head) <= 0 ||
/* check for zero in F_SECT_PER_TRACK */
(unsigned char)((g->sect << 2) >> FD_SIZECODE(g)) == 0 ||
g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||
/* check if reserved bits are set */
(g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)
return -EINVAL;
if (type) {
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
mutex_lock(&open_lock);
if (lock_fdc(drive)) {
mutex_unlock(&open_lock);
return -EINTR;
}
floppy_type[type] = *g;
floppy_type[type].name = "user format";
for (cnt = type << 2; cnt < (type << 2) + 4; cnt++)
floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =
floppy_type[type].size + 1;
process_fd_request();
for (cnt = 0; cnt < N_DRIVE; cnt++) {
struct block_device *bdev = opened_bdev[cnt];
if (!bdev || ITYPE(drive_state[cnt].fd_device) != type)
continue;
__invalidate_device(bdev, true);
}
mutex_unlock(&open_lock);
} else {
int oldStretch;
if (lock_fdc(drive))
return -EINTR;
if (cmd != FDDEFPRM) {
/* notice a disk change immediately, else
* we lose our settings immediately*/
if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
return -EINTR;
}
oldStretch = g->stretch;
user_params[drive] = *g;
if (buffer_drive == drive)
SUPBOUND(buffer_max, user_params[drive].sect);
current_type[drive] = &user_params[drive];
floppy_sizes[drive] = user_params[drive].size;
if (cmd == FDDEFPRM)
DRS->keep_data = -1;
else
DRS->keep_data = 1;
/* invalidation. Invalidate only when needed, i.e.
* when there are already sectors in the buffer cache
* whose number will change. This is useful, because
* mtools often changes the geometry of the disk after
* looking at the boot block */
if (DRS->maxblock > user_params[drive].sect ||
DRS->maxtrack ||
((user_params[drive].sect ^ oldStretch) &
(FD_SWAPSIDES | FD_SECTBASEMASK)))
invalidate_drive(bdev);
else
process_fd_request();
}
return 0;
}
| 169,587 |
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 PageSerializer::addImageToResources(ImageResource* image, RenderObject* imageRenderer, const KURL& url)
{
if (!shouldAddURL(url))
return;
if (!image || !image->hasImage() || image->image() == Image::nullImage())
return;
RefPtr<SharedBuffer> data = imageRenderer ? image->imageForRenderer(imageRenderer)->data() : 0;
if (!data)
data = image->image()->data();
addToResources(image, data, url);
}
Commit Message: Revert 162155 "This review merges the two existing page serializ..."
Change r162155 broke the world even though it was landed using the CQ.
> This review merges the two existing page serializers, WebPageSerializerImpl and
> PageSerializer, into one, PageSerializer. In addition to this it moves all
> the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the
> PageSerializerTest structure and splits out one test for MHTML into a new
> MHTMLTest file.
>
> Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the
> 'Save Page as MHTML' flag is enabled now uses the same code, and should thus
> have the same feature set. Meaning that both modes now should be a bit better.
>
> Detailed list of changes:
>
> - PageSerializerTest: Prepare for more DTD test
> - PageSerializerTest: Remove now unneccesary input image test
> - PageSerializerTest: Remove unused WebPageSerializer/Impl code
> - PageSerializerTest: Move data URI morph test
> - PageSerializerTest: Move data URI test
> - PageSerializerTest: Move namespace test
> - PageSerializerTest: Move SVG Image test
> - MHTMLTest: Move MHTML specific test to own test file
> - PageSerializerTest: Delete duplicate XML header test
> - PageSerializerTest: Move blank frame test
> - PageSerializerTest: Move CSS test
> - PageSerializerTest: Add frameset/frame test
> - PageSerializerTest: Move old iframe test
> - PageSerializerTest: Move old elements test
> - Use PageSerizer for saving web pages
> - PageSerializerTest: Test for rewriting links
> - PageSerializer: Add rewrite link accumulator
> - PageSerializer: Serialize images in iframes/frames src
> - PageSerializer: XHTML fix for meta tags
> - PageSerializer: Add presentation CSS
> - PageSerializer: Rename out parameter
>
> BUG=
> [email protected]
>
> Review URL: https://codereview.chromium.org/68613003
[email protected]
Review URL: https://codereview.chromium.org/73673003
git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void PageSerializer::addImageToResources(ImageResource* image, RenderObject* imageRenderer, const KURL& url)
{
if (!shouldAddURL(url))
return;
if (!image || image->image() == Image::nullImage())
return;
RefPtr<SharedBuffer> data = imageRenderer ? image->imageForRenderer(imageRenderer)->data() : 0;
if (!data)
data = image->image()->data();
addToResources(image, data, url);
}
| 171,564 |
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 long AudioTrack::GetChannels() const
{
return m_channels;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long AudioTrack::GetChannels() const
Track** i = m_trackEntries;
Track** const j = m_trackEntriesEnd;
while (i != j) {
Track* const pTrack = *i++;
if (pTrack == NULL)
continue;
if (tn == pTrack->GetNumber())
return pTrack;
}
return NULL; // not found
}
| 174,289 |
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 *atomic_thread_inc_dec(void *context) {
struct atomic_test_s32_s *at = (struct atomic_test_s32_s *)context;
for (int i = 0; i < at->max_val; i++) {
usleep(1);
atomic_inc_prefix_s32(&at->data[i]);
usleep(1);
atomic_dec_prefix_s32(&at->data[i]);
}
return NULL;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | void *atomic_thread_inc_dec(void *context) {
struct atomic_test_s32_s *at = (struct atomic_test_s32_s *)context;
for (int i = 0; i < at->max_val; i++) {
TEMP_FAILURE_RETRY(usleep(1));
atomic_inc_prefix_s32(&at->data[i]);
TEMP_FAILURE_RETRY(usleep(1));
atomic_dec_prefix_s32(&at->data[i]);
}
return NULL;
}
| 173,491 |
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: asmlinkage int arm_syscall(int no, struct pt_regs *regs)
{
struct thread_info *thread = current_thread_info();
siginfo_t info;
if ((no >> 16) != (__ARM_NR_BASE>> 16))
return bad_syscall(no, regs);
switch (no & 0xffff) {
case 0: /* branch through 0 */
info.si_signo = SIGSEGV;
info.si_errno = 0;
info.si_code = SEGV_MAPERR;
info.si_addr = NULL;
arm_notify_die("branch through zero", regs, &info, 0, 0);
return 0;
case NR(breakpoint): /* SWI BREAK_POINT */
regs->ARM_pc -= thumb_mode(regs) ? 2 : 4;
ptrace_break(current, regs);
return regs->ARM_r0;
/*
* Flush a region from virtual address 'r0' to virtual address 'r1'
* _exclusive_. There is no alignment requirement on either address;
* user space does not need to know the hardware cache layout.
*
* r2 contains flags. It should ALWAYS be passed as ZERO until it
* is defined to be something else. For now we ignore it, but may
* the fires of hell burn in your belly if you break this rule. ;)
*
* (at a later date, we may want to allow this call to not flush
* various aspects of the cache. Passing '0' will guarantee that
* everything necessary gets flushed to maintain consistency in
* the specified region).
*/
case NR(cacheflush):
return do_cache_op(regs->ARM_r0, regs->ARM_r1, regs->ARM_r2);
case NR(usr26):
if (!(elf_hwcap & HWCAP_26BIT))
break;
regs->ARM_cpsr &= ~MODE32_BIT;
return regs->ARM_r0;
case NR(usr32):
if (!(elf_hwcap & HWCAP_26BIT))
break;
regs->ARM_cpsr |= MODE32_BIT;
return regs->ARM_r0;
case NR(set_tls):
thread->tp_value = regs->ARM_r0;
if (tls_emu)
return 0;
if (has_tls_reg) {
asm ("mcr p15, 0, %0, c13, c0, 3"
: : "r" (regs->ARM_r0));
} else {
/*
* User space must never try to access this directly.
* Expect your app to break eventually if you do so.
* The user helper at 0xffff0fe0 must be used instead.
* (see entry-armv.S for details)
*/
*((unsigned int *)0xffff0ff0) = regs->ARM_r0;
}
return 0;
#ifdef CONFIG_NEEDS_SYSCALL_FOR_CMPXCHG
/*
* Atomically store r1 in *r2 if *r2 is equal to r0 for user space.
* Return zero in r0 if *MEM was changed or non-zero if no exchange
* happened. Also set the user C flag accordingly.
* If access permissions have to be fixed up then non-zero is
* returned and the operation has to be re-attempted.
*
* *NOTE*: This is a ghost syscall private to the kernel. Only the
* __kuser_cmpxchg code in entry-armv.S should be aware of its
* existence. Don't ever use this from user code.
*/
case NR(cmpxchg):
for (;;) {
extern void do_DataAbort(unsigned long addr, unsigned int fsr,
struct pt_regs *regs);
unsigned long val;
unsigned long addr = regs->ARM_r2;
struct mm_struct *mm = current->mm;
pgd_t *pgd; pmd_t *pmd; pte_t *pte;
spinlock_t *ptl;
regs->ARM_cpsr &= ~PSR_C_BIT;
down_read(&mm->mmap_sem);
pgd = pgd_offset(mm, addr);
if (!pgd_present(*pgd))
goto bad_access;
pmd = pmd_offset(pgd, addr);
if (!pmd_present(*pmd))
goto bad_access;
pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
if (!pte_present(*pte) || !pte_write(*pte) || !pte_dirty(*pte)) {
pte_unmap_unlock(pte, ptl);
goto bad_access;
}
val = *(unsigned long *)addr;
val -= regs->ARM_r0;
if (val == 0) {
*(unsigned long *)addr = regs->ARM_r1;
regs->ARM_cpsr |= PSR_C_BIT;
}
pte_unmap_unlock(pte, ptl);
up_read(&mm->mmap_sem);
return val;
bad_access:
up_read(&mm->mmap_sem);
/* simulate a write access fault */
do_DataAbort(addr, 15 + (1 << 11), regs);
}
#endif
default:
/* Calls 9f00xx..9f07ff are defined to return -ENOSYS
if not implemented, rather than raising SIGILL. This
way the calling program can gracefully determine whether
a feature is supported. */
if ((no & 0xffff) <= 0x7ff)
return -ENOSYS;
break;
}
#ifdef CONFIG_DEBUG_USER
/*
* experience shows that these seem to indicate that
* something catastrophic has happened
*/
if (user_debug & UDBG_SYSCALL) {
printk("[%d] %s: arm syscall %d\n",
task_pid_nr(current), current->comm, no);
dump_instr("", regs);
if (user_mode(regs)) {
__show_regs(regs);
c_backtrace(regs->ARM_fp, processor_mode(regs));
}
}
#endif
info.si_signo = SIGILL;
info.si_errno = 0;
info.si_code = ILL_ILLTRP;
info.si_addr = (void __user *)instruction_pointer(regs) -
(thumb_mode(regs) ? 2 : 4);
arm_notify_die("Oops - bad syscall(2)", regs, &info, no, 0);
return 0;
}
Commit Message: ARM: 7735/2: Preserve the user r/w register TPIDRURW on context switch and fork
Since commit 6a1c53124aa1 the user writeable TLS register was zeroed to
prevent it from being used as a covert channel between two tasks.
There are more and more applications coming to Windows RT,
Wine could support them, but mostly they expect to have
the thread environment block (TEB) in TPIDRURW.
This patch preserves that register per thread instead of clearing it.
Unlike the TPIDRURO, which is already switched, the TPIDRURW
can be updated from userspace so needs careful treatment in the case that we
modify TPIDRURW and call fork(). To avoid this we must always read
TPIDRURW in copy_thread.
Signed-off-by: André Hentschel <[email protected]>
Signed-off-by: Will Deacon <[email protected]>
Signed-off-by: Jonathan Austin <[email protected]>
Signed-off-by: Russell King <[email protected]>
CWE ID: CWE-264 | asmlinkage int arm_syscall(int no, struct pt_regs *regs)
{
struct thread_info *thread = current_thread_info();
siginfo_t info;
if ((no >> 16) != (__ARM_NR_BASE>> 16))
return bad_syscall(no, regs);
switch (no & 0xffff) {
case 0: /* branch through 0 */
info.si_signo = SIGSEGV;
info.si_errno = 0;
info.si_code = SEGV_MAPERR;
info.si_addr = NULL;
arm_notify_die("branch through zero", regs, &info, 0, 0);
return 0;
case NR(breakpoint): /* SWI BREAK_POINT */
regs->ARM_pc -= thumb_mode(regs) ? 2 : 4;
ptrace_break(current, regs);
return regs->ARM_r0;
/*
* Flush a region from virtual address 'r0' to virtual address 'r1'
* _exclusive_. There is no alignment requirement on either address;
* user space does not need to know the hardware cache layout.
*
* r2 contains flags. It should ALWAYS be passed as ZERO until it
* is defined to be something else. For now we ignore it, but may
* the fires of hell burn in your belly if you break this rule. ;)
*
* (at a later date, we may want to allow this call to not flush
* various aspects of the cache. Passing '0' will guarantee that
* everything necessary gets flushed to maintain consistency in
* the specified region).
*/
case NR(cacheflush):
return do_cache_op(regs->ARM_r0, regs->ARM_r1, regs->ARM_r2);
case NR(usr26):
if (!(elf_hwcap & HWCAP_26BIT))
break;
regs->ARM_cpsr &= ~MODE32_BIT;
return regs->ARM_r0;
case NR(usr32):
if (!(elf_hwcap & HWCAP_26BIT))
break;
regs->ARM_cpsr |= MODE32_BIT;
return regs->ARM_r0;
case NR(set_tls):
thread->tp_value[0] = regs->ARM_r0;
if (tls_emu)
return 0;
if (has_tls_reg) {
asm ("mcr p15, 0, %0, c13, c0, 3"
: : "r" (regs->ARM_r0));
} else {
/*
* User space must never try to access this directly.
* Expect your app to break eventually if you do so.
* The user helper at 0xffff0fe0 must be used instead.
* (see entry-armv.S for details)
*/
*((unsigned int *)0xffff0ff0) = regs->ARM_r0;
}
return 0;
#ifdef CONFIG_NEEDS_SYSCALL_FOR_CMPXCHG
/*
* Atomically store r1 in *r2 if *r2 is equal to r0 for user space.
* Return zero in r0 if *MEM was changed or non-zero if no exchange
* happened. Also set the user C flag accordingly.
* If access permissions have to be fixed up then non-zero is
* returned and the operation has to be re-attempted.
*
* *NOTE*: This is a ghost syscall private to the kernel. Only the
* __kuser_cmpxchg code in entry-armv.S should be aware of its
* existence. Don't ever use this from user code.
*/
case NR(cmpxchg):
for (;;) {
extern void do_DataAbort(unsigned long addr, unsigned int fsr,
struct pt_regs *regs);
unsigned long val;
unsigned long addr = regs->ARM_r2;
struct mm_struct *mm = current->mm;
pgd_t *pgd; pmd_t *pmd; pte_t *pte;
spinlock_t *ptl;
regs->ARM_cpsr &= ~PSR_C_BIT;
down_read(&mm->mmap_sem);
pgd = pgd_offset(mm, addr);
if (!pgd_present(*pgd))
goto bad_access;
pmd = pmd_offset(pgd, addr);
if (!pmd_present(*pmd))
goto bad_access;
pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
if (!pte_present(*pte) || !pte_write(*pte) || !pte_dirty(*pte)) {
pte_unmap_unlock(pte, ptl);
goto bad_access;
}
val = *(unsigned long *)addr;
val -= regs->ARM_r0;
if (val == 0) {
*(unsigned long *)addr = regs->ARM_r1;
regs->ARM_cpsr |= PSR_C_BIT;
}
pte_unmap_unlock(pte, ptl);
up_read(&mm->mmap_sem);
return val;
bad_access:
up_read(&mm->mmap_sem);
/* simulate a write access fault */
do_DataAbort(addr, 15 + (1 << 11), regs);
}
#endif
default:
/* Calls 9f00xx..9f07ff are defined to return -ENOSYS
if not implemented, rather than raising SIGILL. This
way the calling program can gracefully determine whether
a feature is supported. */
if ((no & 0xffff) <= 0x7ff)
return -ENOSYS;
break;
}
#ifdef CONFIG_DEBUG_USER
/*
* experience shows that these seem to indicate that
* something catastrophic has happened
*/
if (user_debug & UDBG_SYSCALL) {
printk("[%d] %s: arm syscall %d\n",
task_pid_nr(current), current->comm, no);
dump_instr("", regs);
if (user_mode(regs)) {
__show_regs(regs);
c_backtrace(regs->ARM_fp, processor_mode(regs));
}
}
#endif
info.si_signo = SIGILL;
info.si_errno = 0;
info.si_code = ILL_ILLTRP;
info.si_addr = (void __user *)instruction_pointer(regs) -
(thumb_mode(regs) ? 2 : 4);
arm_notify_die("Oops - bad syscall(2)", regs, &info, no, 0);
return 0;
}
| 167,581 |
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 RenderLayerCompositor::frameViewDidScroll()
{
FrameView* frameView = m_renderView->frameView();
IntPoint scrollPosition = frameView->scrollPosition();
if (!m_scrollLayer)
return;
bool scrollingCoordinatorHandlesOffset = false;
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator()) {
if (Settings* settings = m_renderView->document().settings()) {
if (isMainFrame() || settings->compositedScrollingForFramesEnabled())
scrollingCoordinatorHandlesOffset = scrollingCoordinator->scrollableAreaScrollLayerDidChange(frameView);
}
}
if (scrollingCoordinatorHandlesOffset)
m_scrollLayer->setPosition(-frameView->minimumScrollPosition());
else
m_scrollLayer->setPosition(-scrollPosition);
blink::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
ScrolledMainFrameBucket,
AcceleratedFixedRootBackgroundHistogramMax);
if (!m_renderView->rootBackgroundIsEntirelyFixed())
return;
blink::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
!!fixedRootBackgroundLayer()
? ScrolledMainFrameWithAcceleratedFixedRootBackground
: ScrolledMainFrameWithUnacceleratedFixedRootBackground,
AcceleratedFixedRootBackgroundHistogramMax);
}
Commit Message: Disable some more query compositingState asserts.
This gets the tests passing again on Mac. See the bug for the stacktrace.
A future patch will need to actually fix the incorrect reading of
compositingState.
BUG=343179
Review URL: https://codereview.chromium.org/162153002
git-svn-id: svn://svn.chromium.org/blink/trunk@167069 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | void RenderLayerCompositor::frameViewDidScroll()
{
FrameView* frameView = m_renderView->frameView();
IntPoint scrollPosition = frameView->scrollPosition();
if (!m_scrollLayer)
return;
bool scrollingCoordinatorHandlesOffset = false;
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator()) {
if (Settings* settings = m_renderView->document().settings()) {
if (isMainFrame() || settings->compositedScrollingForFramesEnabled())
scrollingCoordinatorHandlesOffset = scrollingCoordinator->scrollableAreaScrollLayerDidChange(frameView);
}
}
if (scrollingCoordinatorHandlesOffset)
m_scrollLayer->setPosition(-frameView->minimumScrollPosition());
else
m_scrollLayer->setPosition(-scrollPosition);
blink::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
ScrolledMainFrameBucket,
AcceleratedFixedRootBackgroundHistogramMax);
if (!m_renderView->rootBackgroundIsEntirelyFixed())
return;
// FIXME: fixedRootBackgroundLayer calls compositingState, which is not necessarily up to date here on mac.
// See crbug.com/343179.
DisableCompositingQueryAsserts disabler;
blink::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
!!fixedRootBackgroundLayer()
? ScrolledMainFrameWithAcceleratedFixedRootBackground
: ScrolledMainFrameWithUnacceleratedFixedRootBackground,
AcceleratedFixedRootBackgroundHistogramMax);
}
| 171,342 |
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 __init int seqgen_init(void)
{
rekey_seq_generator(NULL);
return 0;
}
Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5.
Computers have become a lot faster since we compromised on the
partial MD4 hash which we use currently for performance reasons.
MD5 is a much safer choice, and is inline with both RFC1948 and
other ISS generators (OpenBSD, Solaris, etc.)
Furthermore, only having 24-bits of the sequence number be truly
unpredictable is a very serious limitation. So the periodic
regeneration and 8-bit counter have been removed. We compute and
use a full 32-bit sequence number.
For ipv6, DCCP was found to use a 32-bit truncated initial sequence
number (it needs 43-bits) and that is fixed here as well.
Reported-by: Dan Kaminsky <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static __init int seqgen_init(void)
get_random_bytes(random_int_secret, sizeof(random_int_secret));
return 0;
}
| 165,770 |
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 process_one_ticket(struct ceph_auth_client *ac,
struct ceph_crypto_key *secret,
void **p, void *end,
void *dbuf, void *ticket_buf)
{
struct ceph_x_info *xi = ac->private;
int type;
u8 tkt_struct_v, blob_struct_v;
struct ceph_x_ticket_handler *th;
void *dp, *dend;
int dlen;
char is_enc;
struct timespec validity;
struct ceph_crypto_key old_key;
void *tp, *tpend;
struct ceph_timespec new_validity;
struct ceph_crypto_key new_session_key;
struct ceph_buffer *new_ticket_blob;
unsigned long new_expires, new_renew_after;
u64 new_secret_id;
int ret;
ceph_decode_need(p, end, sizeof(u32) + 1, bad);
type = ceph_decode_32(p);
dout(" ticket type %d %s\n", type, ceph_entity_type_name(type));
tkt_struct_v = ceph_decode_8(p);
if (tkt_struct_v != 1)
goto bad;
th = get_ticket_handler(ac, type);
if (IS_ERR(th)) {
ret = PTR_ERR(th);
goto out;
}
/* blob for me */
dlen = ceph_x_decrypt(secret, p, end, dbuf,
TEMP_TICKET_BUF_LEN);
if (dlen <= 0) {
ret = dlen;
goto out;
}
dout(" decrypted %d bytes\n", dlen);
dp = dbuf;
dend = dp + dlen;
tkt_struct_v = ceph_decode_8(&dp);
if (tkt_struct_v != 1)
goto bad;
memcpy(&old_key, &th->session_key, sizeof(old_key));
ret = ceph_crypto_key_decode(&new_session_key, &dp, dend);
if (ret)
goto out;
ceph_decode_copy(&dp, &new_validity, sizeof(new_validity));
ceph_decode_timespec(&validity, &new_validity);
new_expires = get_seconds() + validity.tv_sec;
new_renew_after = new_expires - (validity.tv_sec / 4);
dout(" expires=%lu renew_after=%lu\n", new_expires,
new_renew_after);
/* ticket blob for service */
ceph_decode_8_safe(p, end, is_enc, bad);
tp = ticket_buf;
if (is_enc) {
/* encrypted */
dout(" encrypted ticket\n");
dlen = ceph_x_decrypt(&old_key, p, end, ticket_buf,
TEMP_TICKET_BUF_LEN);
if (dlen < 0) {
ret = dlen;
goto out;
}
dlen = ceph_decode_32(&tp);
} else {
/* unencrypted */
ceph_decode_32_safe(p, end, dlen, bad);
ceph_decode_need(p, end, dlen, bad);
ceph_decode_copy(p, ticket_buf, dlen);
}
tpend = tp + dlen;
dout(" ticket blob is %d bytes\n", dlen);
ceph_decode_need(&tp, tpend, 1 + sizeof(u64), bad);
blob_struct_v = ceph_decode_8(&tp);
new_secret_id = ceph_decode_64(&tp);
ret = ceph_decode_buffer(&new_ticket_blob, &tp, tpend);
if (ret)
goto out;
/* all is well, update our ticket */
ceph_crypto_key_destroy(&th->session_key);
if (th->ticket_blob)
ceph_buffer_put(th->ticket_blob);
th->session_key = new_session_key;
th->ticket_blob = new_ticket_blob;
th->validity = new_validity;
th->secret_id = new_secret_id;
th->expires = new_expires;
th->renew_after = new_renew_after;
dout(" got ticket service %d (%s) secret_id %lld len %d\n",
type, ceph_entity_type_name(type), th->secret_id,
(int)th->ticket_blob->vec.iov_len);
xi->have_keys |= th->service;
out:
return ret;
bad:
ret = -EINVAL;
goto out;
}
Commit Message: libceph: do not hard code max auth ticket len
We hard code cephx auth ticket buffer size to 256 bytes. This isn't
enough for any moderate setups and, in case tickets themselves are not
encrypted, leads to buffer overflows (ceph_x_decrypt() errors out, but
ceph_decode_copy() doesn't - it's just a memcpy() wrapper). Since the
buffer is allocated dynamically anyway, allocated it a bit later, at
the point where we know how much is going to be needed.
Fixes: http://tracker.ceph.com/issues/8979
Cc: [email protected]
Signed-off-by: Ilya Dryomov <[email protected]>
Reviewed-by: Sage Weil <[email protected]>
CWE ID: CWE-399 | static int process_one_ticket(struct ceph_auth_client *ac,
struct ceph_crypto_key *secret,
void **p, void *end)
{
struct ceph_x_info *xi = ac->private;
int type;
u8 tkt_struct_v, blob_struct_v;
struct ceph_x_ticket_handler *th;
void *dbuf = NULL;
void *dp, *dend;
int dlen;
char is_enc;
struct timespec validity;
struct ceph_crypto_key old_key;
void *ticket_buf = NULL;
void *tp, *tpend;
struct ceph_timespec new_validity;
struct ceph_crypto_key new_session_key;
struct ceph_buffer *new_ticket_blob;
unsigned long new_expires, new_renew_after;
u64 new_secret_id;
int ret;
ceph_decode_need(p, end, sizeof(u32) + 1, bad);
type = ceph_decode_32(p);
dout(" ticket type %d %s\n", type, ceph_entity_type_name(type));
tkt_struct_v = ceph_decode_8(p);
if (tkt_struct_v != 1)
goto bad;
th = get_ticket_handler(ac, type);
if (IS_ERR(th)) {
ret = PTR_ERR(th);
goto out;
}
/* blob for me */
dlen = ceph_x_decrypt(secret, p, end, &dbuf, 0);
if (dlen <= 0) {
ret = dlen;
goto out;
}
dout(" decrypted %d bytes\n", dlen);
dp = dbuf;
dend = dp + dlen;
tkt_struct_v = ceph_decode_8(&dp);
if (tkt_struct_v != 1)
goto bad;
memcpy(&old_key, &th->session_key, sizeof(old_key));
ret = ceph_crypto_key_decode(&new_session_key, &dp, dend);
if (ret)
goto out;
ceph_decode_copy(&dp, &new_validity, sizeof(new_validity));
ceph_decode_timespec(&validity, &new_validity);
new_expires = get_seconds() + validity.tv_sec;
new_renew_after = new_expires - (validity.tv_sec / 4);
dout(" expires=%lu renew_after=%lu\n", new_expires,
new_renew_after);
/* ticket blob for service */
ceph_decode_8_safe(p, end, is_enc, bad);
if (is_enc) {
/* encrypted */
dout(" encrypted ticket\n");
dlen = ceph_x_decrypt(&old_key, p, end, &ticket_buf, 0);
if (dlen < 0) {
ret = dlen;
goto out;
}
tp = ticket_buf;
dlen = ceph_decode_32(&tp);
} else {
/* unencrypted */
ceph_decode_32_safe(p, end, dlen, bad);
ticket_buf = kmalloc(dlen, GFP_NOFS);
if (!ticket_buf) {
ret = -ENOMEM;
goto out;
}
tp = ticket_buf;
ceph_decode_need(p, end, dlen, bad);
ceph_decode_copy(p, ticket_buf, dlen);
}
tpend = tp + dlen;
dout(" ticket blob is %d bytes\n", dlen);
ceph_decode_need(&tp, tpend, 1 + sizeof(u64), bad);
blob_struct_v = ceph_decode_8(&tp);
new_secret_id = ceph_decode_64(&tp);
ret = ceph_decode_buffer(&new_ticket_blob, &tp, tpend);
if (ret)
goto out;
/* all is well, update our ticket */
ceph_crypto_key_destroy(&th->session_key);
if (th->ticket_blob)
ceph_buffer_put(th->ticket_blob);
th->session_key = new_session_key;
th->ticket_blob = new_ticket_blob;
th->validity = new_validity;
th->secret_id = new_secret_id;
th->expires = new_expires;
th->renew_after = new_renew_after;
dout(" got ticket service %d (%s) secret_id %lld len %d\n",
type, ceph_entity_type_name(type), th->secret_id,
(int)th->ticket_blob->vec.iov_len);
xi->have_keys |= th->service;
out:
kfree(ticket_buf);
kfree(dbuf);
return ret;
bad:
ret = -EINVAL;
goto out;
}
| 166,265 |
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: mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir,
const unsigned char *s, uint32_t offset, size_t nbytes, size_t linecnt)
{
/*
* Note: FILE_SEARCH and FILE_REGEX do not actually copy
* anything, but setup pointers into the source
*/
if (indir == 0) {
switch (type) {
case FILE_SEARCH:
ms->search.s = RCAST(const char *, s) + offset;
ms->search.s_len = nbytes - offset;
ms->search.offset = offset;
return 0;
case FILE_REGEX: {
const char *b;
const char *c;
const char *last; /* end of search region */
const char *buf; /* start of search region */
const char *end;
size_t lines;
if (s == NULL) {
ms->search.s_len = 0;
ms->search.s = NULL;
return 0;
}
buf = RCAST(const char *, s) + offset;
end = last = RCAST(const char *, s) + nbytes;
/* mget() guarantees buf <= last */
for (lines = linecnt, b = buf; lines && b < end &&
((b = CAST(const char *,
memchr(c = b, '\n', CAST(size_t, (end - b)))))
|| (b = CAST(const char *,
memchr(c, '\r', CAST(size_t, (end - c))))));
lines--, b++) {
last = b;
if (b[0] == '\r' && b[1] == '\n')
b++;
}
if (lines)
last = RCAST(const char *, s) + nbytes;
ms->search.s = buf;
ms->search.s_len = last - buf;
ms->search.offset = offset;
ms->search.rm_len = 0;
return 0;
}
case FILE_BESTRING16:
case FILE_LESTRING16: {
const unsigned char *src = s + offset;
const unsigned char *esrc = s + nbytes;
char *dst = p->s;
char *edst = &p->s[sizeof(p->s) - 1];
if (type == FILE_BESTRING16)
src++;
/* check that offset is within range */
if (offset >= nbytes)
break;
for (/*EMPTY*/; src < esrc; src += 2, dst++) {
if (dst < edst)
*dst = *src;
else
break;
if (*dst == '\0') {
if (type == FILE_BESTRING16 ?
*(src - 1) != '\0' :
*(src + 1) != '\0')
*dst = ' ';
}
}
*edst = '\0';
return 0;
}
case FILE_STRING: /* XXX - these two should not need */
case FILE_PSTRING: /* to copy anything, but do anyway. */
default:
break;
}
}
if (offset >= nbytes) {
(void)memset(p, '\0', sizeof(*p));
return 0;
}
if (nbytes - offset < sizeof(*p))
nbytes = nbytes - offset;
else
nbytes = sizeof(*p);
(void)memcpy(p, s + offset, nbytes);
/*
* the usefulness of padding with zeroes eludes me, it
* might even cause problems
*/
if (nbytes < sizeof(*p))
(void)memset(((char *)(void *)p) + nbytes, '\0',
sizeof(*p) - nbytes);
return 0;
}
Commit Message: * Enforce limit of 8K on regex searches that have no limits
* Allow the l modifier for regex to mean line count. Default
to byte count. If line count is specified, assume a max
of 80 characters per line to limit the byte count.
* Don't allow conversions to be used for dates, allowing
the mask field to be used as an offset.
* Bump the version of the magic format so that regex changes
are visible.
CWE ID: CWE-399 | mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir,
const unsigned char *s, uint32_t offset, size_t nbytes, struct magic *m)
{
/*
* Note: FILE_SEARCH and FILE_REGEX do not actually copy
* anything, but setup pointers into the source
*/
if (indir == 0) {
switch (type) {
case FILE_SEARCH:
ms->search.s = RCAST(const char *, s) + offset;
ms->search.s_len = nbytes - offset;
ms->search.offset = offset;
return 0;
case FILE_REGEX: {
const char *b;
const char *c;
const char *last; /* end of search region */
const char *buf; /* start of search region */
const char *end;
size_t lines, linecnt, bytecnt;
if (s == NULL) {
ms->search.s_len = 0;
ms->search.s = NULL;
return 0;
}
if (m->str_flags & REGEX_LINE_COUNT) {
linecnt = m->str_range;
bytecnt = linecnt * 80;
} else {
linecnt = 0;
bytecnt = m->str_range;
}
if (bytecnt == 0)
bytecnt = 8192;
if (bytecnt > nbytes)
bytecnt = nbytes;
buf = RCAST(const char *, s) + offset;
end = last = RCAST(const char *, s) + bytecnt;
/* mget() guarantees buf <= last */
for (lines = linecnt, b = buf; lines && b < end &&
((b = CAST(const char *,
memchr(c = b, '\n', CAST(size_t, (end - b)))))
|| (b = CAST(const char *,
memchr(c, '\r', CAST(size_t, (end - c))))));
lines--, b++) {
last = b;
if (b[0] == '\r' && b[1] == '\n')
b++;
}
if (lines)
last = RCAST(const char *, s) + bytecnt;
ms->search.s = buf;
ms->search.s_len = last - buf;
ms->search.offset = offset;
ms->search.rm_len = 0;
return 0;
}
case FILE_BESTRING16:
case FILE_LESTRING16: {
const unsigned char *src = s + offset;
const unsigned char *esrc = s + nbytes;
char *dst = p->s;
char *edst = &p->s[sizeof(p->s) - 1];
if (type == FILE_BESTRING16)
src++;
/* check that offset is within range */
if (offset >= nbytes)
break;
for (/*EMPTY*/; src < esrc; src += 2, dst++) {
if (dst < edst)
*dst = *src;
else
break;
if (*dst == '\0') {
if (type == FILE_BESTRING16 ?
*(src - 1) != '\0' :
*(src + 1) != '\0')
*dst = ' ';
}
}
*edst = '\0';
return 0;
}
case FILE_STRING: /* XXX - these two should not need */
case FILE_PSTRING: /* to copy anything, but do anyway. */
default:
break;
}
}
if (offset >= nbytes) {
(void)memset(p, '\0', sizeof(*p));
return 0;
}
if (nbytes - offset < sizeof(*p))
nbytes = nbytes - offset;
else
nbytes = sizeof(*p);
(void)memcpy(p, s + offset, nbytes);
/*
* the usefulness of padding with zeroes eludes me, it
* might even cause problems
*/
if (nbytes < sizeof(*p))
(void)memset(((char *)(void *)p) + nbytes, '\0',
sizeof(*p) - nbytes);
return 0;
}
| 166,359 |
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: char *cJSON_Print( cJSON *item )
{
return print_value( item, 0, 1 );
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | char *cJSON_Print( cJSON *item )
| 167,293 |
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 SubsetterImpl::ResolveCompositeGlyphs(const unsigned int* glyph_ids,
size_t glyph_count,
IntegerSet* glyph_id_processed) {
if (glyph_ids == NULL || glyph_count == 0 || glyph_id_processed == NULL) {
return false;
}
GlyphTablePtr glyph_table =
down_cast<GlyphTable*>(font_->GetTable(Tag::glyf));
LocaTablePtr loca_table = down_cast<LocaTable*>(font_->GetTable(Tag::loca));
if (glyph_table == NULL || loca_table == NULL) {
return false;
}
IntegerSet glyph_id_remaining;
glyph_id_remaining.insert(0); // Always include glyph id 0.
for (size_t i = 0; i < glyph_count; ++i) {
glyph_id_remaining.insert(glyph_ids[i]);
}
while (!glyph_id_remaining.empty()) {
IntegerSet comp_glyph_id;
for (IntegerSet::iterator i = glyph_id_remaining.begin(),
e = glyph_id_remaining.end(); i != e; ++i) {
if (*i < 0 || *i >= loca_table->NumGlyphs()) {
continue;
}
int32_t length = loca_table->GlyphLength(*i);
if (length == 0) {
continue;
}
int32_t offset = loca_table->GlyphOffset(*i);
GlyphPtr glyph;
glyph.Attach(glyph_table->GetGlyph(offset, length));
if (glyph == NULL) {
continue;
}
if (glyph->GlyphType() == GlyphType::kComposite) {
Ptr<GlyphTable::CompositeGlyph> comp_glyph =
down_cast<GlyphTable::CompositeGlyph*>(glyph.p_);
for (int32_t j = 0; j < comp_glyph->NumGlyphs(); ++j) {
int32_t glyph_id = comp_glyph->GlyphIndex(j);
if (glyph_id_processed->find(glyph_id) == glyph_id_processed->end() &&
glyph_id_remaining.find(glyph_id) == glyph_id_remaining.end()) {
comp_glyph_id.insert(comp_glyph->GlyphIndex(j));
}
}
}
glyph_id_processed->insert(*i);
}
glyph_id_remaining.clear();
glyph_id_remaining = comp_glyph_id;
}
}
Commit Message: Fix compile warning.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/7572039
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@95563 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | bool SubsetterImpl::ResolveCompositeGlyphs(const unsigned int* glyph_ids,
size_t glyph_count,
IntegerSet* glyph_id_processed) {
if (glyph_ids == NULL || glyph_count == 0 || glyph_id_processed == NULL) {
return false;
}
GlyphTablePtr glyph_table =
down_cast<GlyphTable*>(font_->GetTable(Tag::glyf));
LocaTablePtr loca_table = down_cast<LocaTable*>(font_->GetTable(Tag::loca));
if (glyph_table == NULL || loca_table == NULL) {
return false;
}
IntegerSet glyph_id_remaining;
glyph_id_remaining.insert(0); // Always include glyph id 0.
for (size_t i = 0; i < glyph_count; ++i) {
glyph_id_remaining.insert(glyph_ids[i]);
}
while (!glyph_id_remaining.empty()) {
IntegerSet comp_glyph_id;
for (IntegerSet::iterator i = glyph_id_remaining.begin(),
e = glyph_id_remaining.end(); i != e; ++i) {
if (*i < 0 || *i >= loca_table->NumGlyphs()) {
continue;
}
int32_t length = loca_table->GlyphLength(*i);
if (length == 0) {
continue;
}
int32_t offset = loca_table->GlyphOffset(*i);
GlyphPtr glyph;
glyph.Attach(glyph_table->GetGlyph(offset, length));
if (glyph == NULL) {
continue;
}
if (glyph->GlyphType() == GlyphType::kComposite) {
Ptr<GlyphTable::CompositeGlyph> comp_glyph =
down_cast<GlyphTable::CompositeGlyph*>(glyph.p_);
for (int32_t j = 0; j < comp_glyph->NumGlyphs(); ++j) {
int32_t glyph_id = comp_glyph->GlyphIndex(j);
if (glyph_id_processed->find(glyph_id) == glyph_id_processed->end() &&
glyph_id_remaining.find(glyph_id) == glyph_id_remaining.end()) {
comp_glyph_id.insert(comp_glyph->GlyphIndex(j));
}
}
}
glyph_id_processed->insert(*i);
}
glyph_id_remaining.clear();
glyph_id_remaining = comp_glyph_id;
}
return true;
}
| 170,329 |
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_item_verify(const ASN1_ITEM *it, X509_ALGOR *a,
ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
unsigned char *buf_in=NULL;
int ret= -1,inl;
int mdnid, pknid;
if (!pkey)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
if (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7)
{
ASN1err(ASN1_F_ASN1_VERIFY, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);
return -1;
}
EVP_MD_CTX_init(&ctx);
/* Convert signature OID into digest and public key OIDs */
if (!OBJ_find_sigid_algs(OBJ_obj2nid(a->algorithm), &mdnid, &pknid))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);
goto err;
}
if (mdnid == NID_undef)
{
if (!pkey->ameth || !pkey->ameth->item_verify)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);
goto err;
}
ret = pkey->ameth->item_verify(&ctx, it, asn, a,
signature, pkey);
/* Return value of 2 means carry on, anything else means we
* exit straight away: either a fatal error of the underlying
* verification routine handles all verification.
*/
if (ret != 2)
goto err;
ret = -1;
}
else
{
const EVP_MD *type;
type=EVP_get_digestbynid(mdnid);
if (type == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
/* Check public key OID matches public key type */
if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE);
goto err;
}
if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
ret = EVP_DigestVerifyUpdate(&ctx,buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (!ret)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
goto err;
}
ret = -1;
if (EVP_DigestVerifyFinal(&ctx,signature->data,
(size_t)signature->length) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
Commit Message: use correct function name
Reviewed-by: Rich Salz <[email protected]>
Reviewed-by: Matt Caswell <[email protected]>
CWE ID: CWE-310 | int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a,
ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
unsigned char *buf_in=NULL;
int ret= -1,inl;
int mdnid, pknid;
if (!pkey)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
if (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);
return -1;
}
EVP_MD_CTX_init(&ctx);
/* Convert signature OID into digest and public key OIDs */
if (!OBJ_find_sigid_algs(OBJ_obj2nid(a->algorithm), &mdnid, &pknid))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);
goto err;
}
if (mdnid == NID_undef)
{
if (!pkey->ameth || !pkey->ameth->item_verify)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);
goto err;
}
ret = pkey->ameth->item_verify(&ctx, it, asn, a,
signature, pkey);
/* Return value of 2 means carry on, anything else means we
* exit straight away: either a fatal error of the underlying
* verification routine handles all verification.
*/
if (ret != 2)
goto err;
ret = -1;
}
else
{
const EVP_MD *type;
type=EVP_get_digestbynid(mdnid);
if (type == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
/* Check public key OID matches public key type */
if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE);
goto err;
}
if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
ret = EVP_DigestVerifyUpdate(&ctx,buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (!ret)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
goto err;
}
ret = -1;
if (EVP_DigestVerifyFinal(&ctx,signature->data,
(size_t)signature->length) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
| 166,793 |
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 insert_key(
sc_pkcs15_card_t *p15card,
const char *path,
unsigned char id,
unsigned char key_reference,
int key_length,
unsigned char auth_id,
const char *label
){
sc_card_t *card=p15card->card;
sc_context_t *ctx=p15card->card->ctx;
sc_file_t *f;
struct sc_pkcs15_prkey_info prkey_info;
struct sc_pkcs15_object prkey_obj;
int r, can_sign, can_crypt;
memset(&prkey_info, 0, sizeof(prkey_info));
prkey_info.id.len = 1;
prkey_info.id.value[0] = id;
prkey_info.native = 1;
prkey_info.key_reference = key_reference;
prkey_info.modulus_length = key_length;
sc_format_path(path, &prkey_info.path);
memset(&prkey_obj, 0, sizeof(prkey_obj));
strlcpy(prkey_obj.label, label, sizeof(prkey_obj.label));
prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
prkey_obj.auth_id.len = 1;
prkey_obj.auth_id.value[0] = auth_id;
can_sign=can_crypt=0;
if(card->type==SC_CARD_TYPE_TCOS_V3){
unsigned char buf[256];
int i, rec_no=0;
if(prkey_info.path.len>=2) prkey_info.path.len-=2;
sc_append_file_id(&prkey_info.path, 0x5349);
if(sc_select_file(card, &prkey_info.path, NULL)!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Select(%s) failed\n",
sc_print_path(&prkey_info.path));
return 1;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Searching for Key-Ref %02X\n", key_reference);
while((r=sc_read_record(card, ++rec_no, buf, sizeof(buf), SC_RECORD_BY_REC_NR))>0){
int found=0;
if(buf[0]!=0xA0) continue;
for(i=2;i<buf[1]+2;i+=2+buf[i+1]){
if(buf[i]==0x83 && buf[i+1]==1 && buf[i+2]==key_reference) ++found;
}
if(found) break;
}
if(r<=0){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,"No EF_KEYD-Record found\n");
return 1;
}
for(i=0;i<r;i+=2+buf[i+1]){
if(buf[i]==0xB6) can_sign++;
if(buf[i]==0xB8) can_crypt++;
}
} else {
if(sc_select_file(card, &prkey_info.path, &f)!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Select(%s) failed\n",
sc_print_path(&prkey_info.path));
return 1;
}
if (f->prop_attr[1] & 0x04) can_crypt=1;
if (f->prop_attr[1] & 0x08) can_sign=1;
sc_file_free(f);
}
prkey_info.usage= SC_PKCS15_PRKEY_USAGE_SIGN;
if(can_crypt) prkey_info.usage |= SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_DECRYPT;
if(can_sign) prkey_info.usage |= SC_PKCS15_PRKEY_USAGE_NONREPUDIATION;
r=sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info);
if(r!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "sc_pkcs15emu_add_rsa_prkey(%s) failed\n", path);
return 4;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: OK%s%s\n", path, can_sign ? ", Sign" : "", can_crypt ? ", Crypt" : "");
return 0;
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125 | static int insert_key(
sc_pkcs15_card_t *p15card,
const char *path,
unsigned char id,
unsigned char key_reference,
int key_length,
unsigned char auth_id,
const char *label
){
sc_card_t *card=p15card->card;
sc_context_t *ctx=p15card->card->ctx;
sc_file_t *f;
struct sc_pkcs15_prkey_info prkey_info;
struct sc_pkcs15_object prkey_obj;
int r, can_sign, can_crypt;
memset(&prkey_info, 0, sizeof(prkey_info));
prkey_info.id.len = 1;
prkey_info.id.value[0] = id;
prkey_info.native = 1;
prkey_info.key_reference = key_reference;
prkey_info.modulus_length = key_length;
sc_format_path(path, &prkey_info.path);
memset(&prkey_obj, 0, sizeof(prkey_obj));
strlcpy(prkey_obj.label, label, sizeof(prkey_obj.label));
prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
prkey_obj.auth_id.len = 1;
prkey_obj.auth_id.value[0] = auth_id;
can_sign=can_crypt=0;
if(card->type==SC_CARD_TYPE_TCOS_V3){
unsigned char buf[256];
int i, rec_no=0;
if(prkey_info.path.len>=2) prkey_info.path.len-=2;
sc_append_file_id(&prkey_info.path, 0x5349);
if(sc_select_file(card, &prkey_info.path, NULL)!=SC_SUCCESS || !f->prop_attr){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Select(%s) failed\n",
sc_print_path(&prkey_info.path));
return 1;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Searching for Key-Ref %02X\n", key_reference);
while((r=sc_read_record(card, ++rec_no, buf, sizeof(buf), SC_RECORD_BY_REC_NR))>0){
int found=0;
if(buf[0]!=0xA0) continue;
for(i=2;i<buf[1]+2;i+=2+buf[i+1]){
if(buf[i]==0x83 && buf[i+1]==1 && buf[i+2]==key_reference) ++found;
}
if(found) break;
}
if(r<=0){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,"No EF_KEYD-Record found\n");
return 1;
}
for(i=0;i<r;i+=2+buf[i+1]){
if(buf[i]==0xB6) can_sign++;
if(buf[i]==0xB8) can_crypt++;
}
} else {
if(sc_select_file(card, &prkey_info.path, &f)!=SC_SUCCESS
|| !f->prop_attr || f->prop_attr_len < 2){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Select(%s) failed\n",
sc_print_path(&prkey_info.path));
return 1;
}
if (f->prop_attr[1] & 0x04) can_crypt=1;
if (f->prop_attr[1] & 0x08) can_sign=1;
sc_file_free(f);
}
prkey_info.usage= SC_PKCS15_PRKEY_USAGE_SIGN;
if(can_crypt) prkey_info.usage |= SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_DECRYPT;
if(can_sign) prkey_info.usage |= SC_PKCS15_PRKEY_USAGE_NONREPUDIATION;
r=sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info);
if(r!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "sc_pkcs15emu_add_rsa_prkey(%s) failed\n", path);
return 4;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: OK%s%s\n", path, can_sign ? ", Sign" : "", can_crypt ? ", Crypt" : "");
return 0;
}
| 169,067 |
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 udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len, int noblock, int flags, int *addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
bool slow;
/*
* Check any passed addresses
*/
if (addr_len)
*addr_len = sizeof(*sin);
if (flags & MSG_ERRQUEUE)
return ip_recv_error(sk, msg, len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
if (udp_lib_checksum_complete(skb))
goto csum_copy_err;
}
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr),
msg->msg_iov, copied);
else {
err = skb_copy_and_csum_datagram_iovec(skb,
sizeof(struct udphdr),
msg->msg_iov);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udp_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
goto out_free;
}
if (!peeked)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (sin) {
sin->sin_family = AF_INET;
sin->sin_port = udp_hdr(skb)->source;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
}
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
}
unlock_sock_fast(sk, slow);
if (noblock)
return -EAGAIN;
/* starting over for a new packet */
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
Commit Message: inet: prevent leakage of uninitialized memory to user in recv syscalls
Only update *addr_len when we actually fill in sockaddr, otherwise we
can return uninitialized memory from the stack to the caller in the
recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL)
checks because we only get called with a valid addr_len pointer either
from sock_common_recvmsg or inet_recvmsg.
If a blocking read waits on a socket which is concurrently shut down we
now return zero and set msg_msgnamelen to 0.
Reported-by: mpb <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len, int noblock, int flags, int *addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
bool slow;
if (flags & MSG_ERRQUEUE)
return ip_recv_error(sk, msg, len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
if (udp_lib_checksum_complete(skb))
goto csum_copy_err;
}
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr),
msg->msg_iov, copied);
else {
err = skb_copy_and_csum_datagram_iovec(skb,
sizeof(struct udphdr),
msg->msg_iov);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udp_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
goto out_free;
}
if (!peeked)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (sin) {
sin->sin_family = AF_INET;
sin->sin_port = udp_hdr(skb)->source;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
*addr_len = sizeof(*sin);
}
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
}
unlock_sock_fast(sk, slow);
if (noblock)
return -EAGAIN;
/* starting over for a new packet */
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
| 166,479 |
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 SyncManager::SyncInternal::UpdateEnabledTypes() {
DCHECK(thread_checker_.CalledOnValidThread());
ModelSafeRoutingInfo routes;
registrar_->GetModelSafeRoutingInfo(&routes);
const ModelTypeSet enabled_types = GetRoutingInfoTypes(routes);
sync_notifier_->UpdateEnabledTypes(enabled_types);
if (enable_sync_tabs_for_other_clients_)
MaybeSetSyncTabsInNigoriNode(enabled_types);
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | void SyncManager::SyncInternal::UpdateEnabledTypes() {
DCHECK(thread_checker_.CalledOnValidThread());
ModelSafeRoutingInfo routes;
registrar_->GetModelSafeRoutingInfo(&routes);
const ModelTypeSet enabled_types = GetRoutingInfoTypes(routes);
sync_notifier_->UpdateEnabledTypes(enabled_types);
| 170,798 |
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 udf_get_filename(struct super_block *sb, uint8_t *sname, uint8_t *dname,
int flen)
{
struct ustr *filename, *unifilename;
int len = 0;
filename = kmalloc(sizeof(struct ustr), GFP_NOFS);
if (!filename)
return 0;
unifilename = kmalloc(sizeof(struct ustr), GFP_NOFS);
if (!unifilename)
goto out1;
if (udf_build_ustr_exact(unifilename, sname, flen))
goto out2;
if (UDF_QUERY_FLAG(sb, UDF_FLAG_UTF8)) {
if (!udf_CS0toUTF8(filename, unifilename)) {
udf_debug("Failed in udf_get_filename: sname = %s\n",
sname);
goto out2;
}
} else if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP)) {
if (!udf_CS0toNLS(UDF_SB(sb)->s_nls_map, filename,
unifilename)) {
udf_debug("Failed in udf_get_filename: sname = %s\n",
sname);
goto out2;
}
} else
goto out2;
len = udf_translate_to_linux(dname, filename->u_name, filename->u_len,
unifilename->u_name, unifilename->u_len);
out2:
kfree(unifilename);
out1:
kfree(filename);
return len;
}
Commit Message: udf: Check path length when reading symlink
Symlink reading code does not check whether the resulting path fits into
the page provided by the generic code. This isn't as easy as just
checking the symlink size because of various encoding conversions we
perform on path. So we have to check whether there is still enough space
in the buffer on the fly.
CC: [email protected]
Reported-by: Carl Henrik Lunde <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-17 | int udf_get_filename(struct super_block *sb, uint8_t *sname, uint8_t *dname,
int udf_get_filename(struct super_block *sb, uint8_t *sname, int slen,
uint8_t *dname, int dlen)
{
struct ustr *filename, *unifilename;
int len = 0;
filename = kmalloc(sizeof(struct ustr), GFP_NOFS);
if (!filename)
return 0;
unifilename = kmalloc(sizeof(struct ustr), GFP_NOFS);
if (!unifilename)
goto out1;
if (udf_build_ustr_exact(unifilename, sname, slen))
goto out2;
if (UDF_QUERY_FLAG(sb, UDF_FLAG_UTF8)) {
if (!udf_CS0toUTF8(filename, unifilename)) {
udf_debug("Failed in udf_get_filename: sname = %s\n",
sname);
goto out2;
}
} else if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP)) {
if (!udf_CS0toNLS(UDF_SB(sb)->s_nls_map, filename,
unifilename)) {
udf_debug("Failed in udf_get_filename: sname = %s\n",
sname);
goto out2;
}
} else
goto out2;
len = udf_translate_to_linux(dname, dlen,
filename->u_name, filename->u_len,
unifilename->u_name, unifilename->u_len);
out2:
kfree(unifilename);
out1:
kfree(filename);
return len;
}
| 166,759 |
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 BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
unsigned long int req, void *buf,
BlockCompletionFunc *cb, void *opaque)
{
IscsiLun *iscsilun = bs->opaque;
struct iscsi_context *iscsi = iscsilun->iscsi;
struct iscsi_data data;
IscsiAIOCB *acb;
acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
acb->iscsilun = iscsilun;
acb->bh = NULL;
acb->status = -EINPROGRESS;
acb->buf = NULL;
acb->ioh = buf;
if (req != SG_IO) {
iscsi_ioctl_handle_emulated(acb, req, buf);
return &acb->common;
}
acb->task = malloc(sizeof(struct scsi_task));
if (acb->task == NULL) {
error_report("iSCSI: Failed to allocate task for scsi command. %s",
case SG_DXFER_TO_DEV:
acb->task->xfer_dir = SCSI_XFER_WRITE;
break;
case SG_DXFER_FROM_DEV:
acb->task->xfer_dir = SCSI_XFER_READ;
break;
default:
acb->task->xfer_dir = SCSI_XFER_NONE;
break;
}
acb->task->cdb_size = acb->ioh->cmd_len;
memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
acb->task->expxferlen = acb->ioh->dxfer_len;
data.size = 0;
if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
if (acb->ioh->iovec_count == 0) {
data.data = acb->ioh->dxferp;
data.size = acb->ioh->dxfer_len;
} else {
scsi_task_set_iov_out(acb->task,
(struct scsi_iovec *) acb->ioh->dxferp,
acb->ioh->iovec_count);
}
}
if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
iscsi_aio_ioctl_cb,
(data.size > 0) ? &data : NULL,
acb) != 0) {
scsi_free_scsi_task(acb->task);
qemu_aio_unref(acb);
return NULL;
}
/* tell libiscsi to read straight into the buffer we got from ioctl */
if (acb->task->xfer_dir == SCSI_XFER_READ) {
if (acb->ioh->iovec_count == 0) {
scsi_task_add_data_in_buffer(acb->task,
acb->ioh->dxfer_len,
acb->ioh->dxferp);
} else {
scsi_task_set_iov_in(acb->task,
(struct scsi_iovec *) acb->ioh->dxferp,
acb->ioh->iovec_count);
}
}
iscsi_set_events(iscsilun);
return &acb->common;
}
Commit Message:
CWE ID: CWE-119 | static BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
unsigned long int req, void *buf,
BlockCompletionFunc *cb, void *opaque)
{
IscsiLun *iscsilun = bs->opaque;
struct iscsi_context *iscsi = iscsilun->iscsi;
struct iscsi_data data;
IscsiAIOCB *acb;
acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
acb->iscsilun = iscsilun;
acb->bh = NULL;
acb->status = -EINPROGRESS;
acb->buf = NULL;
acb->ioh = buf;
if (req != SG_IO) {
iscsi_ioctl_handle_emulated(acb, req, buf);
return &acb->common;
}
if (acb->ioh->cmd_len > SCSI_CDB_MAX_SIZE) {
error_report("iSCSI: ioctl error CDB exceeds max size (%d > %d)",
acb->ioh->cmd_len, SCSI_CDB_MAX_SIZE);
qemu_aio_unref(acb);
return NULL;
}
acb->task = malloc(sizeof(struct scsi_task));
if (acb->task == NULL) {
error_report("iSCSI: Failed to allocate task for scsi command. %s",
case SG_DXFER_TO_DEV:
acb->task->xfer_dir = SCSI_XFER_WRITE;
break;
case SG_DXFER_FROM_DEV:
acb->task->xfer_dir = SCSI_XFER_READ;
break;
default:
acb->task->xfer_dir = SCSI_XFER_NONE;
break;
}
acb->task->cdb_size = acb->ioh->cmd_len;
memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
acb->task->expxferlen = acb->ioh->dxfer_len;
data.size = 0;
if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
if (acb->ioh->iovec_count == 0) {
data.data = acb->ioh->dxferp;
data.size = acb->ioh->dxfer_len;
} else {
scsi_task_set_iov_out(acb->task,
(struct scsi_iovec *) acb->ioh->dxferp,
acb->ioh->iovec_count);
}
}
if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
iscsi_aio_ioctl_cb,
(data.size > 0) ? &data : NULL,
acb) != 0) {
scsi_free_scsi_task(acb->task);
qemu_aio_unref(acb);
return NULL;
}
/* tell libiscsi to read straight into the buffer we got from ioctl */
if (acb->task->xfer_dir == SCSI_XFER_READ) {
if (acb->ioh->iovec_count == 0) {
scsi_task_add_data_in_buffer(acb->task,
acb->ioh->dxfer_len,
acb->ioh->dxferp);
} else {
scsi_task_set_iov_in(acb->task,
(struct scsi_iovec *) acb->ioh->dxferp,
acb->ioh->iovec_count);
}
}
iscsi_set_events(iscsilun);
return &acb->common;
}
| 165,014 |
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 sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,
size_t sec_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (sec_attr == NULL) {
if (file->sec_attr != NULL)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return 0;
}
tmp = (u8 *) realloc(file->sec_attr, sec_attr_len);
if (!tmp) {
if (file->sec_attr)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->sec_attr = tmp;
memcpy(file->sec_attr, sec_attr, sec_attr_len);
file->sec_attr_len = sec_attr_len;
return 0;
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415 | int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,
size_t sec_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (sec_attr == NULL || sec_attr_len) {
if (file->sec_attr != NULL)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return 0;
}
tmp = (u8 *) realloc(file->sec_attr, sec_attr_len);
if (!tmp) {
if (file->sec_attr)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->sec_attr = tmp;
memcpy(file->sec_attr, sec_attr, sec_attr_len);
file->sec_attr_len = sec_attr_len;
return 0;
}
| 169,079 |
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 kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
{
u32 data, tpr;
int max_irr, max_isr;
struct kvm_lapic *apic = vcpu->arch.apic;
void *vapic;
apic_sync_pv_eoi_to_guest(vcpu, apic);
if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
return;
tpr = kvm_apic_get_reg(apic, APIC_TASKPRI) & 0xff;
max_irr = apic_find_highest_irr(apic);
if (max_irr < 0)
max_irr = 0;
max_isr = apic_find_highest_isr(apic);
if (max_isr < 0)
max_isr = 0;
data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
vapic = kmap_atomic(vcpu->arch.apic->vapic_page);
*(u32 *)(vapic + offset_in_page(vcpu->arch.apic->vapic_addr)) = data;
kunmap_atomic(vapic);
}
Commit Message: KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368)
In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the
potential to corrupt kernel memory if userspace provides an address that
is at the end of a page. This patches concerts those functions to use
kvm_write_guest_cached and kvm_read_guest_cached. It also checks the
vapic_address specified by userspace during ioctl processing and returns
an error to userspace if the address is not a valid GPA.
This is generally not guest triggerable, because the required write is
done by firmware that runs before the guest. Also, it only affects AMD
processors and oldish Intel that do not have the FlexPriority feature
(unless you disable FlexPriority, of course; then newer processors are
also affected).
Fixes: b93463aa59d6 ('KVM: Accelerated apic support')
Reported-by: Andrew Honig <[email protected]>
Cc: [email protected]
Signed-off-by: Andrew Honig <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-20 | void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
{
u32 data, tpr;
int max_irr, max_isr;
struct kvm_lapic *apic = vcpu->arch.apic;
apic_sync_pv_eoi_to_guest(vcpu, apic);
if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
return;
tpr = kvm_apic_get_reg(apic, APIC_TASKPRI) & 0xff;
max_irr = apic_find_highest_irr(apic);
if (max_irr < 0)
max_irr = 0;
max_isr = apic_find_highest_isr(apic);
if (max_isr < 0)
max_isr = 0;
data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
sizeof(u32));
}
| 165,946 |
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: LayerTreeHostQt::LayerTreeHostQt(WebPage* webPage)
: LayerTreeHost(webPage)
, m_notifyAfterScheduledLayerFlush(false)
, m_isValid(true)
#if USE(TILED_BACKING_STORE)
, m_waitingForUIProcess(false)
, m_isSuspended(false)
, m_contentsScale(1)
#endif
, m_shouldSyncFrame(false)
, m_shouldSyncRootLayer(true)
, m_layerFlushTimer(this, &LayerTreeHostQt::layerFlushTimerFired)
, m_layerFlushSchedulingEnabled(true)
{
m_rootLayer = GraphicsLayer::create(this);
WebGraphicsLayer* webRootLayer = toWebGraphicsLayer(m_rootLayer.get());
webRootLayer->setRootLayer(true);
#ifndef NDEBUG
m_rootLayer->setName("LayerTreeHostQt root layer");
#endif
m_rootLayer->setDrawsContent(false);
m_rootLayer->setSize(m_webPage->size());
m_layerTreeContext.webLayerID = toWebGraphicsLayer(webRootLayer)->id();
m_nonCompositedContentLayer = GraphicsLayer::create(this);
#if USE(TILED_BACKING_STORE)
toWebGraphicsLayer(m_rootLayer.get())->setWebGraphicsLayerClient(this);
#endif
#ifndef NDEBUG
m_nonCompositedContentLayer->setName("LayerTreeHostQt non-composited content");
#endif
m_nonCompositedContentLayer->setDrawsContent(true);
m_nonCompositedContentLayer->setContentsOpaque(m_webPage->drawsBackground() && !m_webPage->drawsTransparentBackground());
m_nonCompositedContentLayer->setSize(m_webPage->size());
m_rootLayer->addChild(m_nonCompositedContentLayer.get());
if (m_webPage->hasPageOverlay())
createPageOverlayLayer();
scheduleLayerFlush();
}
Commit Message: [Qt][WK2] Allow transparent WebViews
https://bugs.webkit.org/show_bug.cgi?id=80608
Reviewed by Tor Arne Vestbø.
Added support for transparentBackground in QQuickWebViewExperimental.
This uses the existing drawsTransparentBackground property in WebKit2.
Also, changed LayerTreeHostQt to set the contentsOpaque flag when the root layer changes,
otherwise the change doesn't take effect.
A new API test was added.
* UIProcess/API/qt/qquickwebview.cpp:
(QQuickWebViewPrivate::setTransparentBackground):
(QQuickWebViewPrivate::transparentBackground):
(QQuickWebViewExperimental::transparentBackground):
(QQuickWebViewExperimental::setTransparentBackground):
* UIProcess/API/qt/qquickwebview_p.h:
* UIProcess/API/qt/qquickwebview_p_p.h:
(QQuickWebViewPrivate):
* UIProcess/API/qt/tests/qquickwebview/tst_qquickwebview.cpp:
(tst_QQuickWebView):
(tst_QQuickWebView::transparentWebViews):
* WebProcess/WebPage/qt/LayerTreeHostQt.cpp:
(WebKit::LayerTreeHostQt::LayerTreeHostQt):
(WebKit::LayerTreeHostQt::setRootCompositingLayer):
git-svn-id: svn://svn.chromium.org/blink/trunk@110254 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-189 | LayerTreeHostQt::LayerTreeHostQt(WebPage* webPage)
: LayerTreeHost(webPage)
, m_notifyAfterScheduledLayerFlush(false)
, m_isValid(true)
#if USE(TILED_BACKING_STORE)
, m_waitingForUIProcess(false)
, m_isSuspended(false)
, m_contentsScale(1)
#endif
, m_shouldSyncFrame(false)
, m_shouldSyncRootLayer(true)
, m_layerFlushTimer(this, &LayerTreeHostQt::layerFlushTimerFired)
, m_layerFlushSchedulingEnabled(true)
{
m_rootLayer = GraphicsLayer::create(this);
WebGraphicsLayer* webRootLayer = toWebGraphicsLayer(m_rootLayer.get());
webRootLayer->setRootLayer(true);
#ifndef NDEBUG
m_rootLayer->setName("LayerTreeHostQt root layer");
#endif
m_rootLayer->setDrawsContent(false);
m_rootLayer->setSize(m_webPage->size());
m_layerTreeContext.webLayerID = toWebGraphicsLayer(webRootLayer)->id();
m_nonCompositedContentLayer = GraphicsLayer::create(this);
#if USE(TILED_BACKING_STORE)
toWebGraphicsLayer(m_rootLayer.get())->setWebGraphicsLayerClient(this);
#endif
#ifndef NDEBUG
m_nonCompositedContentLayer->setName("LayerTreeHostQt non-composited content");
#endif
m_nonCompositedContentLayer->setDrawsContent(true);
m_nonCompositedContentLayer->setSize(m_webPage->size());
m_rootLayer->addChild(m_nonCompositedContentLayer.get());
if (m_webPage->hasPageOverlay())
createPageOverlayLayer();
scheduleLayerFlush();
}
| 170,618 |
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 sysMapFD(int fd, MemMapping* pMap)
{
off_t start;
size_t length;
void* memPtr;
assert(pMap != NULL);
if (getFileStartAndLength(fd, &start, &length) < 0)
return -1;
memPtr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, start);
if (memPtr == MAP_FAILED) {
LOGW("mmap(%d, R, PRIVATE, %d, %d) failed: %s\n", (int) length,
fd, (int) start, strerror(errno));
return -1;
}
pMap->addr = memPtr;
pMap->length = length;
pMap->range_count = 1;
pMap->ranges = malloc(sizeof(MappedRange));
pMap->ranges[0].addr = memPtr;
pMap->ranges[0].length = length;
return 0;
}
Commit Message: Fix integer overflows in recovery procedure.
Bug: 26960931
Change-Id: Ieae45caccfb4728fcf514f0d920976585d8e6caf
(cherry picked from commit 4f2df162c6ab4a71ca86e4b38735b681729c353b)
CWE ID: CWE-189 | static int sysMapFD(int fd, MemMapping* pMap)
{
off_t start;
size_t length;
void* memPtr;
assert(pMap != NULL);
if (getFileStartAndLength(fd, &start, &length) < 0)
return -1;
memPtr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, start);
if (memPtr == MAP_FAILED) {
LOGW("mmap(%d, R, PRIVATE, %d, %d) failed: %s\n", (int) length,
fd, (int) start, strerror(errno));
return -1;
}
pMap->addr = memPtr;
pMap->length = length;
pMap->range_count = 1;
pMap->ranges = malloc(sizeof(MappedRange));
if (pMap->ranges == NULL) {
LOGE("malloc failed: %s\n", strerror(errno));
munmap(memPtr, length);
return -1;
}
pMap->ranges[0].addr = memPtr;
pMap->ranges[0].length = length;
return 0;
}
| 173,904 |
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 MediaElementAudioSourceHandler::SetFormat(size_t number_of_channels,
float source_sample_rate) {
if (number_of_channels != source_number_of_channels_ ||
source_sample_rate != source_sample_rate_) {
if (!number_of_channels ||
number_of_channels > BaseAudioContext::MaxNumberOfChannels() ||
!AudioUtilities::IsValidAudioBufferSampleRate(source_sample_rate)) {
DLOG(ERROR) << "setFormat(" << number_of_channels << ", "
<< source_sample_rate << ") - unhandled format change";
Locker<MediaElementAudioSourceHandler> locker(*this);
source_number_of_channels_ = 0;
source_sample_rate_ = 0;
return;
}
Locker<MediaElementAudioSourceHandler> locker(*this);
source_number_of_channels_ = number_of_channels;
source_sample_rate_ = source_sample_rate;
if (source_sample_rate != Context()->sampleRate()) {
double scale_factor = source_sample_rate / Context()->sampleRate();
multi_channel_resampler_ = std::make_unique<MultiChannelResampler>(
scale_factor, number_of_channels);
} else {
multi_channel_resampler_.reset();
}
{
BaseAudioContext::GraphAutoLocker context_locker(Context());
Output(0).SetNumberOfChannels(number_of_channels);
}
}
}
Commit Message: Redirect should not circumvent same-origin restrictions
Check whether we have access to the audio data when the format is set.
At this point we have enough information to determine this. The old approach
based on when the src was changed was incorrect because at the point, we
only know the new src; none of the response headers have been read yet.
This new approach also removes the incorrect message reported in 619114.
Bug: 826552, 619114
Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6
Reviewed-on: https://chromium-review.googlesource.com/1069540
Commit-Queue: Raymond Toy <[email protected]>
Reviewed-by: Yutaka Hirano <[email protected]>
Reviewed-by: Hongchan Choi <[email protected]>
Cr-Commit-Position: refs/heads/master@{#564313}
CWE ID: CWE-20 | void MediaElementAudioSourceHandler::SetFormat(size_t number_of_channels,
float source_sample_rate) {
bool is_tainted = WouldTaintOrigin();
if (is_tainted) {
PrintCORSMessage(MediaElement()->currentSrc().GetString());
}
if (number_of_channels != source_number_of_channels_ ||
source_sample_rate != source_sample_rate_) {
if (!number_of_channels ||
number_of_channels > BaseAudioContext::MaxNumberOfChannels() ||
!AudioUtilities::IsValidAudioBufferSampleRate(source_sample_rate)) {
DLOG(ERROR) << "setFormat(" << number_of_channels << ", "
<< source_sample_rate << ") - unhandled format change";
Locker<MediaElementAudioSourceHandler> locker(*this);
source_number_of_channels_ = 0;
source_sample_rate_ = 0;
is_origin_tainted_ = is_tainted;
return;
}
// Synchronize with process() to protect |source_number_of_channels_|,
// |source_sample_rate_|, |multi_channel_resampler_|. and
// |is_origin_tainted_|.
Locker<MediaElementAudioSourceHandler> locker(*this);
is_origin_tainted_ = is_tainted;
source_number_of_channels_ = number_of_channels;
source_sample_rate_ = source_sample_rate;
if (source_sample_rate != Context()->sampleRate()) {
double scale_factor = source_sample_rate / Context()->sampleRate();
multi_channel_resampler_ = std::make_unique<MultiChannelResampler>(
scale_factor, number_of_channels);
} else {
multi_channel_resampler_.reset();
}
{
BaseAudioContext::GraphAutoLocker context_locker(Context());
Output(0).SetNumberOfChannels(number_of_channels);
}
}
}
| 173,150 |
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 CompileFromResponseCallback(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ExceptionState exception_state(args.GetIsolate(),
ExceptionState::kExecutionContext,
"WebAssembly", "compile");
ExceptionToRejectPromiseScope reject_promise_scope(args, exception_state);
ScriptState* script_state = ScriptState::ForRelevantRealm(args);
if (!ExecutionContext::From(script_state)) {
V8SetReturnValue(args, ScriptPromise().V8Value());
return;
}
if (args.Length() < 1 || !args[0]->IsObject() ||
!V8Response::hasInstance(args[0], args.GetIsolate())) {
V8SetReturnValue(
args,
ScriptPromise::Reject(
script_state, V8ThrowException::CreateTypeError(
script_state->GetIsolate(),
"An argument must be provided, which must be a"
"Response or Promise<Response> object"))
.V8Value());
return;
}
Response* response = V8Response::ToImpl(v8::Local<v8::Object>::Cast(args[0]));
if (response->MimeType() != "application/wasm") {
V8SetReturnValue(
args,
ScriptPromise::Reject(
script_state,
V8ThrowException::CreateTypeError(
script_state->GetIsolate(),
"Incorrect response MIME type. Expected 'application/wasm'."))
.V8Value());
return;
}
v8::Local<v8::Value> promise;
if (response->IsBodyLocked() || response->bodyUsed()) {
promise = ScriptPromise::Reject(script_state,
V8ThrowException::CreateTypeError(
script_state->GetIsolate(),
"Cannot compile WebAssembly.Module "
"from an already read Response"))
.V8Value();
} else {
if (response->BodyBuffer()) {
FetchDataLoaderAsWasmModule* loader =
new FetchDataLoaderAsWasmModule(script_state);
promise = loader->GetPromise();
response->BodyBuffer()->StartLoading(loader, new WasmDataLoaderClient());
} else {
promise = ScriptPromise::Reject(script_state,
V8ThrowException::CreateTypeError(
script_state->GetIsolate(),
"Response object has a null body."))
.V8Value();
}
}
V8SetReturnValue(args, promise);
}
Commit Message: [wasm] Use correct bindings APIs
Use ScriptState::ForCurrentRealm in static methods, instead of
ForRelevantRealm().
Bug: chromium:788453
Change-Id: I63bd25e3f5a4e8d7cbaff945da8df0d71aa65527
Reviewed-on: https://chromium-review.googlesource.com/795096
Commit-Queue: Mircea Trofin <[email protected]>
Reviewed-by: Yuki Shiino <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Cr-Commit-Position: refs/heads/master@{#520174}
CWE ID: CWE-79 | void CompileFromResponseCallback(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ExceptionState exception_state(args.GetIsolate(),
ExceptionState::kExecutionContext,
"WebAssembly", "compile");
ExceptionToRejectPromiseScope reject_promise_scope(args, exception_state);
ScriptState* script_state = ScriptState::ForCurrentRealm(args);
if (!ExecutionContext::From(script_state)) {
V8SetReturnValue(args, ScriptPromise().V8Value());
return;
}
if (args.Length() < 1 || !args[0]->IsObject() ||
!V8Response::hasInstance(args[0], args.GetIsolate())) {
V8SetReturnValue(
args,
ScriptPromise::Reject(
script_state, V8ThrowException::CreateTypeError(
script_state->GetIsolate(),
"An argument must be provided, which must be a "
"Response or Promise<Response> object"))
.V8Value());
return;
}
Response* response = V8Response::ToImpl(v8::Local<v8::Object>::Cast(args[0]));
if (response->MimeType() != "application/wasm") {
V8SetReturnValue(
args,
ScriptPromise::Reject(
script_state,
V8ThrowException::CreateTypeError(
script_state->GetIsolate(),
"Incorrect response MIME type. Expected 'application/wasm'."))
.V8Value());
return;
}
v8::Local<v8::Value> promise;
if (response->IsBodyLocked() || response->bodyUsed()) {
promise = ScriptPromise::Reject(script_state,
V8ThrowException::CreateTypeError(
script_state->GetIsolate(),
"Cannot compile WebAssembly.Module "
"from an already read Response"))
.V8Value();
} else {
if (response->BodyBuffer()) {
FetchDataLoaderAsWasmModule* loader =
new FetchDataLoaderAsWasmModule(script_state);
promise = loader->GetPromise();
response->BodyBuffer()->StartLoading(loader, new WasmDataLoaderClient());
} else {
promise = ScriptPromise::Reject(script_state,
V8ThrowException::CreateTypeError(
script_state->GetIsolate(),
"Response object has a null body."))
.V8Value();
}
}
V8SetReturnValue(args, promise);
}
| 172,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: static int add_push_report_sideband_pkt(git_push *push, git_pkt_data *data_pkt, git_buf *data_pkt_buf)
{
git_pkt *pkt;
const char *line, *line_end = NULL;
size_t line_len;
int error;
int reading_from_buf = data_pkt_buf->size > 0;
if (reading_from_buf) {
/* We had an existing partial packet, so add the new
* packet to the buffer and parse the whole thing */
git_buf_put(data_pkt_buf, data_pkt->data, data_pkt->len);
line = data_pkt_buf->ptr;
line_len = data_pkt_buf->size;
}
else {
line = data_pkt->data;
line_len = data_pkt->len;
}
while (line_len > 0) {
error = git_pkt_parse_line(&pkt, line, &line_end, line_len);
if (error == GIT_EBUFS) {
/* Buffer the data when the inner packet is split
* across multiple sideband packets */
if (!reading_from_buf)
git_buf_put(data_pkt_buf, line, line_len);
error = 0;
goto done;
}
else if (error < 0)
goto done;
/* Advance in the buffer */
line_len -= (line_end - line);
line = line_end;
/* When a valid packet with no content has been
* read, git_pkt_parse_line does not report an
* error, but the pkt pointer has not been set.
* Handle this by skipping over empty packets.
*/
if (pkt == NULL)
continue;
error = add_push_report_pkt(push, pkt);
git_pkt_free(pkt);
if (error < 0 && error != GIT_ITEROVER)
goto done;
}
error = 0;
done:
if (reading_from_buf)
git_buf_consume(data_pkt_buf, line_end);
return error;
}
Commit Message: smart_pkt: treat empty packet lines as error
The Git protocol does not specify what should happen in the case
of an empty packet line (that is a packet line "0004"). We
currently indicate success, but do not return a packet in the
case where we hit an empty line. The smart protocol was not
prepared to handle such packets in all cases, though, resulting
in a `NULL` pointer dereference.
Fix the issue by returning an error instead. As such kind of
packets is not even specified by upstream, this is the right
thing to do.
CWE ID: CWE-476 | static int add_push_report_sideband_pkt(git_push *push, git_pkt_data *data_pkt, git_buf *data_pkt_buf)
{
git_pkt *pkt;
const char *line, *line_end = NULL;
size_t line_len;
int error;
int reading_from_buf = data_pkt_buf->size > 0;
if (reading_from_buf) {
/* We had an existing partial packet, so add the new
* packet to the buffer and parse the whole thing */
git_buf_put(data_pkt_buf, data_pkt->data, data_pkt->len);
line = data_pkt_buf->ptr;
line_len = data_pkt_buf->size;
}
else {
line = data_pkt->data;
line_len = data_pkt->len;
}
while (line_len > 0) {
error = git_pkt_parse_line(&pkt, line, &line_end, line_len);
if (error == GIT_EBUFS) {
/* Buffer the data when the inner packet is split
* across multiple sideband packets */
if (!reading_from_buf)
git_buf_put(data_pkt_buf, line, line_len);
error = 0;
goto done;
}
else if (error < 0)
goto done;
/* Advance in the buffer */
line_len -= (line_end - line);
line = line_end;
error = add_push_report_pkt(push, pkt);
git_pkt_free(pkt);
if (error < 0 && error != GIT_ITEROVER)
goto done;
}
error = 0;
done:
if (reading_from_buf)
git_buf_consume(data_pkt_buf, line_end);
return error;
}
| 168,528 |
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 WebMediaPlayerImpl::DidPassCORSAccessCheck() const {
if (data_source_)
return data_source_->DidPassCORSAccessCheck();
return false;
}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732 | bool WebMediaPlayerImpl::DidPassCORSAccessCheck() const {
bool WebMediaPlayerImpl::WouldTaintOrigin() const {
if (!HasSingleSecurityOrigin()) {
// When the resource is redirected to another origin we think it as
// tainted. This is actually not specified, and is under discussion.
// See https://github.com/whatwg/fetch/issues/737.
return true;
}
return data_source_ && data_source_->IsCorsCrossOrigin();
}
| 172,631 |
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 ExtensionsGuestViewMessageFilter::MimeHandlerViewGuestCreatedCallback(
int element_instance_id,
int embedder_render_process_id,
int embedder_render_frame_id,
int32_t plugin_frame_routing_id,
const gfx::Size& element_size,
mime_handler::BeforeUnloadControlPtrInfo before_unload_control,
bool is_full_page_plugin,
WebContents* web_contents) {
auto* guest_view = MimeHandlerViewGuest::FromWebContents(web_contents);
if (!guest_view)
return;
guest_view->SetBeforeUnloadController(std::move(before_unload_control));
int guest_instance_id = guest_view->guest_instance_id();
auto* rfh = RenderFrameHost::FromID(embedder_render_process_id,
embedder_render_frame_id);
if (!rfh)
return;
guest_view->SetEmbedderFrame(embedder_render_process_id,
embedder_render_frame_id);
base::DictionaryValue attach_params;
attach_params.SetInteger(guest_view::kElementWidth, element_size.width());
attach_params.SetInteger(guest_view::kElementHeight, element_size.height());
auto* manager = GuestViewManager::FromBrowserContext(browser_context_);
if (!manager) {
guest_view::bad_message::ReceivedBadMessage(
this,
guest_view::bad_message::GVMF_UNEXPECTED_MESSAGE_BEFORE_GVM_CREATION);
guest_view->Destroy(true);
return;
}
manager->AttachGuest(embedder_render_process_id, element_instance_id,
guest_instance_id, attach_params);
if (!content::MimeHandlerViewMode::UsesCrossProcessFrame()) {
rfh->Send(new ExtensionsGuestViewMsg_CreateMimeHandlerViewGuestACK(
element_instance_id));
return;
}
auto* plugin_rfh = RenderFrameHost::FromID(embedder_render_process_id,
plugin_frame_routing_id);
if (!plugin_rfh) {
plugin_rfh = RenderFrameHost::FromPlaceholderId(embedder_render_process_id,
plugin_frame_routing_id);
}
if (!plugin_rfh) {
guest_view->GetEmbedderFrame()->Send(
new ExtensionsGuestViewMsg_RetryCreatingMimeHandlerViewGuest(
element_instance_id));
guest_view->Destroy(true);
return;
}
if (guest_view->web_contents()->CanAttachToOuterContentsFrame(plugin_rfh)) {
guest_view->AttachToOuterWebContentsFrame(plugin_rfh, element_instance_id,
is_full_page_plugin);
} else {
frame_navigation_helpers_[element_instance_id] =
std::make_unique<FrameNavigationHelper>(
plugin_rfh, guest_view->guest_instance_id(), element_instance_id,
is_full_page_plugin, this);
}
}
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155}
CWE ID: CWE-362 | void ExtensionsGuestViewMessageFilter::MimeHandlerViewGuestCreatedCallback(
int element_instance_id,
int embedder_render_process_id,
int embedder_render_frame_id,
int32_t plugin_frame_routing_id,
const gfx::Size& element_size,
mime_handler::BeforeUnloadControlPtrInfo before_unload_control,
bool is_full_page_plugin,
WebContents* web_contents) {
auto* guest_view = MimeHandlerViewGuest::FromWebContents(web_contents);
if (!guest_view)
return;
guest_view->SetBeforeUnloadController(std::move(before_unload_control));
int guest_instance_id = guest_view->guest_instance_id();
auto* rfh = RenderFrameHost::FromID(embedder_render_process_id,
embedder_render_frame_id);
if (!rfh)
return;
guest_view->SetEmbedderFrame(embedder_render_process_id,
embedder_render_frame_id);
base::DictionaryValue attach_params;
attach_params.SetInteger(guest_view::kElementWidth, element_size.width());
attach_params.SetInteger(guest_view::kElementHeight, element_size.height());
auto* manager = GuestViewManager::FromBrowserContext(browser_context_);
if (!manager) {
guest_view::bad_message::ReceivedBadMessage(
this,
guest_view::bad_message::GVMF_UNEXPECTED_MESSAGE_BEFORE_GVM_CREATION);
guest_view->Destroy(true);
return;
}
manager->AttachGuest(embedder_render_process_id, element_instance_id,
guest_instance_id, attach_params);
if (!content::MimeHandlerViewMode::UsesCrossProcessFrame()) {
rfh->Send(new ExtensionsGuestViewMsg_CreateMimeHandlerViewGuestACK(
element_instance_id));
return;
}
| 173,045 |
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 long BlockGroup::GetNextTimeCode() const
{
return m_next;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long BlockGroup::GetNextTimeCode() const
| 174,348 |
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 WriteTXTImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent],
colorspace[MagickPathExtent],
tuple[MagickPathExtent];
MagickBooleanType
status;
MagickOffsetType
scene;
PixelInfo
pixel;
register const Quantum
*p;
register ssize_t
x;
ssize_t
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
ComplianceType
compliance;
const char
*value;
(void) CopyMagickString(colorspace,CommandOptionToMnemonic(
MagickColorspaceOptions,(ssize_t) image->colorspace),MagickPathExtent);
LocaleLower(colorspace);
image->depth=GetImageQuantumDepth(image,MagickTrue);
if (image->alpha_trait != UndefinedPixelTrait)
(void) ConcatenateMagickString(colorspace,"a",MagickPathExtent);
compliance=NoCompliance;
value=GetImageOption(image_info,"txt:compliance");
if (value != (char *) NULL)
compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions,
MagickFalse,value);
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") != 0)
{
size_t
depth;
depth=compliance == SVGCompliance ? image->depth :
MAGICKCORE_QUANTUM_DEPTH;
(void) FormatLocaleString(buffer,MagickPathExtent,
"# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n",(double)
image->columns,(double) image->rows,(double) ((MagickOffsetType)
GetQuantumRange(depth)),colorspace);
(void) WriteBlobString(image,buffer);
}
GetPixelInfo(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,p,&pixel);
if (pixel.colorspace == LabColorspace)
{
pixel.green-=(QuantumRange+1)/2.0;
pixel.blue-=(QuantumRange+1)/2.0;
}
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") == 0)
{
/*
Sparse-color format.
*/
if (GetPixelAlpha(image,p) == (Quantum) OpaqueAlpha)
{
GetColorTuple(&pixel,MagickFalse,tuple);
(void) FormatLocaleString(buffer,MagickPathExtent,
"%.20g,%.20g,",(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
}
p+=GetPixelChannels(image);
continue;
}
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g,%.20g: ",
(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(tuple,"(",MagickPathExtent);
if (pixel.colorspace == GRAYColorspace)
ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance,
tuple);
else
{
ConcatenateColorComponent(&pixel,RedPixelChannel,compliance,tuple);
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,GreenPixelChannel,compliance,
tuple);
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,BluePixelChannel,compliance,tuple);
}
if (pixel.colorspace == CMYKColorspace)
{
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,BlackPixelChannel,compliance,
tuple);
}
if (pixel.alpha_trait != UndefinedPixelTrait)
{
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,AlphaPixelChannel,compliance,
tuple);
}
(void) ConcatenateMagickString(tuple,")",MagickPathExtent);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
GetColorTuple(&pixel,MagickTrue,tuple);
(void) FormatLocaleString(buffer,MagickPathExtent,"%s",tuple);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image," ");
(void) QueryColorname(image,&pixel,SVGCompliance,tuple,exception);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image,"\n");
p+=GetPixelChannels(image);
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/298
CWE ID: CWE-476 | static MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent],
colorspace[MagickPathExtent],
tuple[MagickPathExtent];
MagickBooleanType
status;
MagickOffsetType
scene;
PixelInfo
pixel;
register const Quantum
*p;
register ssize_t
x;
ssize_t
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
ComplianceType
compliance;
const char
*value;
(void) CopyMagickString(colorspace,CommandOptionToMnemonic(
MagickColorspaceOptions,(ssize_t) image->colorspace),MagickPathExtent);
LocaleLower(colorspace);
image->depth=GetImageQuantumDepth(image,MagickTrue);
if (image->alpha_trait != UndefinedPixelTrait)
(void) ConcatenateMagickString(colorspace,"a",MagickPathExtent);
compliance=NoCompliance;
value=GetImageOption(image_info,"txt:compliance");
if (value != (char *) NULL)
compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions,
MagickFalse,value);
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") != 0)
{
size_t
depth;
depth=compliance == SVGCompliance ? image->depth :
MAGICKCORE_QUANTUM_DEPTH;
(void) FormatLocaleString(buffer,MagickPathExtent,
"# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n",(double)
image->columns,(double) image->rows,(double) ((MagickOffsetType)
GetQuantumRange(depth)),colorspace);
(void) WriteBlobString(image,buffer);
}
GetPixelInfo(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,p,&pixel);
if (pixel.colorspace == LabColorspace)
{
pixel.green-=(QuantumRange+1)/2.0;
pixel.blue-=(QuantumRange+1)/2.0;
}
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") == 0)
{
/*
Sparse-color format.
*/
if (GetPixelAlpha(image,p) == (Quantum) OpaqueAlpha)
{
GetColorTuple(&pixel,MagickFalse,tuple);
(void) FormatLocaleString(buffer,MagickPathExtent,
"%.20g,%.20g,",(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
}
p+=GetPixelChannels(image);
continue;
}
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g,%.20g: ",
(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(tuple,"(",MagickPathExtent);
if (pixel.colorspace == GRAYColorspace)
ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance,tuple);
else
{
ConcatenateColorComponent(&pixel,RedPixelChannel,compliance,tuple);
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,GreenPixelChannel,compliance,
tuple);
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,BluePixelChannel,compliance,tuple);
}
if (pixel.colorspace == CMYKColorspace)
{
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,BlackPixelChannel,compliance,
tuple);
}
if (pixel.alpha_trait != UndefinedPixelTrait)
{
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,AlphaPixelChannel,compliance,
tuple);
}
(void) ConcatenateMagickString(tuple,")",MagickPathExtent);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
GetColorTuple(&pixel,MagickTrue,tuple);
(void) FormatLocaleString(buffer,MagickPathExtent,"%s",tuple);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image," ");
(void) QueryColorname(image,&pixel,SVGCompliance,tuple,exception);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image,"\n");
p+=GetPixelChannels(image);
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| 168,680 |
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: polkit_backend_session_monitor_get_user_for_subject (PolkitBackendSessionMonitor *monitor,
PolkitSubject *subject,
GError **error)
{
PolkitIdentity *ret;
guint32 uid;
ret = NULL;
if (POLKIT_IS_UNIX_PROCESS (subject))
{
uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (subject));
if ((gint) uid == -1)
{
g_set_error (error,
POLKIT_ERROR,
g_set_error (error,
"Unix process subject does not have uid set");
goto out;
}
ret = polkit_unix_user_new (uid);
}
else if (POLKIT_IS_SYSTEM_BUS_NAME (subject))
{
ret = (PolkitIdentity*)polkit_system_bus_name_get_user_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, error);
}
else if (POLKIT_IS_UNIX_SESSION (subject))
{
if (sd_session_get_uid (polkit_unix_session_get_session_id (POLKIT_UNIX_SESSION (subject)), &uid) < 0)
{
polkit_backend_session_monitor_get_session_for_subject (PolkitBackendSessionMonitor *monitor,
PolkitSubject *subject,
GError **error)
{
PolkitUnixProcess *tmp_process = NULL;
}
ret = polkit_unix_user_new (uid);
}
out:
return ret;
}
if (!tmp_process)
goto out;
process = tmp_process;
}
Commit Message:
CWE ID: CWE-200 | polkit_backend_session_monitor_get_user_for_subject (PolkitBackendSessionMonitor *monitor,
PolkitSubject *subject,
gboolean *result_matches,
GError **error)
{
PolkitIdentity *ret;
gboolean matches;
ret = NULL;
matches = FALSE;
if (POLKIT_IS_UNIX_PROCESS (subject))
{
gint subject_uid, current_uid;
GError *local_error;
subject_uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (subject));
if (subject_uid == -1)
{
g_set_error (error,
POLKIT_ERROR,
g_set_error (error,
"Unix process subject does not have uid set");
goto out;
}
local_error = NULL;
current_uid = polkit_unix_process_get_racy_uid__ (POLKIT_UNIX_PROCESS (subject), &local_error);
if (local_error != NULL)
{
g_propagate_error (error, local_error);
goto out;
}
ret = polkit_unix_user_new (subject_uid);
matches = (subject_uid == current_uid);
}
else if (POLKIT_IS_SYSTEM_BUS_NAME (subject))
{
ret = (PolkitIdentity*)polkit_system_bus_name_get_user_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, error);
matches = TRUE;
}
else if (POLKIT_IS_UNIX_SESSION (subject))
{
uid_t uid;
if (sd_session_get_uid (polkit_unix_session_get_session_id (POLKIT_UNIX_SESSION (subject)), &uid) < 0)
{
polkit_backend_session_monitor_get_session_for_subject (PolkitBackendSessionMonitor *monitor,
PolkitSubject *subject,
GError **error)
{
PolkitUnixProcess *tmp_process = NULL;
}
ret = polkit_unix_user_new (uid);
matches = TRUE;
}
out:
if (result_matches != NULL)
{
*result_matches = matches;
}
return ret;
}
if (!tmp_process)
goto out;
process = tmp_process;
}
| 165,289 |
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 DownloadController::OnDownloadStarted(
DownloadItem* download_item) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
WebContents* web_contents = download_item->GetWebContents();
if (!web_contents)
return;
download_item->AddObserver(this);
ChromeDownloadDelegate::FromWebContents(web_contents)->OnDownloadStarted(
download_item->GetTargetFilePath().BaseName().value(),
download_item->GetMimeType());
}
Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack
The only exception is OMA DRM download.
And it only applies to context menu download interception.
Clean up the remaining unused code now.
BUG=647755
Review-Url: https://codereview.chromium.org/2371773003
Cr-Commit-Position: refs/heads/master@{#421332}
CWE ID: CWE-254 | void DownloadController::OnDownloadStarted(
DownloadItem* download_item) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
WebContents* web_contents = download_item->GetWebContents();
if (!web_contents)
return;
download_item->AddObserver(this);
ChromeDownloadDelegate::FromWebContents(web_contents)->OnDownloadStarted(
download_item->GetTargetFilePath().BaseName().value());
}
| 171,882 |
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 Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
Handle<JSObject> object,
Handle<Object> value,
uint32_t start_from, uint32_t length) {
DCHECK(JSObject::PrototypeHasNoElements(isolate, *object));
Handle<Map> original_map = handle(object->map(), isolate);
Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()),
isolate);
for (uint32_t k = start_from; k < length; ++k) {
uint32_t entry = GetEntryForIndexImpl(isolate, *object, *parameter_map, k,
ALL_PROPERTIES);
if (entry == kMaxUInt32) {
continue;
}
Handle<Object> element_k =
Subclass::GetImpl(isolate, *parameter_map, entry);
if (element_k->IsAccessorPair()) {
LookupIterator it(isolate, object, k, LookupIterator::OWN);
DCHECK(it.IsFound());
DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k,
Object::GetPropertyWithAccessor(&it),
Nothing<int64_t>());
if (value->StrictEquals(*element_k)) {
return Just<int64_t>(k);
}
if (object->map() != *original_map) {
return IndexOfValueSlowPath(isolate, object, value, k + 1, length);
}
} else if (value->StrictEquals(*element_k)) {
return Just<int64_t>(k);
}
}
return Just<int64_t>(-1);
}
Commit Message: Backport: Fix Object.entries/values with changing elements
Bug: 111274046
Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \
/data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest
Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb
(cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99)
CWE ID: CWE-704 | static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
Handle<JSObject> object,
Handle<Object> value,
uint32_t start_from, uint32_t length) {
DCHECK(JSObject::PrototypeHasNoElements(isolate, *object));
Handle<Map> original_map(object->map(), isolate);
Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()),
isolate);
for (uint32_t k = start_from; k < length; ++k) {
DCHECK_EQ(object->map(), *original_map);
uint32_t entry = GetEntryForIndexImpl(isolate, *object, *parameter_map, k,
ALL_PROPERTIES);
if (entry == kMaxUInt32) {
continue;
}
Handle<Object> element_k =
Subclass::GetImpl(isolate, *parameter_map, entry);
if (element_k->IsAccessorPair()) {
LookupIterator it(isolate, object, k, LookupIterator::OWN);
DCHECK(it.IsFound());
DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k,
Object::GetPropertyWithAccessor(&it),
Nothing<int64_t>());
if (value->StrictEquals(*element_k)) {
return Just<int64_t>(k);
}
if (object->map() != *original_map) {
return IndexOfValueSlowPath(isolate, object, value, k + 1, length);
}
} else if (value->StrictEquals(*element_k)) {
return Just<int64_t>(k);
}
}
return Just<int64_t>(-1);
}
| 174,099 |
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 tcp_v6_send_synack(const struct sock *sk, struct dst_entry *dst,
struct flowi *fl,
struct request_sock *req,
struct tcp_fastopen_cookie *foc,
bool attach_req)
{
struct inet_request_sock *ireq = inet_rsk(req);
struct ipv6_pinfo *np = inet6_sk(sk);
struct flowi6 *fl6 = &fl->u.ip6;
struct sk_buff *skb;
int err = -ENOMEM;
/* First, grab a route. */
if (!dst && (dst = inet6_csk_route_req(sk, fl6, req,
IPPROTO_TCP)) == NULL)
goto done;
skb = tcp_make_synack(sk, dst, req, foc, attach_req);
if (skb) {
__tcp_v6_send_check(skb, &ireq->ir_v6_loc_addr,
&ireq->ir_v6_rmt_addr);
fl6->daddr = ireq->ir_v6_rmt_addr;
if (np->repflow && ireq->pktopts)
fl6->flowlabel = ip6_flowlabel(ipv6_hdr(ireq->pktopts));
err = ip6_xmit(sk, skb, fl6, np->opt, np->tclass);
err = net_xmit_eval(err);
}
done:
return err;
}
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 int tcp_v6_send_synack(const struct sock *sk, struct dst_entry *dst,
struct flowi *fl,
struct request_sock *req,
struct tcp_fastopen_cookie *foc,
bool attach_req)
{
struct inet_request_sock *ireq = inet_rsk(req);
struct ipv6_pinfo *np = inet6_sk(sk);
struct flowi6 *fl6 = &fl->u.ip6;
struct sk_buff *skb;
int err = -ENOMEM;
/* First, grab a route. */
if (!dst && (dst = inet6_csk_route_req(sk, fl6, req,
IPPROTO_TCP)) == NULL)
goto done;
skb = tcp_make_synack(sk, dst, req, foc, attach_req);
if (skb) {
__tcp_v6_send_check(skb, &ireq->ir_v6_loc_addr,
&ireq->ir_v6_rmt_addr);
fl6->daddr = ireq->ir_v6_rmt_addr;
if (np->repflow && ireq->pktopts)
fl6->flowlabel = ip6_flowlabel(ipv6_hdr(ireq->pktopts));
err = ip6_xmit(sk, skb, fl6, rcu_dereference(np->opt),
np->tclass);
err = net_xmit_eval(err);
}
done:
return err;
}
| 167,341 |
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 RenderWidgetHostImpl::Destroy(bool also_delete) {
DCHECK(!destroyed_);
destroyed_ = true;
NotificationService::current()->Notify(
NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, Source<RenderWidgetHost>(this),
NotificationService::NoDetails());
if (view_) {
view_->Destroy();
view_.reset();
}
process_->RemoveRoute(routing_id_);
g_routing_id_widget_map.Get().erase(
RenderWidgetHostID(process_->GetID(), routing_id_));
if (delegate_)
delegate_->RenderWidgetDeleted(this);
if (also_delete)
delete this;
}
Commit Message: Check that RWHI isn't deleted manually while owned by a scoped_ptr in RVHI
BUG=590284
Review URL: https://codereview.chromium.org/1747183002
Cr-Commit-Position: refs/heads/master@{#378844}
CWE ID: | void RenderWidgetHostImpl::Destroy(bool also_delete) {
DCHECK(!destroyed_);
destroyed_ = true;
NotificationService::current()->Notify(
NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, Source<RenderWidgetHost>(this),
NotificationService::NoDetails());
if (view_) {
view_->Destroy();
view_.reset();
}
process_->RemoveRoute(routing_id_);
g_routing_id_widget_map.Get().erase(
RenderWidgetHostID(process_->GetID(), routing_id_));
if (delegate_)
delegate_->RenderWidgetDeleted(this);
if (also_delete) {
CHECK(!owner_delegate_);
delete this;
}
}
| 172,116 |
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 ocfs2_setattr(struct dentry *dentry, struct iattr *attr)
{
int status = 0, size_change;
int inode_locked = 0;
struct inode *inode = d_inode(dentry);
struct super_block *sb = inode->i_sb;
struct ocfs2_super *osb = OCFS2_SB(sb);
struct buffer_head *bh = NULL;
handle_t *handle = NULL;
struct dquot *transfer_to[MAXQUOTAS] = { };
int qtype;
int had_lock;
struct ocfs2_lock_holder oh;
trace_ocfs2_setattr(inode, dentry,
(unsigned long long)OCFS2_I(inode)->ip_blkno,
dentry->d_name.len, dentry->d_name.name,
attr->ia_valid, attr->ia_mode,
from_kuid(&init_user_ns, attr->ia_uid),
from_kgid(&init_user_ns, attr->ia_gid));
/* ensuring we don't even attempt to truncate a symlink */
if (S_ISLNK(inode->i_mode))
attr->ia_valid &= ~ATTR_SIZE;
#define OCFS2_VALID_ATTRS (ATTR_ATIME | ATTR_MTIME | ATTR_CTIME | ATTR_SIZE \
| ATTR_GID | ATTR_UID | ATTR_MODE)
if (!(attr->ia_valid & OCFS2_VALID_ATTRS))
return 0;
status = setattr_prepare(dentry, attr);
if (status)
return status;
if (is_quota_modification(inode, attr)) {
status = dquot_initialize(inode);
if (status)
return status;
}
size_change = S_ISREG(inode->i_mode) && attr->ia_valid & ATTR_SIZE;
if (size_change) {
status = ocfs2_rw_lock(inode, 1);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
had_lock = ocfs2_inode_lock_tracker(inode, &bh, 1, &oh);
if (had_lock < 0) {
status = had_lock;
goto bail_unlock_rw;
} else if (had_lock) {
/*
* As far as we know, ocfs2_setattr() could only be the first
* VFS entry point in the call chain of recursive cluster
* locking issue.
*
* For instance:
* chmod_common()
* notify_change()
* ocfs2_setattr()
* posix_acl_chmod()
* ocfs2_iop_get_acl()
*
* But, we're not 100% sure if it's always true, because the
* ordering of the VFS entry points in the call chain is out
* of our control. So, we'd better dump the stack here to
* catch the other cases of recursive locking.
*/
mlog(ML_ERROR, "Another case of recursive locking:\n");
dump_stack();
}
inode_locked = 1;
if (size_change) {
status = inode_newsize_ok(inode, attr->ia_size);
if (status)
goto bail_unlock;
inode_dio_wait(inode);
if (i_size_read(inode) >= attr->ia_size) {
if (ocfs2_should_order_data(inode)) {
status = ocfs2_begin_ordered_truncate(inode,
attr->ia_size);
if (status)
goto bail_unlock;
}
status = ocfs2_truncate_file(inode, bh, attr->ia_size);
} else
status = ocfs2_extend_file(inode, bh, attr->ia_size);
if (status < 0) {
if (status != -ENOSPC)
mlog_errno(status);
status = -ENOSPC;
goto bail_unlock;
}
}
if ((attr->ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
(attr->ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
/*
* Gather pointers to quota structures so that allocation /
* freeing of quota structures happens here and not inside
* dquot_transfer() where we have problems with lock ordering
*/
if (attr->ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)
&& OCFS2_HAS_RO_COMPAT_FEATURE(sb,
OCFS2_FEATURE_RO_COMPAT_USRQUOTA)) {
transfer_to[USRQUOTA] = dqget(sb, make_kqid_uid(attr->ia_uid));
if (IS_ERR(transfer_to[USRQUOTA])) {
status = PTR_ERR(transfer_to[USRQUOTA]);
goto bail_unlock;
}
}
if (attr->ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid)
&& OCFS2_HAS_RO_COMPAT_FEATURE(sb,
OCFS2_FEATURE_RO_COMPAT_GRPQUOTA)) {
transfer_to[GRPQUOTA] = dqget(sb, make_kqid_gid(attr->ia_gid));
if (IS_ERR(transfer_to[GRPQUOTA])) {
status = PTR_ERR(transfer_to[GRPQUOTA]);
goto bail_unlock;
}
}
handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS +
2 * ocfs2_quota_trans_credits(sb));
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
mlog_errno(status);
goto bail_unlock;
}
status = __dquot_transfer(inode, transfer_to);
if (status < 0)
goto bail_commit;
} else {
handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
mlog_errno(status);
goto bail_unlock;
}
}
setattr_copy(inode, attr);
mark_inode_dirty(inode);
status = ocfs2_mark_inode_dirty(handle, inode, bh);
if (status < 0)
mlog_errno(status);
bail_commit:
ocfs2_commit_trans(osb, handle);
bail_unlock:
if (status && inode_locked) {
ocfs2_inode_unlock_tracker(inode, 1, &oh, had_lock);
inode_locked = 0;
}
bail_unlock_rw:
if (size_change)
ocfs2_rw_unlock(inode, 1);
bail:
/* Release quota pointers in case we acquired them */
for (qtype = 0; qtype < OCFS2_MAXQUOTAS; qtype++)
dqput(transfer_to[qtype]);
if (!status && attr->ia_valid & ATTR_MODE) {
status = ocfs2_acl_chmod(inode, bh);
if (status < 0)
mlog_errno(status);
}
if (inode_locked)
ocfs2_inode_unlock_tracker(inode, 1, &oh, had_lock);
brelse(bh);
return status;
}
Commit Message: ocfs2: should wait dio before inode lock in ocfs2_setattr()
we should wait dio requests to finish before inode lock in
ocfs2_setattr(), otherwise the following deadlock will happen:
process 1 process 2 process 3
truncate file 'A' end_io of writing file 'A' receiving the bast messages
ocfs2_setattr
ocfs2_inode_lock_tracker
ocfs2_inode_lock_full
inode_dio_wait
__inode_dio_wait
-->waiting for all dio
requests finish
dlm_proxy_ast_handler
dlm_do_local_bast
ocfs2_blocking_ast
ocfs2_generic_handle_bast
set OCFS2_LOCK_BLOCKED flag
dio_end_io
dio_bio_end_aio
dio_complete
ocfs2_dio_end_io
ocfs2_dio_end_io_write
ocfs2_inode_lock
__ocfs2_cluster_lock
ocfs2_wait_for_mask
-->waiting for OCFS2_LOCK_BLOCKED
flag to be cleared, that is waiting
for 'process 1' unlocking the inode lock
inode_dio_end
-->here dec the i_dio_count, but will never
be called, so a deadlock happened.
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Alex Chen <[email protected]>
Reviewed-by: Jun Piao <[email protected]>
Reviewed-by: Joseph Qi <[email protected]>
Acked-by: Changwei Ge <[email protected]>
Cc: Mark Fasheh <[email protected]>
Cc: Joel Becker <[email protected]>
Cc: Junxiao Bi <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: | int ocfs2_setattr(struct dentry *dentry, struct iattr *attr)
{
int status = 0, size_change;
int inode_locked = 0;
struct inode *inode = d_inode(dentry);
struct super_block *sb = inode->i_sb;
struct ocfs2_super *osb = OCFS2_SB(sb);
struct buffer_head *bh = NULL;
handle_t *handle = NULL;
struct dquot *transfer_to[MAXQUOTAS] = { };
int qtype;
int had_lock;
struct ocfs2_lock_holder oh;
trace_ocfs2_setattr(inode, dentry,
(unsigned long long)OCFS2_I(inode)->ip_blkno,
dentry->d_name.len, dentry->d_name.name,
attr->ia_valid, attr->ia_mode,
from_kuid(&init_user_ns, attr->ia_uid),
from_kgid(&init_user_ns, attr->ia_gid));
/* ensuring we don't even attempt to truncate a symlink */
if (S_ISLNK(inode->i_mode))
attr->ia_valid &= ~ATTR_SIZE;
#define OCFS2_VALID_ATTRS (ATTR_ATIME | ATTR_MTIME | ATTR_CTIME | ATTR_SIZE \
| ATTR_GID | ATTR_UID | ATTR_MODE)
if (!(attr->ia_valid & OCFS2_VALID_ATTRS))
return 0;
status = setattr_prepare(dentry, attr);
if (status)
return status;
if (is_quota_modification(inode, attr)) {
status = dquot_initialize(inode);
if (status)
return status;
}
size_change = S_ISREG(inode->i_mode) && attr->ia_valid & ATTR_SIZE;
if (size_change) {
/*
* Here we should wait dio to finish before inode lock
* to avoid a deadlock between ocfs2_setattr() and
* ocfs2_dio_end_io_write()
*/
inode_dio_wait(inode);
status = ocfs2_rw_lock(inode, 1);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
had_lock = ocfs2_inode_lock_tracker(inode, &bh, 1, &oh);
if (had_lock < 0) {
status = had_lock;
goto bail_unlock_rw;
} else if (had_lock) {
/*
* As far as we know, ocfs2_setattr() could only be the first
* VFS entry point in the call chain of recursive cluster
* locking issue.
*
* For instance:
* chmod_common()
* notify_change()
* ocfs2_setattr()
* posix_acl_chmod()
* ocfs2_iop_get_acl()
*
* But, we're not 100% sure if it's always true, because the
* ordering of the VFS entry points in the call chain is out
* of our control. So, we'd better dump the stack here to
* catch the other cases of recursive locking.
*/
mlog(ML_ERROR, "Another case of recursive locking:\n");
dump_stack();
}
inode_locked = 1;
if (size_change) {
status = inode_newsize_ok(inode, attr->ia_size);
if (status)
goto bail_unlock;
if (i_size_read(inode) >= attr->ia_size) {
if (ocfs2_should_order_data(inode)) {
status = ocfs2_begin_ordered_truncate(inode,
attr->ia_size);
if (status)
goto bail_unlock;
}
status = ocfs2_truncate_file(inode, bh, attr->ia_size);
} else
status = ocfs2_extend_file(inode, bh, attr->ia_size);
if (status < 0) {
if (status != -ENOSPC)
mlog_errno(status);
status = -ENOSPC;
goto bail_unlock;
}
}
if ((attr->ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
(attr->ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
/*
* Gather pointers to quota structures so that allocation /
* freeing of quota structures happens here and not inside
* dquot_transfer() where we have problems with lock ordering
*/
if (attr->ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)
&& OCFS2_HAS_RO_COMPAT_FEATURE(sb,
OCFS2_FEATURE_RO_COMPAT_USRQUOTA)) {
transfer_to[USRQUOTA] = dqget(sb, make_kqid_uid(attr->ia_uid));
if (IS_ERR(transfer_to[USRQUOTA])) {
status = PTR_ERR(transfer_to[USRQUOTA]);
goto bail_unlock;
}
}
if (attr->ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid)
&& OCFS2_HAS_RO_COMPAT_FEATURE(sb,
OCFS2_FEATURE_RO_COMPAT_GRPQUOTA)) {
transfer_to[GRPQUOTA] = dqget(sb, make_kqid_gid(attr->ia_gid));
if (IS_ERR(transfer_to[GRPQUOTA])) {
status = PTR_ERR(transfer_to[GRPQUOTA]);
goto bail_unlock;
}
}
handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS +
2 * ocfs2_quota_trans_credits(sb));
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
mlog_errno(status);
goto bail_unlock;
}
status = __dquot_transfer(inode, transfer_to);
if (status < 0)
goto bail_commit;
} else {
handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
mlog_errno(status);
goto bail_unlock;
}
}
setattr_copy(inode, attr);
mark_inode_dirty(inode);
status = ocfs2_mark_inode_dirty(handle, inode, bh);
if (status < 0)
mlog_errno(status);
bail_commit:
ocfs2_commit_trans(osb, handle);
bail_unlock:
if (status && inode_locked) {
ocfs2_inode_unlock_tracker(inode, 1, &oh, had_lock);
inode_locked = 0;
}
bail_unlock_rw:
if (size_change)
ocfs2_rw_unlock(inode, 1);
bail:
/* Release quota pointers in case we acquired them */
for (qtype = 0; qtype < OCFS2_MAXQUOTAS; qtype++)
dqput(transfer_to[qtype]);
if (!status && attr->ia_valid & ATTR_MODE) {
status = ocfs2_acl_chmod(inode, bh);
if (status < 0)
mlog_errno(status);
}
if (inode_locked)
ocfs2_inode_unlock_tracker(inode, 1, &oh, had_lock);
brelse(bh);
return status;
}
| 169,410 |
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 SUB_STATE_RETURN read_state_machine(SSL *s)
{
OSSL_STATEM *st = &s->statem;
int ret, mt;
unsigned long len = 0;
int (*transition) (SSL *s, int mt);
PACKET pkt;
MSG_PROCESS_RETURN(*process_message) (SSL *s, PACKET *pkt);
WORK_STATE(*post_process_message) (SSL *s, WORK_STATE wst);
unsigned long (*max_message_size) (SSL *s);
void (*cb) (const SSL *ssl, int type, int val) = NULL;
cb = get_callback(s);
if (s->server) {
transition = ossl_statem_server_read_transition;
process_message = ossl_statem_server_process_message;
max_message_size = ossl_statem_server_max_message_size;
post_process_message = ossl_statem_server_post_process_message;
} else {
transition = ossl_statem_client_read_transition;
process_message = ossl_statem_client_process_message;
max_message_size = ossl_statem_client_max_message_size;
post_process_message = ossl_statem_client_post_process_message;
}
if (st->read_state_first_init) {
s->first_packet = 1;
st->read_state_first_init = 0;
}
while (1) {
switch (st->read_state) {
case READ_STATE_HEADER:
/* Get the state the peer wants to move to */
if (SSL_IS_DTLS(s)) {
/*
* In DTLS we get the whole message in one go - header and body
*/
ret = dtls_get_message(s, &mt, &len);
} else {
ret = tls_get_message_header(s, &mt);
}
if (ret == 0) {
/* Could be non-blocking IO */
return SUB_STATE_ERROR;
}
if (cb != NULL) {
/* Notify callback of an impending state change */
if (s->server)
cb(s, SSL_CB_ACCEPT_LOOP, 1);
else
cb(s, SSL_CB_CONNECT_LOOP, 1);
}
/*
* Validate that we are allowed to move to the new state and move
* to that state if so
*/
if (!transition(s, mt)) {
ossl_statem_set_error(s);
return SUB_STATE_ERROR;
}
if (s->s3->tmp.message_size > max_message_size(s)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
return SUB_STATE_ERROR;
}
st->read_state = READ_STATE_BODY;
/* Fall through */
if (!PACKET_buf_init(&pkt, s->init_msg, len)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
return SUB_STATE_ERROR;
}
ret = process_message(s, &pkt);
/* Discard the packet data */
s->init_num = 0;
switch (ret) {
case MSG_PROCESS_ERROR:
return SUB_STATE_ERROR;
case MSG_PROCESS_FINISHED_READING:
if (SSL_IS_DTLS(s)) {
dtls1_stop_timer(s);
}
return SUB_STATE_FINISHED;
case MSG_PROCESS_CONTINUE_PROCESSING:
st->read_state = READ_STATE_POST_PROCESS;
st->read_state_work = WORK_MORE_A;
break;
default:
st->read_state = READ_STATE_HEADER;
break;
}
break;
case READ_STATE_POST_PROCESS:
st->read_state_work = post_process_message(s, st->read_state_work);
switch (st->read_state_work) {
default:
return SUB_STATE_ERROR;
case WORK_FINISHED_CONTINUE:
st->read_state = READ_STATE_HEADER;
break;
case WORK_FINISHED_STOP:
if (SSL_IS_DTLS(s)) {
dtls1_stop_timer(s);
}
return SUB_STATE_FINISHED;
}
break;
default:
/* Shouldn't happen */
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
ossl_statem_set_error(s);
return SUB_STATE_ERROR;
}
}
}
Commit Message:
CWE ID: CWE-400 | static SUB_STATE_RETURN read_state_machine(SSL *s)
{
OSSL_STATEM *st = &s->statem;
int ret, mt;
unsigned long len = 0;
int (*transition) (SSL *s, int mt);
PACKET pkt;
MSG_PROCESS_RETURN(*process_message) (SSL *s, PACKET *pkt);
WORK_STATE(*post_process_message) (SSL *s, WORK_STATE wst);
unsigned long (*max_message_size) (SSL *s);
void (*cb) (const SSL *ssl, int type, int val) = NULL;
cb = get_callback(s);
if (s->server) {
transition = ossl_statem_server_read_transition;
process_message = ossl_statem_server_process_message;
max_message_size = ossl_statem_server_max_message_size;
post_process_message = ossl_statem_server_post_process_message;
} else {
transition = ossl_statem_client_read_transition;
process_message = ossl_statem_client_process_message;
max_message_size = ossl_statem_client_max_message_size;
post_process_message = ossl_statem_client_post_process_message;
}
if (st->read_state_first_init) {
s->first_packet = 1;
st->read_state_first_init = 0;
}
while (1) {
switch (st->read_state) {
case READ_STATE_HEADER:
/* Get the state the peer wants to move to */
if (SSL_IS_DTLS(s)) {
/*
* In DTLS we get the whole message in one go - header and body
*/
ret = dtls_get_message(s, &mt, &len);
} else {
ret = tls_get_message_header(s, &mt);
}
if (ret == 0) {
/* Could be non-blocking IO */
return SUB_STATE_ERROR;
}
if (cb != NULL) {
/* Notify callback of an impending state change */
if (s->server)
cb(s, SSL_CB_ACCEPT_LOOP, 1);
else
cb(s, SSL_CB_CONNECT_LOOP, 1);
}
/*
* Validate that we are allowed to move to the new state and move
* to that state if so
*/
if (!transition(s, mt)) {
ossl_statem_set_error(s);
return SUB_STATE_ERROR;
}
if (s->s3->tmp.message_size > max_message_size(s)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
return SUB_STATE_ERROR;
}
/* dtls_get_message already did this */
if (!SSL_IS_DTLS(s)
&& s->s3->tmp.message_size > 0
&& !BUF_MEM_grow_clean(s->init_buf,
(int)s->s3->tmp.message_size
+ SSL3_HM_HEADER_LENGTH)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, ERR_R_BUF_LIB);
return SUB_STATE_ERROR;
}
st->read_state = READ_STATE_BODY;
/* Fall through */
if (!PACKET_buf_init(&pkt, s->init_msg, len)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
return SUB_STATE_ERROR;
}
ret = process_message(s, &pkt);
/* Discard the packet data */
s->init_num = 0;
switch (ret) {
case MSG_PROCESS_ERROR:
return SUB_STATE_ERROR;
case MSG_PROCESS_FINISHED_READING:
if (SSL_IS_DTLS(s)) {
dtls1_stop_timer(s);
}
return SUB_STATE_FINISHED;
case MSG_PROCESS_CONTINUE_PROCESSING:
st->read_state = READ_STATE_POST_PROCESS;
st->read_state_work = WORK_MORE_A;
break;
default:
st->read_state = READ_STATE_HEADER;
break;
}
break;
case READ_STATE_POST_PROCESS:
st->read_state_work = post_process_message(s, st->read_state_work);
switch (st->read_state_work) {
default:
return SUB_STATE_ERROR;
case WORK_FINISHED_CONTINUE:
st->read_state = READ_STATE_HEADER;
break;
case WORK_FINISHED_STOP:
if (SSL_IS_DTLS(s)) {
dtls1_stop_timer(s);
}
return SUB_STATE_FINISHED;
}
break;
default:
/* Shouldn't happen */
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
ossl_statem_set_error(s);
return SUB_STATE_ERROR;
}
}
}
| 164,962 |
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 long Cluster::GetTime() const
{
const long long tc = GetTimeCode();
if (tc < 0)
return tc;
const SegmentInfo* const pInfo = m_pSegment->GetInfo();
assert(pInfo);
const long long scale = pInfo->GetTimeCodeScale();
assert(scale >= 1);
const long long t = m_timecode * scale;
return t;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long Cluster::GetTime() const
| 174,362 |
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: DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len)
{
int i;
int ret = 0;
DefragInit();
/*
* Build the packets.
*/
int id = 1;
Packet *packets[17];
memset(packets, 0x00, sizeof(packets));
/*
* Original fragments.
*/
/* A*24 at 0. */
packets[0] = BuildTestPacket(id, 0, 1, 'A', 24);
/* B*15 at 32. */
packets[1] = BuildTestPacket(id, 32 >> 3, 1, 'B', 16);
/* C*24 at 48. */
packets[2] = BuildTestPacket(id, 48 >> 3, 1, 'C', 24);
/* D*8 at 80. */
packets[3] = BuildTestPacket(id, 80 >> 3, 1, 'D', 8);
/* E*16 at 104. */
packets[4] = BuildTestPacket(id, 104 >> 3, 1, 'E', 16);
/* F*24 at 120. */
packets[5] = BuildTestPacket(id, 120 >> 3, 1, 'F', 24);
/* G*16 at 144. */
packets[6] = BuildTestPacket(id, 144 >> 3, 1, 'G', 16);
/* H*16 at 160. */
packets[7] = BuildTestPacket(id, 160 >> 3, 1, 'H', 16);
/* I*8 at 176. */
packets[8] = BuildTestPacket(id, 176 >> 3, 1, 'I', 8);
/*
* Overlapping subsequent fragments.
*/
/* J*32 at 8. */
packets[9] = BuildTestPacket(id, 8 >> 3, 1, 'J', 32);
/* K*24 at 48. */
packets[10] = BuildTestPacket(id, 48 >> 3, 1, 'K', 24);
/* L*24 at 72. */
packets[11] = BuildTestPacket(id, 72 >> 3, 1, 'L', 24);
/* M*24 at 96. */
packets[12] = BuildTestPacket(id, 96 >> 3, 1, 'M', 24);
/* N*8 at 128. */
packets[13] = BuildTestPacket(id, 128 >> 3, 1, 'N', 8);
/* O*8 at 152. */
packets[14] = BuildTestPacket(id, 152 >> 3, 1, 'O', 8);
/* P*8 at 160. */
packets[15] = BuildTestPacket(id, 160 >> 3, 1, 'P', 8);
/* Q*16 at 176. */
packets[16] = BuildTestPacket(id, 176 >> 3, 0, 'Q', 16);
default_policy = policy;
/* Send all but the last. */
for (i = 0; i < 9; i++) {
Packet *tp = Defrag(NULL, NULL, packets[i], NULL);
if (tp != NULL) {
SCFree(tp);
goto end;
}
if (ENGINE_ISSET_EVENT(packets[i], IPV4_FRAG_OVERLAP)) {
goto end;
}
}
int overlap = 0;
for (; i < 16; i++) {
Packet *tp = Defrag(NULL, NULL, packets[i], NULL);
if (tp != NULL) {
SCFree(tp);
goto end;
}
if (ENGINE_ISSET_EVENT(packets[i], IPV4_FRAG_OVERLAP)) {
overlap++;
}
}
if (!overlap) {
goto end;
}
/* And now the last one. */
Packet *reassembled = Defrag(NULL, NULL, packets[16], NULL);
if (reassembled == NULL) {
goto end;
}
if (IPV4_GET_HLEN(reassembled) != 20) {
goto end;
}
if (IPV4_GET_IPLEN(reassembled) != 20 + 192) {
goto end;
}
if (memcmp(GET_PKT_DATA(reassembled) + 20, expected, expected_len) != 0) {
goto end;
}
SCFree(reassembled);
/* Make sure all frags were returned back to the pool. */
if (defrag_context->frag_pool->outstanding != 0) {
goto end;
}
ret = 1;
end:
for (i = 0; i < 17; i++) {
SCFree(packets[i]);
}
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358 | DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len)
{
int i;
int ret = 0;
DefragInit();
/*
* Build the packets.
*/
int id = 1;
Packet *packets[17];
memset(packets, 0x00, sizeof(packets));
/*
* Original fragments.
*/
/* A*24 at 0. */
packets[0] = BuildTestPacket(IPPROTO_ICMP, id, 0, 1, 'A', 24);
/* B*15 at 32. */
packets[1] = BuildTestPacket(IPPROTO_ICMP, id, 32 >> 3, 1, 'B', 16);
/* C*24 at 48. */
packets[2] = BuildTestPacket(IPPROTO_ICMP, id, 48 >> 3, 1, 'C', 24);
/* D*8 at 80. */
packets[3] = BuildTestPacket(IPPROTO_ICMP, id, 80 >> 3, 1, 'D', 8);
/* E*16 at 104. */
packets[4] = BuildTestPacket(IPPROTO_ICMP, id, 104 >> 3, 1, 'E', 16);
/* F*24 at 120. */
packets[5] = BuildTestPacket(IPPROTO_ICMP, id, 120 >> 3, 1, 'F', 24);
/* G*16 at 144. */
packets[6] = BuildTestPacket(IPPROTO_ICMP, id, 144 >> 3, 1, 'G', 16);
/* H*16 at 160. */
packets[7] = BuildTestPacket(IPPROTO_ICMP, id, 160 >> 3, 1, 'H', 16);
/* I*8 at 176. */
packets[8] = BuildTestPacket(IPPROTO_ICMP, id, 176 >> 3, 1, 'I', 8);
/*
* Overlapping subsequent fragments.
*/
/* J*32 at 8. */
packets[9] = BuildTestPacket(IPPROTO_ICMP, id, 8 >> 3, 1, 'J', 32);
/* K*24 at 48. */
packets[10] = BuildTestPacket(IPPROTO_ICMP, id, 48 >> 3, 1, 'K', 24);
/* L*24 at 72. */
packets[11] = BuildTestPacket(IPPROTO_ICMP, id, 72 >> 3, 1, 'L', 24);
/* M*24 at 96. */
packets[12] = BuildTestPacket(IPPROTO_ICMP, id, 96 >> 3, 1, 'M', 24);
/* N*8 at 128. */
packets[13] = BuildTestPacket(IPPROTO_ICMP, id, 128 >> 3, 1, 'N', 8);
/* O*8 at 152. */
packets[14] = BuildTestPacket(IPPROTO_ICMP, id, 152 >> 3, 1, 'O', 8);
/* P*8 at 160. */
packets[15] = BuildTestPacket(IPPROTO_ICMP, id, 160 >> 3, 1, 'P', 8);
/* Q*16 at 176. */
packets[16] = BuildTestPacket(IPPROTO_ICMP, id, 176 >> 3, 0, 'Q', 16);
default_policy = policy;
/* Send all but the last. */
for (i = 0; i < 9; i++) {
Packet *tp = Defrag(NULL, NULL, packets[i], NULL);
if (tp != NULL) {
SCFree(tp);
goto end;
}
if (ENGINE_ISSET_EVENT(packets[i], IPV4_FRAG_OVERLAP)) {
goto end;
}
}
int overlap = 0;
for (; i < 16; i++) {
Packet *tp = Defrag(NULL, NULL, packets[i], NULL);
if (tp != NULL) {
SCFree(tp);
goto end;
}
if (ENGINE_ISSET_EVENT(packets[i], IPV4_FRAG_OVERLAP)) {
overlap++;
}
}
if (!overlap) {
goto end;
}
/* And now the last one. */
Packet *reassembled = Defrag(NULL, NULL, packets[16], NULL);
if (reassembled == NULL) {
goto end;
}
if (IPV4_GET_HLEN(reassembled) != 20) {
goto end;
}
if (IPV4_GET_IPLEN(reassembled) != 20 + 192) {
goto end;
}
if (memcmp(GET_PKT_DATA(reassembled) + 20, expected, expected_len) != 0) {
goto end;
}
SCFree(reassembled);
/* Make sure all frags were returned back to the pool. */
if (defrag_context->frag_pool->outstanding != 0) {
goto end;
}
ret = 1;
end:
for (i = 0; i < 17; i++) {
SCFree(packets[i]);
}
DefragDestroy();
return ret;
}
| 168,295 |
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* GetInstance() {
return Singleton<InputMethodStatusConnection,
LeakySingletonTraits<InputMethodStatusConnection> >::get();
}
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* GetInstance() {
virtual void Connect() {
MaybeRestoreConnections();
}
| 170,535 |
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 Track* Tracks::GetTrackByIndex(unsigned long idx) const
{
const ptrdiff_t count = m_trackEntriesEnd - m_trackEntries;
if (idx >= static_cast<unsigned long>(count))
return NULL;
return m_trackEntries[idx];
}
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 Track* Tracks::GetTrackByIndex(unsigned long idx) const
return m_trackEntries[idx];
}
| 174,370 |
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::unique_ptr<views::Border> AutofillPopupBaseView::CreateBorder() {
auto border = std::make_unique<views::BubbleBorder>(
views::BubbleBorder::NONE, views::BubbleBorder::SMALL_SHADOW,
SK_ColorWHITE);
border->SetCornerRadius(GetCornerRadius());
border->set_md_shadow_elevation(
ChromeLayoutProvider::Get()->GetShadowElevationMetric(
views::EMPHASIS_MEDIUM));
return border;
}
Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature.
Bug: 906135,831603
Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499
Reviewed-on: https://chromium-review.googlesource.com/c/1387124
Reviewed-by: Robert Kaplow <[email protected]>
Reviewed-by: Vasilii Sukhanov <[email protected]>
Reviewed-by: Fabio Tirelo <[email protected]>
Reviewed-by: Tommy Martino <[email protected]>
Commit-Queue: Mathieu Perreault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621360}
CWE ID: CWE-416 | std::unique_ptr<views::Border> AutofillPopupBaseView::CreateBorder() {
| 172,094 |
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 ChromeOSSendHandwritingStroke(InputMethodStatusConnection* connection,
const HandwritingStroke& stroke) {
g_return_if_fail(connection);
connection->SendHandwritingStroke(stroke);
}
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 | void ChromeOSSendHandwritingStroke(InputMethodStatusConnection* connection,
virtual void SendHandwritingStroke(const HandwritingStroke& stroke) {
}
virtual void CancelHandwriting(int n_strokes) {
}
};
IBusController* IBusController::Create() {
#if defined(HAVE_IBUS)
return IBusControllerImpl::GetInstance();
#else
return new IBusControllerStubImpl;
#endif
}
| 170,525 |
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 AffiliationFetcher::ParseResponse(
AffiliationFetcherDelegate::Result* result) const {
std::string serialized_response;
if (!fetcher_->GetResponseAsString(&serialized_response)) {
NOTREACHED();
}
affiliation_pb::LookupAffiliationResponse response;
if (!response.ParseFromString(serialized_response))
return false;
result->reserve(requested_facet_uris_.size());
std::map<FacetURI, size_t> facet_uri_to_class_index;
for (int i = 0; i < response.affiliation_size(); ++i) {
const affiliation_pb::Affiliation& equivalence_class(
response.affiliation(i));
AffiliatedFacets affiliated_uris;
for (int j = 0; j < equivalence_class.facet_size(); ++j) {
const std::string& uri_spec(equivalence_class.facet(j));
FacetURI uri = FacetURI::FromPotentiallyInvalidSpec(uri_spec);
if (!uri.is_valid())
continue;
affiliated_uris.push_back(uri);
}
if (affiliated_uris.empty())
continue;
for (const FacetURI& uri : affiliated_uris) {
if (!facet_uri_to_class_index.count(uri))
facet_uri_to_class_index[uri] = result->size();
if (facet_uri_to_class_index[uri] !=
facet_uri_to_class_index[affiliated_uris[0]]) {
return false;
}
}
if (facet_uri_to_class_index[affiliated_uris[0]] == result->size())
result->push_back(affiliated_uris);
}
for (const FacetURI& uri : requested_facet_uris_) {
if (!facet_uri_to_class_index.count(uri))
result->push_back(AffiliatedFacets(1, uri));
}
return true;
}
Commit Message: Update AffiliationFetcher to use new Affiliation API wire format.
The new format is not backward compatible with the old one, therefore this CL updates the client side protobuf definitions to be in line with the API definition. However, this CL does not yet make use of any additional fields introduced in the new wire format.
BUG=437865
Review URL: https://codereview.chromium.org/996613002
Cr-Commit-Position: refs/heads/master@{#319860}
CWE ID: CWE-119 | bool AffiliationFetcher::ParseResponse(
AffiliationFetcherDelegate::Result* result) const {
std::string serialized_response;
if (!fetcher_->GetResponseAsString(&serialized_response)) {
NOTREACHED();
}
affiliation_pb::LookupAffiliationResponse response;
if (!response.ParseFromString(serialized_response))
return false;
result->reserve(requested_facet_uris_.size());
std::map<FacetURI, size_t> facet_uri_to_class_index;
for (int i = 0; i < response.affiliation_size(); ++i) {
const affiliation_pb::Affiliation& equivalence_class(
response.affiliation(i));
AffiliatedFacets affiliated_uris;
for (int j = 0; j < equivalence_class.facet_size(); ++j) {
const std::string& uri_spec(equivalence_class.facet(j).id());
FacetURI uri = FacetURI::FromPotentiallyInvalidSpec(uri_spec);
if (!uri.is_valid())
continue;
affiliated_uris.push_back(uri);
}
if (affiliated_uris.empty())
continue;
for (const FacetURI& uri : affiliated_uris) {
if (!facet_uri_to_class_index.count(uri))
facet_uri_to_class_index[uri] = result->size();
if (facet_uri_to_class_index[uri] !=
facet_uri_to_class_index[affiliated_uris[0]]) {
return false;
}
}
if (facet_uri_to_class_index[affiliated_uris[0]] == result->size())
result->push_back(affiliated_uris);
}
for (const FacetURI& uri : requested_facet_uris_) {
if (!facet_uri_to_class_index.count(uri))
result->push_back(AffiliatedFacets(1, uri));
}
return true;
}
| 171,143 |
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 HeapObjectHeader::zapMagic() {
ASSERT(checkHeader());
m_magic = zappedMagic;
}
Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect.
This requires changing its signature. This is a preliminary stage to making it
private.
BUG=633030
Review-Url: https://codereview.chromium.org/2698673003
Cr-Commit-Position: refs/heads/master@{#460489}
CWE ID: CWE-119 | void HeapObjectHeader::zapMagic() {
checkHeader();
m_magic = zappedMagic;
}
| 172,716 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t GraphicBuffer::unflatten(
void const*& buffer, size_t& size, int const*& fds, size_t& count) {
if (size < 8*sizeof(int)) return NO_MEMORY;
int const* buf = static_cast<int const*>(buffer);
if (buf[0] != 'GBFR') return BAD_TYPE;
const size_t numFds = buf[8];
const size_t numInts = buf[9];
const size_t sizeNeeded = (10 + numInts) * sizeof(int);
if (size < sizeNeeded) return NO_MEMORY;
size_t fdCountNeeded = 0;
if (count < fdCountNeeded) return NO_MEMORY;
if (handle) {
free_handle();
}
if (numFds || numInts) {
width = buf[1];
height = buf[2];
stride = buf[3];
format = buf[4];
usage = buf[5];
native_handle* h = native_handle_create(numFds, numInts);
memcpy(h->data, fds, numFds*sizeof(int));
memcpy(h->data + numFds, &buf[10], numInts*sizeof(int));
handle = h;
} else {
width = height = stride = format = usage = 0;
handle = NULL;
}
mId = static_cast<uint64_t>(buf[6]) << 32;
mId |= static_cast<uint32_t>(buf[7]);
mOwner = ownHandle;
if (handle != 0) {
status_t err = mBufferMapper.registerBuffer(handle);
if (err != NO_ERROR) {
width = height = stride = format = usage = 0;
handle = NULL;
ALOGE("unflatten: registerBuffer failed: %s (%d)",
strerror(-err), err);
return err;
}
}
buffer = reinterpret_cast<void const*>(static_cast<int const*>(buffer) + sizeNeeded);
size -= sizeNeeded;
fds += numFds;
count -= numFds;
return NO_ERROR;
}
Commit Message: Fix for corruption when numFds or numInts is too large.
Bug: 18076253
Change-Id: I4c5935440013fc755e1d123049290383f4659fb6
(cherry picked from commit dfd06b89a4b77fc75eb85a3c1c700da3621c0118)
CWE ID: CWE-189 | status_t GraphicBuffer::unflatten(
void const*& buffer, size_t& size, int const*& fds, size_t& count) {
if (size < 8*sizeof(int)) return NO_MEMORY;
int const* buf = static_cast<int const*>(buffer);
if (buf[0] != 'GBFR') return BAD_TYPE;
const size_t numFds = buf[8];
const size_t numInts = buf[9];
const size_t maxNumber = UINT_MAX / sizeof(int);
if (numFds >= maxNumber || numInts >= (maxNumber - 10)) {
width = height = stride = format = usage = 0;
handle = NULL;
ALOGE("unflatten: numFds or numInts is too large: %d, %d",
numFds, numInts);
return BAD_VALUE;
}
const size_t sizeNeeded = (10 + numInts) * sizeof(int);
if (size < sizeNeeded) return NO_MEMORY;
size_t fdCountNeeded = numFds;
if (count < fdCountNeeded) return NO_MEMORY;
if (handle) {
free_handle();
}
if (numFds || numInts) {
width = buf[1];
height = buf[2];
stride = buf[3];
format = buf[4];
usage = buf[5];
native_handle* h = native_handle_create(numFds, numInts);
if (!h) {
width = height = stride = format = usage = 0;
handle = NULL;
ALOGE("unflatten: native_handle_create failed");
return NO_MEMORY;
}
memcpy(h->data, fds, numFds*sizeof(int));
memcpy(h->data + numFds, &buf[10], numInts*sizeof(int));
handle = h;
} else {
width = height = stride = format = usage = 0;
handle = NULL;
}
mId = static_cast<uint64_t>(buf[6]) << 32;
mId |= static_cast<uint32_t>(buf[7]);
mOwner = ownHandle;
if (handle != 0) {
status_t err = mBufferMapper.registerBuffer(handle);
if (err != NO_ERROR) {
width = height = stride = format = usage = 0;
handle = NULL;
ALOGE("unflatten: registerBuffer failed: %s (%d)",
strerror(-err), err);
return err;
}
}
buffer = reinterpret_cast<void const*>(static_cast<int const*>(buffer) + sizeNeeded);
size -= sizeNeeded;
fds += numFds;
count -= numFds;
return NO_ERROR;
}
| 173,374 |
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 ip6_ufo_append_data(struct sock *sk,
int getfrag(void *from, char *to, int offset, int len,
int odd, struct sk_buff *skb),
void *from, int length, int hh_len, int fragheaderlen,
int transhdrlen, int mtu,unsigned int flags,
struct rt6_info *rt)
{
struct sk_buff *skb;
int err;
/* There is support for UDP large send offload by network
* device, so create one single skb packet containing complete
* udp datagram
*/
if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) {
struct frag_hdr fhdr;
skb = sock_alloc_send_skb(sk,
hh_len + fragheaderlen + transhdrlen + 20,
(flags & MSG_DONTWAIT), &err);
if (skb == NULL)
return err;
/* reserve space for Hardware header */
skb_reserve(skb, hh_len);
/* create space for UDP/IP header */
skb_put(skb,fragheaderlen + transhdrlen);
/* initialize network header pointer */
skb_reset_network_header(skb);
/* initialize protocol header pointer */
skb->transport_header = skb->network_header + fragheaderlen;
skb->protocol = htons(ETH_P_IPV6);
skb->ip_summed = CHECKSUM_PARTIAL;
skb->csum = 0;
/* Specify the length of each IPv6 datagram fragment.
* It has to be a multiple of 8.
*/
skb_shinfo(skb)->gso_size = (mtu - fragheaderlen -
sizeof(struct frag_hdr)) & ~7;
skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
ipv6_select_ident(&fhdr, rt);
skb_shinfo(skb)->ip6_frag_id = fhdr.identification;
__skb_queue_tail(&sk->sk_write_queue, skb);
}
return skb_append_datato_frags(sk, skb, getfrag, from,
(length - transhdrlen));
}
Commit Message: ip6_output: do skb ufo init for peeked non ufo skb as well
Now, if user application does:
sendto len<mtu flag MSG_MORE
sendto len>mtu flag 0
The skb is not treated as fragmented one because it is not initialized
that way. So move the initialization to fix this.
introduced by:
commit e89e9cf539a28df7d0eb1d0a545368e9920b34ac "[IPv4/IPv6]: UFO Scatter-gather approach"
Signed-off-by: Jiri Pirko <[email protected]>
Acked-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264 | static inline int ip6_ufo_append_data(struct sock *sk,
int getfrag(void *from, char *to, int offset, int len,
int odd, struct sk_buff *skb),
void *from, int length, int hh_len, int fragheaderlen,
int transhdrlen, int mtu,unsigned int flags,
struct rt6_info *rt)
{
struct sk_buff *skb;
struct frag_hdr fhdr;
int err;
/* There is support for UDP large send offload by network
* device, so create one single skb packet containing complete
* udp datagram
*/
if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) {
skb = sock_alloc_send_skb(sk,
hh_len + fragheaderlen + transhdrlen + 20,
(flags & MSG_DONTWAIT), &err);
if (skb == NULL)
return err;
/* reserve space for Hardware header */
skb_reserve(skb, hh_len);
/* create space for UDP/IP header */
skb_put(skb,fragheaderlen + transhdrlen);
/* initialize network header pointer */
skb_reset_network_header(skb);
/* initialize protocol header pointer */
skb->transport_header = skb->network_header + fragheaderlen;
skb->protocol = htons(ETH_P_IPV6);
skb->csum = 0;
__skb_queue_tail(&sk->sk_write_queue, skb);
} else if (skb_is_gso(skb)) {
goto append;
}
skb->ip_summed = CHECKSUM_PARTIAL;
/* Specify the length of each IPv6 datagram fragment.
* It has to be a multiple of 8.
*/
skb_shinfo(skb)->gso_size = (mtu - fragheaderlen -
sizeof(struct frag_hdr)) & ~7;
skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
ipv6_select_ident(&fhdr, rt);
skb_shinfo(skb)->ip6_frag_id = fhdr.identification;
append:
return skb_append_datato_frags(sk, skb, getfrag, from,
(length - transhdrlen));
}
| 169,893 |
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 DecodeGifImg(struct ngiflib_img * i) {
struct ngiflib_decode_context context;
long npix;
u8 * stackp;
u8 * stack_top;
u16 clr;
u16 eof;
u16 free;
u16 act_code = 0;
u16 old_code = 0;
u16 read_byt;
u16 ab_prfx[4096];
u8 ab_suffx[4096];
u8 ab_stack[4096];
u8 flags;
u8 casspecial = 0;
if(!i) return -1;
i->posX = GetWord(i->parent); /* offsetX */
i->posY = GetWord(i->parent); /* offsetY */
i->width = GetWord(i->parent); /* SizeX */
i->height = GetWord(i->parent); /* SizeY */
context.Xtogo = i->width;
context.curY = i->posY;
#ifdef NGIFLIB_INDEXED_ONLY
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#else
if(i->parent->mode & NGIFLIB_MODE_INDEXED) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width;
context.frbuff_p.p32 = context.line_p.p32 + i->posX;
#else
context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
npix = (long)i->width * i->height;
flags = GetByte(i->parent);
i->interlaced = (flags & 64) >> 6;
context.pass = i->interlaced ? 1 : 0;
i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */
i->localpalbits = (flags & 7) + 1;
if(flags&128) { /* palette locale */
int k;
int localpalsize = 1 << i->localpalbits;
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize);
for(k=0; k<localpalsize; k++) {
i->palette[k].r = GetByte(i->parent);
i->palette[k].g = GetByte(i->parent);
i->palette[k].b = GetByte(i->parent);
}
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
i->palette = i->parent->palette;
i->localpalbits = i->parent->imgbits;
}
i->ncolors = 1 << i->localpalbits;
i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) {
if(i->interlaced) fprintf(i->parent->log, "interlaced ");
fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n",
i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors);
}
#endif /* !defined(NGIFLIB_NO_FILE) */
if(i->imgbits==1) { /* fix for 1bit images ? */
i->imgbits = 2;
}
clr = 1 << i->imgbits;
eof = clr + 1;
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
stackp = stack_top = ab_stack + 4096;
context.restbits = 0; /* initialise le "buffer" de lecture */
context.restbyte = 0; /* des codes LZW */
context.lbyte = 0;
for(;;) {
act_code = GetGifWord(i, &context);
if(act_code==eof) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 0;
}
if(npix==0) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 1;
}
if(act_code==clr) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (free=%hu) npix=%ld\n", free, npix);
#endif /* !defined(NGIFLIB_NO_FILE) */
/* clear */
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
act_code = GetGifWord(i, &context);
casspecial = (u8)act_code;
old_code = act_code;
WritePixel(i, &context, casspecial); npix--;
} else {
read_byt = act_code;
if(act_code >= free) { /* code pas encore dans alphabet */
/* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */
*(--stackp) = casspecial; /* dernier debut de chaine ! */
act_code = old_code;
}
/* printf("actcode=%d\n", act_code); */
while(act_code > clr) { /* code non concret */
/* fillstackloop empile les suffixes ! */
*(--stackp) = ab_suffx[act_code];
act_code = ab_prfx[act_code]; /* prefixe */
}
/* act_code est concret */
casspecial = (u8)act_code; /* dernier debut de chaine ! */
*(--stackp) = casspecial; /* push on stack */
WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */
npix -= (stack_top - stackp);
stackp = stack_top;
/* putchar('\n'); */
if(free < 4096) { /* la taille du dico est 4096 max ! */
ab_prfx[free] = old_code;
ab_suffx[free] = (u8)act_code;
free++;
if((free > context.max) && (context.nbbit < 12)) {
context.nbbit++; /* 1 bit de plus pour les codes LZW */
context.max += context.max + 1;
}
}
old_code = read_byt;
}
}
return 0;
}
Commit Message: check GIF image position and dimensions
fixes #1
CWE ID: CWE-119 | static int DecodeGifImg(struct ngiflib_img * i) {
struct ngiflib_decode_context context;
long npix;
u8 * stackp;
u8 * stack_top;
u16 clr;
u16 eof;
u16 free;
u16 act_code = 0;
u16 old_code = 0;
u16 read_byt;
u16 ab_prfx[4096];
u8 ab_suffx[4096];
u8 ab_stack[4096];
u8 flags;
u8 casspecial = 0;
if(!i) return -1;
i->posX = GetWord(i->parent); /* offsetX */
i->posY = GetWord(i->parent); /* offsetY */
i->width = GetWord(i->parent); /* SizeX */
i->height = GetWord(i->parent); /* SizeY */
if((i->width > i->parent->width) || (i->height > i->parent->height)) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Image bigger than global GIF canvas !\n");
#endif
return -1;
}
if((i->posX + i->width) > i->parent->width) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting X position\n");
#endif
i->posX = i->parent->width - i->width;
}
if((i->posY + i->height) > i->parent->height) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting Y position\n");
#endif
i->posY = i->parent->height - i->height;
}
context.Xtogo = i->width;
context.curY = i->posY;
#ifdef NGIFLIB_INDEXED_ONLY
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#else
if(i->parent->mode & NGIFLIB_MODE_INDEXED) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width;
context.frbuff_p.p32 = context.line_p.p32 + i->posX;
#else
context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
npix = (long)i->width * i->height;
flags = GetByte(i->parent);
i->interlaced = (flags & 64) >> 6;
context.pass = i->interlaced ? 1 : 0;
i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */
i->localpalbits = (flags & 7) + 1;
if(flags&128) { /* palette locale */
int k;
int localpalsize = 1 << i->localpalbits;
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize);
for(k=0; k<localpalsize; k++) {
i->palette[k].r = GetByte(i->parent);
i->palette[k].g = GetByte(i->parent);
i->palette[k].b = GetByte(i->parent);
}
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
i->palette = i->parent->palette;
i->localpalbits = i->parent->imgbits;
}
i->ncolors = 1 << i->localpalbits;
i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) {
if(i->interlaced) fprintf(i->parent->log, "interlaced ");
fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n",
i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors);
}
#endif /* !defined(NGIFLIB_NO_FILE) */
if(i->imgbits==1) { /* fix for 1bit images ? */
i->imgbits = 2;
}
clr = 1 << i->imgbits;
eof = clr + 1;
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
stackp = stack_top = ab_stack + 4096;
context.restbits = 0; /* initialise le "buffer" de lecture */
context.restbyte = 0; /* des codes LZW */
context.lbyte = 0;
for(;;) {
act_code = GetGifWord(i, &context);
if(act_code==eof) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 0;
}
if(npix==0) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 1;
}
if(act_code==clr) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (free=%hu) npix=%ld\n", free, npix);
#endif /* !defined(NGIFLIB_NO_FILE) */
/* clear */
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
act_code = GetGifWord(i, &context);
casspecial = (u8)act_code;
old_code = act_code;
WritePixel(i, &context, casspecial); npix--;
} else {
read_byt = act_code;
if(act_code >= free) { /* code pas encore dans alphabet */
/* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */
*(--stackp) = casspecial; /* dernier debut de chaine ! */
act_code = old_code;
}
/* printf("actcode=%d\n", act_code); */
while(act_code > clr) { /* code non concret */
/* fillstackloop empile les suffixes ! */
*(--stackp) = ab_suffx[act_code];
act_code = ab_prfx[act_code]; /* prefixe */
}
/* act_code est concret */
casspecial = (u8)act_code; /* dernier debut de chaine ! */
*(--stackp) = casspecial; /* push on stack */
WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */
npix -= (stack_top - stackp);
stackp = stack_top;
/* putchar('\n'); */
if(free < 4096) { /* la taille du dico est 4096 max ! */
ab_prfx[free] = old_code;
ab_suffx[free] = (u8)act_code;
free++;
if((free > context.max) && (context.nbbit < 12)) {
context.nbbit++; /* 1 bit de plus pour les codes LZW */
context.max += context.max + 1;
}
}
old_code = read_byt;
}
}
return 0;
}
| 169,247 |
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_entry_size_and_hooks(struct ip6t_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct ip6t_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!ip6_checkentry(&e->ipv6))
return -EINVAL;
err = xt_check_entry_offsets(e, e->target_offset, e->next_offset);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_debug("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
Commit Message: netfilter: x_tables: check for bogus target offset
We're currently asserting that targetoff + targetsize <= nextoff.
Extend it to also check that targetoff is >= sizeof(xt_entry).
Since this is generic code, add an argument pointing to the start of the
match/target, we can then derive the base structure size from the delta.
We also need the e->elems pointer in a followup change to validate matches.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-264 | check_entry_size_and_hooks(struct ip6t_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct ip6t_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!ip6_checkentry(&e->ipv6))
return -EINVAL;
err = xt_check_entry_offsets(e, e->elems, e->target_offset,
e->next_offset);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_debug("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
| 167,220 |
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 empty_write_end(struct page *page, unsigned from,
unsigned to, int mode)
{
struct inode *inode = page->mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
struct buffer_head *bh;
unsigned offset, blksize = 1 << inode->i_blkbits;
pgoff_t end_index = i_size_read(inode) >> PAGE_CACHE_SHIFT;
zero_user(page, from, to-from);
mark_page_accessed(page);
if (page->index < end_index || !(mode & FALLOC_FL_KEEP_SIZE)) {
if (!gfs2_is_writeback(ip))
gfs2_page_add_databufs(ip, page, from, to);
block_commit_write(page, from, to);
return 0;
}
offset = 0;
bh = page_buffers(page);
while (offset < to) {
if (offset >= from) {
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
clear_buffer_new(bh);
write_dirty_buffer(bh, WRITE);
}
offset += blksize;
bh = bh->b_this_page;
}
offset = 0;
bh = page_buffers(page);
while (offset < to) {
if (offset >= from) {
wait_on_buffer(bh);
if (!buffer_uptodate(bh))
return -EIO;
}
offset += blksize;
bh = bh->b_this_page;
}
return 0;
}
Commit Message: GFS2: rewrite fallocate code to write blocks directly
GFS2's fallocate code currently goes through the page cache. Since it's only
writing to the end of the file or to holes in it, it doesn't need to, and it
was causing issues on low memory environments. This patch pulls in some of
Steve's block allocation work, and uses it to simply allocate the blocks for
the file, and zero them out at allocation time. It provides a slight
performance increase, and it dramatically simplifies the code.
Signed-off-by: Benjamin Marzinski <[email protected]>
Signed-off-by: Steven Whitehouse <[email protected]>
CWE ID: CWE-119 | static int empty_write_end(struct page *page, unsigned from,
| 166,211 |
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 fr_add_pvc(struct net_device *frad, unsigned int dlci, int type)
{
hdlc_device *hdlc = dev_to_hdlc(frad);
pvc_device *pvc;
struct net_device *dev;
int used;
if ((pvc = add_pvc(frad, dlci)) == NULL) {
netdev_warn(frad, "Memory squeeze on fr_add_pvc()\n");
return -ENOBUFS;
}
if (*get_dev_p(pvc, type))
return -EEXIST;
used = pvc_is_used(pvc);
if (type == ARPHRD_ETHER)
dev = alloc_netdev(0, "pvceth%d", ether_setup);
else
dev = alloc_netdev(0, "pvc%d", pvc_setup);
if (!dev) {
netdev_warn(frad, "Memory squeeze on fr_pvc()\n");
delete_unused_pvcs(hdlc);
return -ENOBUFS;
}
if (type == ARPHRD_ETHER)
random_ether_addr(dev->dev_addr);
else {
*(__be16*)dev->dev_addr = htons(dlci);
dlci_to_q922(dev->broadcast, dlci);
}
dev->netdev_ops = &pvc_ops;
dev->mtu = HDLC_MAX_MTU;
dev->tx_queue_len = 0;
dev->ml_priv = pvc;
if (register_netdevice(dev) != 0) {
free_netdev(dev);
delete_unused_pvcs(hdlc);
return -EIO;
}
dev->destructor = free_netdev;
*get_dev_p(pvc, type) = dev;
if (!used) {
state(hdlc)->dce_changed = 1;
state(hdlc)->dce_pvc_count++;
}
return 0;
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264 | static int fr_add_pvc(struct net_device *frad, unsigned int dlci, int type)
{
hdlc_device *hdlc = dev_to_hdlc(frad);
pvc_device *pvc;
struct net_device *dev;
int used;
if ((pvc = add_pvc(frad, dlci)) == NULL) {
netdev_warn(frad, "Memory squeeze on fr_add_pvc()\n");
return -ENOBUFS;
}
if (*get_dev_p(pvc, type))
return -EEXIST;
used = pvc_is_used(pvc);
if (type == ARPHRD_ETHER) {
dev = alloc_netdev(0, "pvceth%d", ether_setup);
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
} else
dev = alloc_netdev(0, "pvc%d", pvc_setup);
if (!dev) {
netdev_warn(frad, "Memory squeeze on fr_pvc()\n");
delete_unused_pvcs(hdlc);
return -ENOBUFS;
}
if (type == ARPHRD_ETHER)
random_ether_addr(dev->dev_addr);
else {
*(__be16*)dev->dev_addr = htons(dlci);
dlci_to_q922(dev->broadcast, dlci);
}
dev->netdev_ops = &pvc_ops;
dev->mtu = HDLC_MAX_MTU;
dev->tx_queue_len = 0;
dev->ml_priv = pvc;
if (register_netdevice(dev) != 0) {
free_netdev(dev);
delete_unused_pvcs(hdlc);
return -EIO;
}
dev->destructor = free_netdev;
*get_dev_p(pvc, type) = dev;
if (!used) {
state(hdlc)->dce_changed = 1;
state(hdlc)->dce_pvc_count++;
}
return 0;
}
| 165,732 |
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 long Segment::ParseHeaders()
{
long long total, available;
const int status = m_pReader->Length(&total, &available);
if (status < 0) //error
return status;
assert((total < 0) || (available <= total));
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
assert((segment_stop < 0) || (total < 0) || (segment_stop <= total));
assert((segment_stop < 0) || (m_pos <= segment_stop));
for (;;)
{
if ((total >= 0) && (m_pos >= total))
break;
if ((segment_stop >= 0) && (m_pos >= segment_stop))
break;
long long pos = m_pos;
const long long element_start = pos;
if ((pos + 1) > available)
return (pos + 1);
long len;
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return result;
if (result > 0) //underflow (weird)
return (pos + 1);
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id < 0) //error
return id;
if (id == 0x0F43B675) //Cluster ID
break;
pos += len; //consume ID
if ((pos + 1) > available)
return (pos + 1);
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return result;
if (result > 0) //underflow (weird)
return (pos + 1);
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) //error
return size;
pos += len; //consume length of size of element
const long long element_size = size + pos - element_start;
if ((segment_stop >= 0) && ((pos + size) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + size) > available)
return pos + size;
if (id == 0x0549A966) //Segment Info ID
{
if (m_pInfo)
return E_FILE_FORMAT_INVALID;
m_pInfo = new (std::nothrow) SegmentInfo(
this,
pos,
size,
element_start,
element_size);
if (m_pInfo == NULL)
return -1;
const long status = m_pInfo->Parse();
if (status)
return status;
}
else if (id == 0x0654AE6B) //Tracks ID
{
if (m_pTracks)
return E_FILE_FORMAT_INVALID;
m_pTracks = new (std::nothrow) Tracks(this,
pos,
size,
element_start,
element_size);
if (m_pTracks == NULL)
return -1;
const long status = m_pTracks->Parse();
if (status)
return status;
}
else if (id == 0x0C53BB6B) //Cues ID
{
if (m_pCues == NULL)
{
m_pCues = new (std::nothrow) Cues(
this,
pos,
size,
element_start,
element_size);
if (m_pCues == NULL)
return -1;
}
}
else if (id == 0x014D9B74) //SeekHead ID
{
if (m_pSeekHead == NULL)
{
m_pSeekHead = new (std::nothrow) SeekHead(
this,
pos,
size,
element_start,
element_size);
if (m_pSeekHead == NULL)
return -1;
const long status = m_pSeekHead->Parse();
if (status)
return status;
}
}
else if (id == 0x0043A770) //Chapters ID
{
if (m_pChapters == NULL)
{
m_pChapters = new (std::nothrow) Chapters(
this,
pos,
size,
element_start,
element_size);
if (m_pChapters == NULL)
return -1;
const long status = m_pChapters->Parse();
if (status)
return status;
}
}
m_pos = pos + size; //consume payload
}
assert((segment_stop < 0) || (m_pos <= segment_stop));
if (m_pInfo == NULL) //TODO: liberalize this behavior
return E_FILE_FORMAT_INVALID;
if (m_pTracks == NULL)
return E_FILE_FORMAT_INVALID;
return 0; //success
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long Segment::ParseHeaders()
if (status)
return status;
} else if (id == 0x0C53BB6B) { // Cues ID
if (m_pCues == NULL) {
m_pCues = new (std::nothrow)
Cues(this, pos, size, element_start, element_size);
if (m_pCues == NULL)
return -1;
}
} else if (id == 0x014D9B74) { // SeekHead ID
if (m_pSeekHead == NULL) {
m_pSeekHead = new (std::nothrow)
SeekHead(this, pos, size, element_start, element_size);
if (m_pSeekHead == NULL)
return -1;
const long status = m_pSeekHead->Parse();
if (status)
return status;
}
} else if (id == 0x0043A770) { // Chapters ID
if (m_pChapters == NULL) {
m_pChapters = new (std::nothrow)
Chapters(this, pos, size, element_start, element_size);
if (m_pChapters == NULL)
return -1;
const long status = m_pChapters->Parse();
if (status)
return status;
}
}
m_pos = pos + size; // consume payload
}
assert((segment_stop < 0) || (m_pos <= segment_stop));
if (m_pInfo == NULL) // TODO: liberalize this behavior
return E_FILE_FORMAT_INVALID;
if (m_pTracks == NULL)
return E_FILE_FORMAT_INVALID;
return 0; // success
}
| 174,427 |
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 AutoFillManager::LogMetricsAboutSubmittedForm(
const FormData& form,
const FormStructure* submitted_form) {
FormStructure* cached_submitted_form;
if (!FindCachedForm(form, &cached_submitted_form)) {
NOTREACHED();
return;
}
std::map<std::string, const AutoFillField*> cached_fields;
for (size_t i = 0; i < cached_submitted_form->field_count(); ++i) {
const AutoFillField* field = cached_submitted_form->field(i);
cached_fields[field->FieldSignature()] = field;
}
for (size_t i = 0; i < submitted_form->field_count(); ++i) {
const AutoFillField* field = submitted_form->field(i);
FieldTypeSet field_types;
personal_data_->GetPossibleFieldTypes(field->value(), &field_types);
DCHECK(!field_types.empty());
if (field->form_control_type() == ASCIIToUTF16("select-one")) {
continue;
}
metric_logger_->Log(AutoFillMetrics::FIELD_SUBMITTED);
if (field_types.find(EMPTY_TYPE) == field_types.end() &&
field_types.find(UNKNOWN_TYPE) == field_types.end()) {
if (field->is_autofilled()) {
metric_logger_->Log(AutoFillMetrics::FIELD_AUTOFILLED);
} else {
metric_logger_->Log(AutoFillMetrics::FIELD_AUTOFILL_FAILED);
AutoFillFieldType heuristic_type = UNKNOWN_TYPE;
AutoFillFieldType server_type = NO_SERVER_DATA;
std::map<std::string, const AutoFillField*>::const_iterator
cached_field = cached_fields.find(field->FieldSignature());
if (cached_field != cached_fields.end()) {
heuristic_type = cached_field->second->heuristic_type();
server_type = cached_field->second->server_type();
}
if (heuristic_type == UNKNOWN_TYPE)
metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_UNKNOWN);
else if (field_types.count(heuristic_type))
metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_MATCH);
else
metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_MISMATCH);
if (server_type == NO_SERVER_DATA)
metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_UNKNOWN);
else if (field_types.count(server_type))
metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_MATCH);
else
metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_MISMATCH);
}
}
}
}
Commit Message: Add support for autofill server experiments
BUG=none
TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId
Review URL: http://codereview.chromium.org/6260027
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void AutoFillManager::LogMetricsAboutSubmittedForm(
const FormData& form,
const FormStructure* submitted_form) {
FormStructure* cached_submitted_form;
if (!FindCachedForm(form, &cached_submitted_form)) {
NOTREACHED();
return;
}
std::map<std::string, const AutoFillField*> cached_fields;
for (size_t i = 0; i < cached_submitted_form->field_count(); ++i) {
const AutoFillField* field = cached_submitted_form->field(i);
cached_fields[field->FieldSignature()] = field;
}
std::string experiment_id = cached_submitted_form->server_experiment_id();
for (size_t i = 0; i < submitted_form->field_count(); ++i) {
const AutoFillField* field = submitted_form->field(i);
FieldTypeSet field_types;
personal_data_->GetPossibleFieldTypes(field->value(), &field_types);
DCHECK(!field_types.empty());
if (field->form_control_type() == ASCIIToUTF16("select-one")) {
continue;
}
metric_logger_->Log(AutoFillMetrics::FIELD_SUBMITTED, experiment_id);
if (field_types.find(EMPTY_TYPE) == field_types.end() &&
field_types.find(UNKNOWN_TYPE) == field_types.end()) {
if (field->is_autofilled()) {
metric_logger_->Log(AutoFillMetrics::FIELD_AUTOFILLED, experiment_id);
} else {
metric_logger_->Log(AutoFillMetrics::FIELD_AUTOFILL_FAILED,
experiment_id);
AutoFillFieldType heuristic_type = UNKNOWN_TYPE;
AutoFillFieldType server_type = NO_SERVER_DATA;
std::map<std::string, const AutoFillField*>::const_iterator
cached_field = cached_fields.find(field->FieldSignature());
if (cached_field != cached_fields.end()) {
heuristic_type = cached_field->second->heuristic_type();
server_type = cached_field->second->server_type();
}
if (heuristic_type == UNKNOWN_TYPE) {
metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_UNKNOWN,
experiment_id);
} else if (field_types.count(heuristic_type)) {
metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_MATCH,
experiment_id);
} else {
metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_MISMATCH,
experiment_id);
}
if (server_type == NO_SERVER_DATA) {
metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_UNKNOWN,
experiment_id);
} else if (field_types.count(server_type)) {
metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_MATCH,
experiment_id);
} else {
metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_MISMATCH,
experiment_id);
}
}
}
}
}
| 170,651 |
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 UserSelectionScreen::FillUserDictionary(
user_manager::User* user,
bool is_owner,
bool is_signin_to_add,
proximity_auth::mojom::AuthType auth_type,
const std::vector<std::string>* public_session_recommended_locales,
base::DictionaryValue* user_dict) {
const bool is_public_session =
user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT;
const bool is_legacy_supervised_user =
user->GetType() == user_manager::USER_TYPE_SUPERVISED;
const bool is_child_user = user->GetType() == user_manager::USER_TYPE_CHILD;
user_dict->SetString(kKeyUsername, user->GetAccountId().Serialize());
user_dict->SetString(kKeyEmailAddress, user->display_email());
user_dict->SetString(kKeyDisplayName, user->GetDisplayName());
user_dict->SetBoolean(kKeyPublicAccount, is_public_session);
user_dict->SetBoolean(kKeyLegacySupervisedUser, is_legacy_supervised_user);
user_dict->SetBoolean(kKeyChildUser, is_child_user);
user_dict->SetBoolean(kKeyDesktopUser, false);
user_dict->SetInteger(kKeyInitialAuthType, static_cast<int>(auth_type));
user_dict->SetBoolean(kKeySignedIn, user->is_logged_in());
user_dict->SetBoolean(kKeyIsOwner, is_owner);
user_dict->SetBoolean(kKeyIsActiveDirectory, user->IsActiveDirectoryUser());
user_dict->SetBoolean(kKeyAllowFingerprint, AllowFingerprintForUser(user));
FillMultiProfileUserPrefs(user, user_dict, is_signin_to_add);
if (is_public_session) {
AddPublicSessionDetailsToUserDictionaryEntry(
user_dict, public_session_recommended_locales);
}
}
Commit Message: cros: Check initial auth type when showing views login.
Bug: 859611
Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058
Reviewed-on: https://chromium-review.googlesource.com/1123056
Reviewed-by: Xiaoyin Hu <[email protected]>
Commit-Queue: Jacob Dufault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572224}
CWE ID: | void UserSelectionScreen::FillUserDictionary(
const user_manager::User* user,
bool is_owner,
bool is_signin_to_add,
proximity_auth::mojom::AuthType auth_type,
const std::vector<std::string>* public_session_recommended_locales,
base::DictionaryValue* user_dict) {
const bool is_public_session =
user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT;
const bool is_legacy_supervised_user =
user->GetType() == user_manager::USER_TYPE_SUPERVISED;
const bool is_child_user = user->GetType() == user_manager::USER_TYPE_CHILD;
user_dict->SetString(kKeyUsername, user->GetAccountId().Serialize());
user_dict->SetString(kKeyEmailAddress, user->display_email());
user_dict->SetString(kKeyDisplayName, user->GetDisplayName());
user_dict->SetBoolean(kKeyPublicAccount, is_public_session);
user_dict->SetBoolean(kKeyLegacySupervisedUser, is_legacy_supervised_user);
user_dict->SetBoolean(kKeyChildUser, is_child_user);
user_dict->SetBoolean(kKeyDesktopUser, false);
user_dict->SetInteger(kKeyInitialAuthType, static_cast<int>(auth_type));
user_dict->SetBoolean(kKeySignedIn, user->is_logged_in());
user_dict->SetBoolean(kKeyIsOwner, is_owner);
user_dict->SetBoolean(kKeyIsActiveDirectory, user->IsActiveDirectoryUser());
user_dict->SetBoolean(kKeyAllowFingerprint, AllowFingerprintForUser(user));
FillMultiProfileUserPrefs(user, user_dict, is_signin_to_add);
if (is_public_session) {
AddPublicSessionDetailsToUserDictionaryEntry(
user_dict, public_session_recommended_locales);
}
}
| 172,200 |
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, rewind)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC);
} /* }}} */
/* {{{ proto void SplFileObject::eof()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileObject, rewind)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC);
} /* }}} */
/* {{{ proto void SplFileObject::eof()
| 167,051 |
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 ResetScreenHandler::Show() {
if (!page_is_ready()) {
show_on_init_ = true;
return;
}
PrefService* prefs = g_browser_process->local_state();
restart_required_ = !CommandLine::ForCurrentProcess()->HasSwitch(
switches::kFirstExecAfterBoot);
reboot_was_requested_ = false;
rollback_available_ = false;
if (!restart_required_) // First exec after boot.
reboot_was_requested_ = prefs->GetBoolean(prefs::kFactoryResetRequested);
if (!restart_required_ && reboot_was_requested_) {
rollback_available_ = prefs->GetBoolean(prefs::kRollbackRequested);
ShowWithParams();
} else {
chromeos::DBusThreadManager::Get()->GetUpdateEngineClient()->
CanRollbackCheck(base::Bind(&ResetScreenHandler::OnRollbackCheck,
weak_ptr_factory_.GetWeakPtr()));
}
}
Commit Message: Rollback option put behind the flag.
BUG=368860
Review URL: https://codereview.chromium.org/267393011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@269753 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void ResetScreenHandler::Show() {
if (!page_is_ready()) {
show_on_init_ = true;
return;
}
PrefService* prefs = g_browser_process->local_state();
restart_required_ = !CommandLine::ForCurrentProcess()->HasSwitch(
switches::kFirstExecAfterBoot);
reboot_was_requested_ = false;
rollback_available_ = false;
if (!restart_required_) // First exec after boot.
reboot_was_requested_ = prefs->GetBoolean(prefs::kFactoryResetRequested);
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableRollbackOption)) {
rollback_available_ = false;
ShowWithParams();
} else if (!restart_required_ && reboot_was_requested_) {
rollback_available_ = prefs->GetBoolean(prefs::kRollbackRequested);
ShowWithParams();
} else {
chromeos::DBusThreadManager::Get()->GetUpdateEngineClient()->
CanRollbackCheck(base::Bind(&ResetScreenHandler::OnRollbackCheck,
weak_ptr_factory_.GetWeakPtr()));
}
}
| 171,181 |
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 ChromeNetworkDelegate::OnCompleted(net::URLRequest* request,
bool started) {
TRACE_EVENT_ASYNC_END0("net", "URLRequest", request);
if (request->status().status() == net::URLRequestStatus::SUCCESS) {
int64 received_content_length = request->received_response_content_length();
bool is_http = request->url().SchemeIs("http");
bool is_https = request->url().SchemeIs("https");
if (!request->was_cached() && // Don't record cached content
received_content_length && // Zero-byte responses aren't useful.
(is_http || is_https)) { // Only record for HTTP or HTTPS urls.
int64 original_content_length =
request->response_info().headers->GetInt64HeaderValue(
"x-original-content-length");
bool via_data_reduction_proxy =
request->response_info().headers->HasHeaderValue(
"via", "1.1 Chrome Compression Proxy");
int64 adjusted_original_content_length = original_content_length;
if (adjusted_original_content_length == -1)
adjusted_original_content_length = received_content_length;
base::TimeDelta freshness_lifetime =
request->response_info().headers->GetFreshnessLifetime(
request->response_info().response_time);
AccumulateContentLength(received_content_length,
adjusted_original_content_length,
via_data_reduction_proxy);
RecordContentLengthHistograms(received_content_length,
original_content_length,
freshness_lifetime);
DVLOG(2) << __FUNCTION__
<< " received content length: " << received_content_length
<< " original content length: " << original_content_length
<< " url: " << request->url();
}
bool is_redirect = request->response_headers() &&
net::HttpResponseHeaders::IsRedirectResponseCode(
request->response_headers()->response_code());
if (!is_redirect) {
ExtensionWebRequestEventRouter::GetInstance()->OnCompleted(
profile_, extension_info_map_.get(), request);
}
} else if (request->status().status() == net::URLRequestStatus::FAILED ||
request->status().status() == net::URLRequestStatus::CANCELED) {
ExtensionWebRequestEventRouter::GetInstance()->OnErrorOccurred(
profile_, extension_info_map_.get(), request, started);
} else {
NOTREACHED();
}
ForwardProxyErrors(request, event_router_.get(), profile_);
ForwardRequestStatus(REQUEST_DONE, request, profile_);
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416 | void ChromeNetworkDelegate::OnCompleted(net::URLRequest* request,
bool started) {
TRACE_EVENT_ASYNC_END0("net", "URLRequest", request);
if (request->status().status() == net::URLRequestStatus::SUCCESS) {
int64 received_content_length = request->received_response_content_length();
bool is_http = request->url().SchemeIs("http");
bool is_https = request->url().SchemeIs("https");
if (!request->was_cached() && // Don't record cached content
received_content_length && // Zero-byte responses aren't useful.
(is_http || is_https)) { // Only record for HTTP or HTTPS urls.
int64 original_content_length =
request->response_info().headers->GetInt64HeaderValue(
"x-original-content-length");
chrome_browser_net::DataReductionRequestType data_reduction_type =
chrome_browser_net::GetDataReductionRequestType(
reinterpret_cast<Profile*>(profile_), request);
base::TimeDelta freshness_lifetime =
request->response_info().headers->GetFreshnessLifetime(
request->response_info().response_time);
int64 adjusted_original_content_length =
chrome_browser_net::GetAdjustedOriginalContentLength(
data_reduction_type, original_content_length,
received_content_length);
AccumulateContentLength(received_content_length,
adjusted_original_content_length,
data_reduction_type);
RecordContentLengthHistograms(received_content_length,
original_content_length,
freshness_lifetime);
DVLOG(2) << __FUNCTION__
<< " received content length: " << received_content_length
<< " original content length: " << original_content_length
<< " url: " << request->url();
}
bool is_redirect = request->response_headers() &&
net::HttpResponseHeaders::IsRedirectResponseCode(
request->response_headers()->response_code());
if (!is_redirect) {
ExtensionWebRequestEventRouter::GetInstance()->OnCompleted(
profile_, extension_info_map_.get(), request);
}
} else if (request->status().status() == net::URLRequestStatus::FAILED ||
request->status().status() == net::URLRequestStatus::CANCELED) {
ExtensionWebRequestEventRouter::GetInstance()->OnErrorOccurred(
profile_, extension_info_map_.get(), request, started);
} else {
NOTREACHED();
}
ForwardProxyErrors(request, event_router_.get(), profile_);
ForwardRequestStatus(REQUEST_DONE, request, profile_);
}
| 171,332 |
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 Cluster::Parse(long long& pos, long& len) const
{
long status = Load(pos, len);
if (status < 0)
return status;
assert(m_pos >= m_element_start);
assert(m_timecode >= 0);
const long long cluster_stop =
(m_element_size < 0) ? -1 : m_element_start + m_element_size;
if ((cluster_stop >= 0) && (m_pos >= cluster_stop))
return 1; //nothing else to do
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
status = pReader->Length(&total, &avail);
if (status < 0) //error
return status;
assert((total < 0) || (avail <= total));
pos = m_pos;
for (;;)
{
if ((cluster_stop >= 0) && (pos >= cluster_stop))
break;
if ((total >= 0) && (pos >= total))
{
if (m_element_size < 0)
m_element_size = pos - m_element_start;
break;
}
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) //error
return static_cast<long>(id);
if (id == 0) //weird
return E_FILE_FORMAT_INVALID;
if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) //Cluster or Cues ID
{
if (m_element_size < 0)
m_element_size = pos - m_element_start;
break;
}
pos += len; //consume ID field
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
pos += len; //consume size field
if ((cluster_stop >= 0) && (pos > cluster_stop))
return E_FILE_FORMAT_INVALID;
if (size == 0) //weird
continue;
const long long block_stop = pos + size;
if (cluster_stop >= 0)
{
if (block_stop > cluster_stop)
{
if ((id == 0x20) || (id == 0x23))
return E_FILE_FORMAT_INVALID;
pos = cluster_stop;
break;
}
}
else if ((total >= 0) && (block_stop > total))
{
m_element_size = total - m_element_start;
pos = total;
break;
}
else if (block_stop > avail)
{
len = static_cast<long>(size);
return E_BUFFER_NOT_FULL;
}
Cluster* const this_ = const_cast<Cluster*>(this);
if (id == 0x20) //BlockGroup
return this_->ParseBlockGroup(size, pos, len);
if (id == 0x23) //SimpleBlock
return this_->ParseSimpleBlock(size, pos, len);
pos += size; //consume payload
assert((cluster_stop < 0) || (pos <= cluster_stop));
}
assert(m_element_size > 0);
m_pos = pos;
assert((cluster_stop < 0) || (m_pos <= cluster_stop));
if (m_entries_count > 0)
{
const long idx = m_entries_count - 1;
const BlockEntry* const pLast = m_entries[idx];
assert(pLast);
const Block* const pBlock = pLast->GetBlock();
assert(pBlock);
const long long start = pBlock->m_start;
if ((total >= 0) && (start > total))
return -1; //defend against trucated stream
const long long size = pBlock->m_size;
const long long stop = start + size;
assert((cluster_stop < 0) || (stop <= cluster_stop));
if ((total >= 0) && (stop > total))
return -1; //defend against trucated stream
}
return 1; //no more entries
}
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 Cluster::Parse(long long& pos, long& len) const
| 174,409 |
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: base::string16 GetAppForProtocolUsingRegistry(const GURL& url) {
base::string16 command_to_launch;
base::string16 cmd_key_path = base::ASCIIToUTF16(url.scheme());
base::win::RegKey cmd_key_name(HKEY_CLASSES_ROOT, cmd_key_path.c_str(),
KEY_READ);
if (cmd_key_name.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS &&
!command_to_launch.empty()) {
return command_to_launch;
}
cmd_key_path = base::ASCIIToUTF16(url.scheme() + "\\shell\\open\\command");
base::win::RegKey cmd_key_exe(HKEY_CLASSES_ROOT, cmd_key_path.c_str(),
KEY_READ);
if (cmd_key_exe.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS) {
base::CommandLine command_line(
base::CommandLine::FromString(command_to_launch));
return command_line.GetProgram().BaseName().value();
}
return base::string16();
}
Commit Message: Validate external protocols before launching on Windows
Bug: 889459
Change-Id: Id33ca6444bff1e6dd71b6000823cf6fec09746ef
Reviewed-on: https://chromium-review.googlesource.com/c/1256208
Reviewed-by: Greg Thompson <[email protected]>
Commit-Queue: Mustafa Emre Acer <[email protected]>
Cr-Commit-Position: refs/heads/master@{#597611}
CWE ID: CWE-20 | base::string16 GetAppForProtocolUsingRegistry(const GURL& url) {
const base::string16 url_scheme = base::ASCIIToUTF16(url.scheme());
if (!IsValidCustomProtocol(url_scheme))
return base::string16();
base::string16 command_to_launch;
base::win::RegKey cmd_key_name(HKEY_CLASSES_ROOT, url_scheme.c_str(),
KEY_READ);
if (cmd_key_name.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS &&
!command_to_launch.empty()) {
return command_to_launch;
}
const base::string16 cmd_key_path = url_scheme + L"\\shell\\open\\command";
base::win::RegKey cmd_key_exe(HKEY_CLASSES_ROOT, cmd_key_path.c_str(),
KEY_READ);
if (cmd_key_exe.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS) {
base::CommandLine command_line(
base::CommandLine::FromString(command_to_launch));
return command_line.GetProgram().BaseName().value();
}
return base::string16();
}
| 172,636 |
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 audit_log_single_execve_arg(struct audit_context *context,
struct audit_buffer **ab,
int arg_num,
size_t *len_sent,
const char __user *p,
char *buf)
{
char arg_num_len_buf[12];
const char __user *tmp_p = p;
/* how many digits are in arg_num? 5 is the length of ' a=""' */
size_t arg_num_len = snprintf(arg_num_len_buf, 12, "%d", arg_num) + 5;
size_t len, len_left, to_send;
size_t max_execve_audit_len = MAX_EXECVE_AUDIT_LEN;
unsigned int i, has_cntl = 0, too_long = 0;
int ret;
/* strnlen_user includes the null we don't want to send */
len_left = len = strnlen_user(p, MAX_ARG_STRLEN) - 1;
/*
* We just created this mm, if we can't find the strings
* we just copied into it something is _very_ wrong. Similar
* for strings that are too long, we should not have created
* any.
*/
if (WARN_ON_ONCE(len < 0 || len > MAX_ARG_STRLEN - 1)) {
send_sig(SIGKILL, current, 0);
return -1;
}
/* walk the whole argument looking for non-ascii chars */
do {
if (len_left > MAX_EXECVE_AUDIT_LEN)
to_send = MAX_EXECVE_AUDIT_LEN;
else
to_send = len_left;
ret = copy_from_user(buf, tmp_p, to_send);
/*
* There is no reason for this copy to be short. We just
* copied them here, and the mm hasn't been exposed to user-
* space yet.
*/
if (ret) {
WARN_ON(1);
send_sig(SIGKILL, current, 0);
return -1;
}
buf[to_send] = '\0';
has_cntl = audit_string_contains_control(buf, to_send);
if (has_cntl) {
/*
* hex messages get logged as 2 bytes, so we can only
* send half as much in each message
*/
max_execve_audit_len = MAX_EXECVE_AUDIT_LEN / 2;
break;
}
len_left -= to_send;
tmp_p += to_send;
} while (len_left > 0);
len_left = len;
if (len > max_execve_audit_len)
too_long = 1;
/* rewalk the argument actually logging the message */
for (i = 0; len_left > 0; i++) {
int room_left;
if (len_left > max_execve_audit_len)
to_send = max_execve_audit_len;
else
to_send = len_left;
/* do we have space left to send this argument in this ab? */
room_left = MAX_EXECVE_AUDIT_LEN - arg_num_len - *len_sent;
if (has_cntl)
room_left -= (to_send * 2);
else
room_left -= to_send;
if (room_left < 0) {
*len_sent = 0;
audit_log_end(*ab);
*ab = audit_log_start(context, GFP_KERNEL, AUDIT_EXECVE);
if (!*ab)
return 0;
}
/*
* first record needs to say how long the original string was
* so we can be sure nothing was lost.
*/
if ((i == 0) && (too_long))
audit_log_format(*ab, " a%d_len=%zu", arg_num,
has_cntl ? 2*len : len);
/*
* normally arguments are small enough to fit and we already
* filled buf above when we checked for control characters
* so don't bother with another copy_from_user
*/
if (len >= max_execve_audit_len)
ret = copy_from_user(buf, p, to_send);
else
ret = 0;
if (ret) {
WARN_ON(1);
send_sig(SIGKILL, current, 0);
return -1;
}
buf[to_send] = '\0';
/* actually log it */
audit_log_format(*ab, " a%d", arg_num);
if (too_long)
audit_log_format(*ab, "[%d]", i);
audit_log_format(*ab, "=");
if (has_cntl)
audit_log_n_hex(*ab, buf, to_send);
else
audit_log_string(*ab, buf);
p += to_send;
len_left -= to_send;
*len_sent += arg_num_len;
if (has_cntl)
*len_sent += to_send * 2;
else
*len_sent += to_send;
}
/* include the null we didn't log */
return len + 1;
}
Commit Message: audit: fix a double fetch in audit_log_single_execve_arg()
There is a double fetch problem in audit_log_single_execve_arg()
where we first check the execve(2) argumnets for any "bad" characters
which would require hex encoding and then re-fetch the arguments for
logging in the audit record[1]. Of course this leaves a window of
opportunity for an unsavory application to munge with the data.
This patch reworks things by only fetching the argument data once[2]
into a buffer where it is scanned and logged into the audit
records(s). In addition to fixing the double fetch, this patch
improves on the original code in a few other ways: better handling
of large arguments which require encoding, stricter record length
checking, and some performance improvements (completely unverified,
but we got rid of some strlen() calls, that's got to be a good
thing).
As part of the development of this patch, I've also created a basic
regression test for the audit-testsuite, the test can be tracked on
GitHub at the following link:
* https://github.com/linux-audit/audit-testsuite/issues/25
[1] If you pay careful attention, there is actually a triple fetch
problem due to a strnlen_user() call at the top of the function.
[2] This is a tiny white lie, we do make a call to strnlen_user()
prior to fetching the argument data. I don't like it, but due to the
way the audit record is structured we really have no choice unless we
copy the entire argument at once (which would require a rather
wasteful allocation). The good news is that with this patch the
kernel no longer relies on this strnlen_user() value for anything
beyond recording it in the log, we also update it with a trustworthy
value whenever possible.
Reported-by: Pengfei Wang <[email protected]>
Cc: <[email protected]>
Signed-off-by: Paul Moore <[email protected]>
CWE ID: CWE-362 | static int audit_log_single_execve_arg(struct audit_context *context,
static void audit_log_execve_info(struct audit_context *context,
struct audit_buffer **ab)
{
long len_max;
long len_rem;
long len_full;
long len_buf;
long len_abuf;
long len_tmp;
bool require_data;
bool encode;
unsigned int iter;
unsigned int arg;
char *buf_head;
char *buf;
const char __user *p = (const char __user *)current->mm->arg_start;
/* NOTE: this buffer needs to be large enough to hold all the non-arg
* data we put in the audit record for this argument (see the
* code below) ... at this point in time 96 is plenty */
char abuf[96];
/* NOTE: we set MAX_EXECVE_AUDIT_LEN to a rather arbitrary limit, the
* current value of 7500 is not as important as the fact that it
* is less than 8k, a setting of 7500 gives us plenty of wiggle
* room if we go over a little bit in the logging below */
WARN_ON_ONCE(MAX_EXECVE_AUDIT_LEN > 7500);
len_max = MAX_EXECVE_AUDIT_LEN;
/* scratch buffer to hold the userspace args */
buf_head = kmalloc(MAX_EXECVE_AUDIT_LEN + 1, GFP_KERNEL);
if (!buf_head) {
audit_panic("out of memory for argv string");
return;
}
buf = buf_head;
audit_log_format(*ab, "argc=%d", context->execve.argc);
len_rem = len_max;
len_buf = 0;
len_full = 0;
require_data = true;
encode = false;
iter = 0;
arg = 0;
do {
/* NOTE: we don't ever want to trust this value for anything
* serious, but the audit record format insists we
* provide an argument length for really long arguments,
* e.g. > MAX_EXECVE_AUDIT_LEN, so we have no choice but
* to use strncpy_from_user() to obtain this value for
* recording in the log, although we don't use it
* anywhere here to avoid a double-fetch problem */
if (len_full == 0)
len_full = strnlen_user(p, MAX_ARG_STRLEN) - 1;
/* read more data from userspace */
if (require_data) {
/* can we make more room in the buffer? */
if (buf != buf_head) {
memmove(buf_head, buf, len_buf);
buf = buf_head;
}
/* fetch as much as we can of the argument */
len_tmp = strncpy_from_user(&buf_head[len_buf], p,
len_max - len_buf);
if (len_tmp == -EFAULT) {
/* unable to copy from userspace */
send_sig(SIGKILL, current, 0);
goto out;
} else if (len_tmp == (len_max - len_buf)) {
/* buffer is not large enough */
require_data = true;
/* NOTE: if we are going to span multiple
* buffers force the encoding so we stand
* a chance at a sane len_full value and
* consistent record encoding */
encode = true;
len_full = len_full * 2;
p += len_tmp;
} else {
require_data = false;
if (!encode)
encode = audit_string_contains_control(
buf, len_tmp);
/* try to use a trusted value for len_full */
if (len_full < len_max)
len_full = (encode ?
len_tmp * 2 : len_tmp);
p += len_tmp + 1;
}
len_buf += len_tmp;
buf_head[len_buf] = '\0';
/* length of the buffer in the audit record? */
len_abuf = (encode ? len_buf * 2 : len_buf + 2);
}
| 167,019 |
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 bool write_hci_command(hci_packet_t type, const void *packet, size_t length) {
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_FD)
goto error;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(0x7F000001);
addr.sin_port = htons(8873);
if (connect(sock, (const struct sockaddr *)&addr, sizeof(addr)) == -1)
goto error;
if (send(sock, &type, 1, 0) != 1)
goto error;
if (send(sock, &length, 2, 0) != 2)
goto error;
if (send(sock, packet, length, 0) != (ssize_t)length)
goto error;
close(sock);
return true;
error:;
close(sock);
return false;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static bool write_hci_command(hci_packet_t type, const void *packet, size_t length) {
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_FD)
goto error;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(0x7F000001);
addr.sin_port = htons(8873);
if (TEMP_FAILURE_RETRY(connect(sock, (const struct sockaddr *)&addr, sizeof(addr))) == -1)
goto error;
if (TEMP_FAILURE_RETRY(send(sock, &type, 1, 0)) != 1)
goto error;
if (TEMP_FAILURE_RETRY(send(sock, &length, 2, 0)) != 2)
goto error;
if (TEMP_FAILURE_RETRY(send(sock, packet, length, 0)) != (ssize_t)length)
goto error;
close(sock);
return true;
error:;
close(sock);
return false;
}
| 173,492 |
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 si_conn_send(struct connection *conn)
{
struct stream_interface *si = conn->owner;
struct channel *chn = si->ob;
int ret;
if (chn->pipe && conn->xprt->snd_pipe) {
ret = conn->xprt->snd_pipe(conn, chn->pipe);
if (ret > 0)
chn->flags |= CF_WRITE_PARTIAL;
if (!chn->pipe->data) {
put_pipe(chn->pipe);
chn->pipe = NULL;
}
if (conn->flags & CO_FL_ERROR)
return;
}
/* At this point, the pipe is empty, but we may still have data pending
* in the normal buffer.
*/
if (!chn->buf->o)
return;
/* when we're here, we already know that there is no spliced
* data left, and that there are sendable buffered data.
*/
if (!(conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH | CO_FL_DATA_WR_SH | CO_FL_WAIT_DATA | CO_FL_HANDSHAKE))) {
/* check if we want to inform the kernel that we're interested in
* sending more data after this call. We want this if :
* - we're about to close after this last send and want to merge
* the ongoing FIN with the last segment.
* - we know we can't send everything at once and must get back
* here because of unaligned data
* - there is still a finite amount of data to forward
* The test is arranged so that the most common case does only 2
* tests.
*/
unsigned int send_flag = 0;
if ((!(chn->flags & (CF_NEVER_WAIT|CF_SEND_DONTWAIT)) &&
((chn->to_forward && chn->to_forward != CHN_INFINITE_FORWARD) ||
(chn->flags & CF_EXPECT_MORE))) ||
((chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) == CF_SHUTW_NOW))
send_flag |= CO_SFL_MSG_MORE;
if (chn->flags & CF_STREAMER)
send_flag |= CO_SFL_STREAMER;
ret = conn->xprt->snd_buf(conn, chn->buf, send_flag);
if (ret > 0) {
chn->flags |= CF_WRITE_PARTIAL;
if (!chn->buf->o) {
/* Always clear both flags once everything has been sent, they're one-shot */
chn->flags &= ~(CF_EXPECT_MORE | CF_SEND_DONTWAIT);
}
/* if some data remain in the buffer, it's only because the
* system buffers are full, we will try next time.
*/
}
}
return;
}
Commit Message:
CWE ID: CWE-189 | static void si_conn_send(struct connection *conn)
{
struct stream_interface *si = conn->owner;
struct channel *chn = si->ob;
int ret;
if (chn->pipe && conn->xprt->snd_pipe) {
ret = conn->xprt->snd_pipe(conn, chn->pipe);
if (ret > 0)
chn->flags |= CF_WRITE_PARTIAL | CF_WROTE_DATA;
if (!chn->pipe->data) {
put_pipe(chn->pipe);
chn->pipe = NULL;
}
if (conn->flags & CO_FL_ERROR)
return;
}
/* At this point, the pipe is empty, but we may still have data pending
* in the normal buffer.
*/
if (!chn->buf->o)
return;
/* when we're here, we already know that there is no spliced
* data left, and that there are sendable buffered data.
*/
if (!(conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH | CO_FL_DATA_WR_SH | CO_FL_WAIT_DATA | CO_FL_HANDSHAKE))) {
/* check if we want to inform the kernel that we're interested in
* sending more data after this call. We want this if :
* - we're about to close after this last send and want to merge
* the ongoing FIN with the last segment.
* - we know we can't send everything at once and must get back
* here because of unaligned data
* - there is still a finite amount of data to forward
* The test is arranged so that the most common case does only 2
* tests.
*/
unsigned int send_flag = 0;
if ((!(chn->flags & (CF_NEVER_WAIT|CF_SEND_DONTWAIT)) &&
((chn->to_forward && chn->to_forward != CHN_INFINITE_FORWARD) ||
(chn->flags & CF_EXPECT_MORE))) ||
((chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) == CF_SHUTW_NOW))
send_flag |= CO_SFL_MSG_MORE;
if (chn->flags & CF_STREAMER)
send_flag |= CO_SFL_STREAMER;
ret = conn->xprt->snd_buf(conn, chn->buf, send_flag);
if (ret > 0) {
chn->flags |= CF_WRITE_PARTIAL | CF_WROTE_DATA;
if (!chn->buf->o) {
/* Always clear both flags once everything has been sent, they're one-shot */
chn->flags &= ~(CF_EXPECT_MORE | CF_SEND_DONTWAIT);
}
/* if some data remain in the buffer, it's only because the
* system buffers are full, we will try next time.
*/
}
}
return;
}
| 164,991 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.