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: ssize_t NaClDescCustomRecvMsg(void* handle, NaClImcTypedMsgHdr* msg, int /* flags */) { if (msg->iov_length != 1) return -1; msg->ndesc_length = 0; // Messages with descriptors aren't supported yet. return static_cast<ssize_t>( ToAdapter(handle)->BlockingReceive(static_cast<char*>(msg->iov[0].base), msg->iov[0].length)); } 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
ssize_t NaClDescCustomRecvMsg(void* handle, NaClImcTypedMsgHdr* msg, int /* flags */) { if (msg->iov_length != 1) return -1; return static_cast<ssize_t>( ToAdapter(handle)->BlockingReceive(static_cast<char*>(msg->iov[0].base), msg->iov[0].length)); }
170,730
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::View> AutofillPopupBaseView::CreateWrapperView() { return nullptr; } 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::View> AutofillPopupBaseView::CreateWrapperView() {
172,095
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: cff_charset_load( CFF_Charset charset, FT_UInt num_glyphs, FT_Stream stream, FT_ULong base_offset, FT_ULong offset, FT_Bool invert ) { FT_Memory memory = stream->memory; FT_Error error = CFF_Err_Ok; FT_UShort glyph_sid; /* If the the offset is greater than 2, we have to parse the */ /* charset table. */ if ( offset > 2 ) { FT_UInt j; charset->offset = base_offset + offset; /* Get the format of the table. */ if ( FT_STREAM_SEEK( charset->offset ) || FT_READ_BYTE( charset->format ) ) goto Exit; /* Allocate memory for sids. */ if ( FT_NEW_ARRAY( charset->sids, num_glyphs ) ) goto Exit; /* assign the .notdef glyph */ charset->sids[0] = 0; switch ( charset->format ) { case 0: if ( num_glyphs > 0 ) { if ( FT_FRAME_ENTER( ( num_glyphs - 1 ) * 2 ) ) goto Exit; for ( j = 1; j < num_glyphs; j++ ) charset->sids[j] = FT_GET_USHORT(); FT_FRAME_EXIT(); } /* Read the first glyph sid of the range. */ if ( FT_READ_USHORT( glyph_sid ) ) goto Exit; /* Read the number of glyphs in the range. */ if ( charset->format == 2 ) { if ( FT_READ_USHORT( nleft ) ) goto Exit; } else { if ( FT_READ_BYTE( nleft ) ) goto Exit; } /* Fill in the range of sids -- `nleft + 1' glyphs. */ for ( i = 0; j < num_glyphs && i <= nleft; i++, j++, glyph_sid++ ) charset->sids[j] = glyph_sid; } } break; default: FT_ERROR(( "cff_charset_load: invalid table format!\n" )); error = CFF_Err_Invalid_File_Format; goto Exit; } Commit Message: CWE ID: CWE-189
cff_charset_load( CFF_Charset charset, FT_UInt num_glyphs, FT_Stream stream, FT_ULong base_offset, FT_ULong offset, FT_Bool invert ) { FT_Memory memory = stream->memory; FT_Error error = CFF_Err_Ok; FT_UShort glyph_sid; /* If the the offset is greater than 2, we have to parse the */ /* charset table. */ if ( offset > 2 ) { FT_UInt j; charset->offset = base_offset + offset; /* Get the format of the table. */ if ( FT_STREAM_SEEK( charset->offset ) || FT_READ_BYTE( charset->format ) ) goto Exit; /* Allocate memory for sids. */ if ( FT_NEW_ARRAY( charset->sids, num_glyphs ) ) goto Exit; /* assign the .notdef glyph */ charset->sids[0] = 0; switch ( charset->format ) { case 0: if ( num_glyphs > 0 ) { if ( FT_FRAME_ENTER( ( num_glyphs - 1 ) * 2 ) ) goto Exit; for ( j = 1; j < num_glyphs; j++ ) { FT_UShort sid = FT_GET_USHORT(); /* this constant is given in the CFF specification */ if ( sid < 65000 ) charset->sids[j] = sid; else { FT_ERROR(( "cff_charset_load:" " invalid SID value %d set to zero\n", sid )); charset->sids[j] = 0; } } FT_FRAME_EXIT(); } /* Read the first glyph sid of the range. */ if ( FT_READ_USHORT( glyph_sid ) ) goto Exit; /* Read the number of glyphs in the range. */ if ( charset->format == 2 ) { if ( FT_READ_USHORT( nleft ) ) goto Exit; } else { if ( FT_READ_BYTE( nleft ) ) goto Exit; } /* Fill in the range of sids -- `nleft + 1' glyphs. */ for ( i = 0; j < num_glyphs && i <= nleft; i++, j++, glyph_sid++ ) charset->sids[j] = glyph_sid; } } break; default: FT_ERROR(( "cff_charset_load: invalid table format!\n" )); error = CFF_Err_Invalid_File_Format; goto Exit; }
164,743
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: ext2_set_acl(struct inode *inode, struct posix_acl *acl, int type) { int name_index; void *value = NULL; size_t size = 0; int error; switch(type) { case ACL_TYPE_ACCESS: name_index = EXT2_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_equiv_mode(acl, &inode->i_mode); if (error < 0) return error; else { inode->i_ctime = CURRENT_TIME_SEC; mark_inode_dirty(inode); if (error == 0) acl = NULL; } } break; case ACL_TYPE_DEFAULT: name_index = EXT2_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = ext2_acl_to_disk(acl, &size); if (IS_ERR(value)) return (int)PTR_ERR(value); } error = ext2_xattr_set(inode, name_index, "", value, size, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Andreas Gruenbacher <[email protected]> CWE ID: CWE-285
ext2_set_acl(struct inode *inode, struct posix_acl *acl, int type) { int name_index; void *value = NULL; size_t size = 0; int error; switch(type) { case ACL_TYPE_ACCESS: name_index = EXT2_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_update_mode(inode, &inode->i_mode, &acl); if (error) return error; inode->i_ctime = CURRENT_TIME_SEC; mark_inode_dirty(inode); } break; case ACL_TYPE_DEFAULT: name_index = EXT2_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = ext2_acl_to_disk(acl, &size); if (IS_ERR(value)) return (int)PTR_ERR(value); } error = ext2_xattr_set(inode, name_index, "", value, size, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; }
166,969
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 keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen) { struct key *key; key_ref_t key_ref; long ret; /* find the key first */ key_ref = lookup_user_key(keyid, 0, 0); if (IS_ERR(key_ref)) { ret = -ENOKEY; goto error; } key = key_ref_to_ptr(key_ref); if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) { ret = -ENOKEY; goto error2; } /* see if we can read it directly */ ret = key_permission(key_ref, KEY_NEED_READ); if (ret == 0) goto can_read_key; if (ret != -EACCES) goto error2; /* we can't; see if it's searchable from this process's keyrings * - we automatically take account of the fact that it may be * dangling off an instantiation key */ if (!is_key_possessed(key_ref)) { ret = -EACCES; goto error2; } /* the key is probably readable - now try to read it */ can_read_key: ret = -EOPNOTSUPP; if (key->type->read) { /* Read the data with the semaphore held (since we might sleep) * to protect against the key being updated or revoked. */ down_read(&key->sem); ret = key_validate(key); if (ret == 0) ret = key->type->read(key, buffer, buflen); up_read(&key->sem); } error2: key_put(key); error: return ret; } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20
long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen) { struct key *key; key_ref_t key_ref; long ret; /* find the key first */ key_ref = lookup_user_key(keyid, 0, 0); if (IS_ERR(key_ref)) { ret = -ENOKEY; goto error; } key = key_ref_to_ptr(key_ref); ret = key_read_state(key); if (ret < 0) goto error2; /* Negatively instantiated */ /* see if we can read it directly */ ret = key_permission(key_ref, KEY_NEED_READ); if (ret == 0) goto can_read_key; if (ret != -EACCES) goto error2; /* we can't; see if it's searchable from this process's keyrings * - we automatically take account of the fact that it may be * dangling off an instantiation key */ if (!is_key_possessed(key_ref)) { ret = -EACCES; goto error2; } /* the key is probably readable - now try to read it */ can_read_key: ret = -EOPNOTSUPP; if (key->type->read) { /* Read the data with the semaphore held (since we might sleep) * to protect against the key being updated or revoked. */ down_read(&key->sem); ret = key_validate(key); if (ret == 0) ret = key->type->read(key, buffer, buflen); up_read(&key->sem); } error2: key_put(key); error: return ret; }
167,701
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CL_Init( void ) { Com_Printf( "----- Client Initialization -----\n" ); Con_Init (); if(!com_fullyInitialized) { CL_ClearState(); clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED cl_oldGameSet = qfalse; } cls.realtime = 0; CL_InitInput (); cl_noprint = Cvar_Get( "cl_noprint", "0", 0 ); #ifdef UPDATE_SERVER_NAME cl_motd = Cvar_Get ("cl_motd", "1", 0); #endif cl_timeout = Cvar_Get ("cl_timeout", "200", 0); cl_timeNudge = Cvar_Get ("cl_timeNudge", "0", CVAR_TEMP ); cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP ); cl_showSend = Cvar_Get ("cl_showSend", "0", CVAR_TEMP ); cl_showTimeDelta = Cvar_Get ("cl_showTimeDelta", "0", CVAR_TEMP ); cl_freezeDemo = Cvar_Get ("cl_freezeDemo", "0", CVAR_TEMP ); rcon_client_password = Cvar_Get ("rconPassword", "", CVAR_TEMP ); cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP ); cl_timedemo = Cvar_Get ("timedemo", "0", 0); cl_timedemoLog = Cvar_Get ("cl_timedemoLog", "", CVAR_ARCHIVE); cl_autoRecordDemo = Cvar_Get ("cl_autoRecordDemo", "0", CVAR_ARCHIVE); cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE); cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE); cl_forceavidemo = Cvar_Get ("cl_forceavidemo", "0", 0); rconAddress = Cvar_Get ("rconAddress", "", 0); cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_ARCHIVE); cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "140", CVAR_ARCHIVE); cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", 0); cl_maxpackets = Cvar_Get ("cl_maxpackets", "30", CVAR_ARCHIVE ); cl_packetdup = Cvar_Get ("cl_packetdup", "1", CVAR_ARCHIVE ); cl_run = Cvar_Get ("cl_run", "1", CVAR_ARCHIVE); cl_sensitivity = Cvar_Get ("sensitivity", "5", CVAR_ARCHIVE); cl_mouseAccel = Cvar_Get ("cl_mouseAccel", "0", CVAR_ARCHIVE); cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE ); cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE ); cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE ); Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse); cl_showMouseRate = Cvar_Get ("cl_showmouserate", "0", 0); cl_allowDownload = Cvar_Get ("cl_allowDownload", "0", CVAR_ARCHIVE); #ifdef USE_CURL_DLOPEN cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE); #endif cl_conXOffset = Cvar_Get ("cl_conXOffset", "0", 0); #ifdef __APPLE__ cl_inGameVideo = Cvar_Get ("r_inGameVideo", "0", CVAR_ARCHIVE); #else cl_inGameVideo = Cvar_Get ("r_inGameVideo", "1", CVAR_ARCHIVE); #endif cl_serverStatusResendTime = Cvar_Get ("cl_serverStatusResendTime", "750", 0); Cvar_Get ("cg_autoswitch", "1", CVAR_ARCHIVE); m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE); m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_ARCHIVE); m_forward = Cvar_Get ("m_forward", "0.25", CVAR_ARCHIVE); m_side = Cvar_Get ("m_side", "0.25", CVAR_ARCHIVE); #ifdef __APPLE__ m_filter = Cvar_Get ("m_filter", "1", CVAR_ARCHIVE); #else m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE); #endif j_pitch = Cvar_Get ("j_pitch", "0.022", CVAR_ARCHIVE); j_yaw = Cvar_Get ("j_yaw", "-0.022", CVAR_ARCHIVE); j_forward = Cvar_Get ("j_forward", "-0.25", CVAR_ARCHIVE); j_side = Cvar_Get ("j_side", "0.25", CVAR_ARCHIVE); j_up = Cvar_Get ("j_up", "0", CVAR_ARCHIVE); j_pitch_axis = Cvar_Get ("j_pitch_axis", "3", CVAR_ARCHIVE); j_yaw_axis = Cvar_Get ("j_yaw_axis", "2", CVAR_ARCHIVE); j_forward_axis = Cvar_Get ("j_forward_axis", "1", CVAR_ARCHIVE); j_side_axis = Cvar_Get ("j_side_axis", "0", CVAR_ARCHIVE); j_up_axis = Cvar_Get ("j_up_axis", "4", CVAR_ARCHIVE); Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM ); Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE ); cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE); cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE); cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE); Cvar_Get ("name", "UnnamedPlayer", CVAR_USERINFO | CVAR_ARCHIVE ); cl_rate = Cvar_Get ("rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("model", "sarge", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("headmodel", "sarge", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("team_model", "james", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("team_headmodel", "*james", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("g_redTeam", "Stroggs", CVAR_SERVERINFO | CVAR_ARCHIVE); Cvar_Get ("g_blueTeam", "Pagans", CVAR_SERVERINFO | CVAR_ARCHIVE); Cvar_Get ("color1", "4", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("color2", "5", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("teamtask", "0", CVAR_USERINFO ); Cvar_Get ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("password", "", CVAR_USERINFO); Cvar_Get ("cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE ); #ifdef USE_MUMBLE cl_useMumble = Cvar_Get ("cl_useMumble", "0", CVAR_ARCHIVE | CVAR_LATCH); cl_mumbleScale = Cvar_Get ("cl_mumbleScale", "0.0254", CVAR_ARCHIVE); #endif #ifdef USE_VOIP cl_voipSend = Cvar_Get ("cl_voipSend", "0", 0); cl_voipSendTarget = Cvar_Get ("cl_voipSendTarget", "spatial", 0); cl_voipGainDuringCapture = Cvar_Get ("cl_voipGainDuringCapture", "0.2", CVAR_ARCHIVE); cl_voipCaptureMult = Cvar_Get ("cl_voipCaptureMult", "2.0", CVAR_ARCHIVE); cl_voipUseVAD = Cvar_Get ("cl_voipUseVAD", "0", CVAR_ARCHIVE); cl_voipVADThreshold = Cvar_Get ("cl_voipVADThreshold", "0.25", CVAR_ARCHIVE); cl_voipShowMeter = Cvar_Get ("cl_voipShowMeter", "1", CVAR_ARCHIVE); cl_voip = Cvar_Get ("cl_voip", "1", CVAR_ARCHIVE); Cvar_CheckRange( cl_voip, 0, 1, qtrue ); cl_voipProtocol = Cvar_Get ("cl_voipProtocol", cl_voip->integer ? "opus" : "", CVAR_USERINFO | CVAR_ROM); #endif Cvar_Get ("cg_viewsize", "100", CVAR_ARCHIVE ); Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM); Cmd_AddCommand ("cmd", CL_ForwardToServer_f); Cmd_AddCommand ("configstrings", CL_Configstrings_f); Cmd_AddCommand ("clientinfo", CL_Clientinfo_f); Cmd_AddCommand ("snd_restart", CL_Snd_Restart_f); Cmd_AddCommand ("vid_restart", CL_Vid_Restart_f); Cmd_AddCommand ("disconnect", CL_Disconnect_f); Cmd_AddCommand ("record", CL_Record_f); Cmd_AddCommand ("demo", CL_PlayDemo_f); Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName ); Cmd_AddCommand ("cinematic", CL_PlayCinematic_f); Cmd_AddCommand ("stoprecord", CL_StopRecord_f); Cmd_AddCommand ("connect", CL_Connect_f); Cmd_AddCommand ("reconnect", CL_Reconnect_f); Cmd_AddCommand ("localservers", CL_LocalServers_f); Cmd_AddCommand ("globalservers", CL_GlobalServers_f); Cmd_AddCommand ("rcon", CL_Rcon_f); Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon ); Cmd_AddCommand ("ping", CL_Ping_f ); Cmd_AddCommand ("serverstatus", CL_ServerStatus_f ); Cmd_AddCommand ("showip", CL_ShowIP_f ); Cmd_AddCommand ("fs_openedList", CL_OpenedPK3List_f ); Cmd_AddCommand ("fs_referencedList", CL_ReferencedPK3List_f ); Cmd_AddCommand ("model", CL_SetModel_f ); Cmd_AddCommand ("video", CL_Video_f ); Cmd_AddCommand ("stopvideo", CL_StopVideo_f ); if( !com_dedicated->integer ) { Cmd_AddCommand ("sayto", CL_Sayto_f ); Cmd_SetCommandCompletionFunc( "sayto", CL_CompletePlayerName ); } CL_InitRef(); SCR_Init (); Cvar_Set( "cl_running", "1" ); CL_GenerateQKey(); Cvar_Get( "cl_guid", "", CVAR_USERINFO | CVAR_ROM ); CL_UpdateGUID( NULL, 0 ); Com_Printf( "----- Client Initialization Complete -----\n" ); } Commit Message: Don't load .pk3s as .dlls, and don't load user config files from .pk3s. CWE ID: CWE-269
void CL_Init( void ) { Com_Printf( "----- Client Initialization -----\n" ); Con_Init (); if(!com_fullyInitialized) { CL_ClearState(); clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED cl_oldGameSet = qfalse; } cls.realtime = 0; CL_InitInput (); cl_noprint = Cvar_Get( "cl_noprint", "0", 0 ); #ifdef UPDATE_SERVER_NAME cl_motd = Cvar_Get ("cl_motd", "1", 0); #endif cl_timeout = Cvar_Get ("cl_timeout", "200", 0); cl_timeNudge = Cvar_Get ("cl_timeNudge", "0", CVAR_TEMP ); cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP ); cl_showSend = Cvar_Get ("cl_showSend", "0", CVAR_TEMP ); cl_showTimeDelta = Cvar_Get ("cl_showTimeDelta", "0", CVAR_TEMP ); cl_freezeDemo = Cvar_Get ("cl_freezeDemo", "0", CVAR_TEMP ); rcon_client_password = Cvar_Get ("rconPassword", "", CVAR_TEMP ); cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP ); cl_timedemo = Cvar_Get ("timedemo", "0", 0); cl_timedemoLog = Cvar_Get ("cl_timedemoLog", "", CVAR_ARCHIVE); cl_autoRecordDemo = Cvar_Get ("cl_autoRecordDemo", "0", CVAR_ARCHIVE); cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE); cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE); cl_forceavidemo = Cvar_Get ("cl_forceavidemo", "0", 0); rconAddress = Cvar_Get ("rconAddress", "", 0); cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_ARCHIVE); cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "140", CVAR_ARCHIVE); cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", 0); cl_maxpackets = Cvar_Get ("cl_maxpackets", "30", CVAR_ARCHIVE ); cl_packetdup = Cvar_Get ("cl_packetdup", "1", CVAR_ARCHIVE ); cl_run = Cvar_Get ("cl_run", "1", CVAR_ARCHIVE); cl_sensitivity = Cvar_Get ("sensitivity", "5", CVAR_ARCHIVE); cl_mouseAccel = Cvar_Get ("cl_mouseAccel", "0", CVAR_ARCHIVE); cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE ); cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE ); cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE ); Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse); cl_showMouseRate = Cvar_Get ("cl_showmouserate", "0", 0); cl_allowDownload = Cvar_Get ("cl_allowDownload", "0", CVAR_ARCHIVE); #ifdef USE_CURL_DLOPEN cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE | CVAR_PROTECTED); #endif cl_conXOffset = Cvar_Get ("cl_conXOffset", "0", 0); #ifdef __APPLE__ cl_inGameVideo = Cvar_Get ("r_inGameVideo", "0", CVAR_ARCHIVE); #else cl_inGameVideo = Cvar_Get ("r_inGameVideo", "1", CVAR_ARCHIVE); #endif cl_serverStatusResendTime = Cvar_Get ("cl_serverStatusResendTime", "750", 0); Cvar_Get ("cg_autoswitch", "1", CVAR_ARCHIVE); m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE); m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_ARCHIVE); m_forward = Cvar_Get ("m_forward", "0.25", CVAR_ARCHIVE); m_side = Cvar_Get ("m_side", "0.25", CVAR_ARCHIVE); #ifdef __APPLE__ m_filter = Cvar_Get ("m_filter", "1", CVAR_ARCHIVE); #else m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE); #endif j_pitch = Cvar_Get ("j_pitch", "0.022", CVAR_ARCHIVE); j_yaw = Cvar_Get ("j_yaw", "-0.022", CVAR_ARCHIVE); j_forward = Cvar_Get ("j_forward", "-0.25", CVAR_ARCHIVE); j_side = Cvar_Get ("j_side", "0.25", CVAR_ARCHIVE); j_up = Cvar_Get ("j_up", "0", CVAR_ARCHIVE); j_pitch_axis = Cvar_Get ("j_pitch_axis", "3", CVAR_ARCHIVE); j_yaw_axis = Cvar_Get ("j_yaw_axis", "2", CVAR_ARCHIVE); j_forward_axis = Cvar_Get ("j_forward_axis", "1", CVAR_ARCHIVE); j_side_axis = Cvar_Get ("j_side_axis", "0", CVAR_ARCHIVE); j_up_axis = Cvar_Get ("j_up_axis", "4", CVAR_ARCHIVE); Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM ); Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE ); cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE); cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE); cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE); Cvar_Get ("name", "UnnamedPlayer", CVAR_USERINFO | CVAR_ARCHIVE ); cl_rate = Cvar_Get ("rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("model", "sarge", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("headmodel", "sarge", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("team_model", "james", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("team_headmodel", "*james", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("g_redTeam", "Stroggs", CVAR_SERVERINFO | CVAR_ARCHIVE); Cvar_Get ("g_blueTeam", "Pagans", CVAR_SERVERINFO | CVAR_ARCHIVE); Cvar_Get ("color1", "4", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("color2", "5", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("teamtask", "0", CVAR_USERINFO ); Cvar_Get ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("password", "", CVAR_USERINFO); Cvar_Get ("cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE ); #ifdef USE_MUMBLE cl_useMumble = Cvar_Get ("cl_useMumble", "0", CVAR_ARCHIVE | CVAR_LATCH); cl_mumbleScale = Cvar_Get ("cl_mumbleScale", "0.0254", CVAR_ARCHIVE); #endif #ifdef USE_VOIP cl_voipSend = Cvar_Get ("cl_voipSend", "0", 0); cl_voipSendTarget = Cvar_Get ("cl_voipSendTarget", "spatial", 0); cl_voipGainDuringCapture = Cvar_Get ("cl_voipGainDuringCapture", "0.2", CVAR_ARCHIVE); cl_voipCaptureMult = Cvar_Get ("cl_voipCaptureMult", "2.0", CVAR_ARCHIVE); cl_voipUseVAD = Cvar_Get ("cl_voipUseVAD", "0", CVAR_ARCHIVE); cl_voipVADThreshold = Cvar_Get ("cl_voipVADThreshold", "0.25", CVAR_ARCHIVE); cl_voipShowMeter = Cvar_Get ("cl_voipShowMeter", "1", CVAR_ARCHIVE); cl_voip = Cvar_Get ("cl_voip", "1", CVAR_ARCHIVE); Cvar_CheckRange( cl_voip, 0, 1, qtrue ); cl_voipProtocol = Cvar_Get ("cl_voipProtocol", cl_voip->integer ? "opus" : "", CVAR_USERINFO | CVAR_ROM); #endif Cvar_Get ("cg_viewsize", "100", CVAR_ARCHIVE ); Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM); Cmd_AddCommand ("cmd", CL_ForwardToServer_f); Cmd_AddCommand ("configstrings", CL_Configstrings_f); Cmd_AddCommand ("clientinfo", CL_Clientinfo_f); Cmd_AddCommand ("snd_restart", CL_Snd_Restart_f); Cmd_AddCommand ("vid_restart", CL_Vid_Restart_f); Cmd_AddCommand ("disconnect", CL_Disconnect_f); Cmd_AddCommand ("record", CL_Record_f); Cmd_AddCommand ("demo", CL_PlayDemo_f); Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName ); Cmd_AddCommand ("cinematic", CL_PlayCinematic_f); Cmd_AddCommand ("stoprecord", CL_StopRecord_f); Cmd_AddCommand ("connect", CL_Connect_f); Cmd_AddCommand ("reconnect", CL_Reconnect_f); Cmd_AddCommand ("localservers", CL_LocalServers_f); Cmd_AddCommand ("globalservers", CL_GlobalServers_f); Cmd_AddCommand ("rcon", CL_Rcon_f); Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon ); Cmd_AddCommand ("ping", CL_Ping_f ); Cmd_AddCommand ("serverstatus", CL_ServerStatus_f ); Cmd_AddCommand ("showip", CL_ShowIP_f ); Cmd_AddCommand ("fs_openedList", CL_OpenedPK3List_f ); Cmd_AddCommand ("fs_referencedList", CL_ReferencedPK3List_f ); Cmd_AddCommand ("model", CL_SetModel_f ); Cmd_AddCommand ("video", CL_Video_f ); Cmd_AddCommand ("stopvideo", CL_StopVideo_f ); if( !com_dedicated->integer ) { Cmd_AddCommand ("sayto", CL_Sayto_f ); Cmd_SetCommandCompletionFunc( "sayto", CL_CompletePlayerName ); } CL_InitRef(); SCR_Init (); Cvar_Set( "cl_running", "1" ); CL_GenerateQKey(); Cvar_Get( "cl_guid", "", CVAR_USERINFO | CVAR_ROM ); CL_UpdateGUID( NULL, 0 ); Com_Printf( "----- Client Initialization Complete -----\n" ); }
170,088
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: SchedulerObject::remove(std::string key, std::string &reason, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (!abortJob(id.cluster, id.proc, reason.c_str(), true // Always perform within a transaction )) { text = "Failed to remove job"; return false; } return true; } Commit Message: CWE ID: CWE-20
SchedulerObject::remove(std::string key, std::string &reason, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster <= 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (!abortJob(id.cluster, id.proc, reason.c_str(), true // Always perform within a transaction )) { text = "Failed to remove job"; return false; } return true; }
164,834
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 nbd_recv_coroutines_enter_all(NBDClientSession *s) { int i; for (i = 0; i < MAX_NBD_REQUESTS; i++) { qemu_coroutine_enter(s->recv_coroutine[i]); qemu_coroutine_enter(s->recv_coroutine[i]); } } Commit Message: CWE ID: CWE-20
static void nbd_recv_coroutines_enter_all(NBDClientSession *s) static void nbd_recv_coroutines_enter_all(BlockDriverState *bs) { NBDClientSession *s = nbd_get_client_session(bs); int i; for (i = 0; i < MAX_NBD_REQUESTS; i++) { qemu_coroutine_enter(s->recv_coroutine[i]); qemu_coroutine_enter(s->recv_coroutine[i]); } }
165,449
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 MediaStreamManager::StopStreamDevice(int render_process_id, int render_frame_id, const std::string& device_id, int session_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DVLOG(1) << "StopStreamDevice({render_frame_id = " << render_frame_id << "} " << ", {device_id = " << device_id << "}, session_id = " << session_id << "})"; Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
void MediaStreamManager::StopStreamDevice(int render_process_id, int render_frame_id, int requester_id, const std::string& device_id, int session_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DVLOG(1) << "StopStreamDevice({render_frame_id = " << render_frame_id << "} " << ", {device_id = " << device_id << "}, session_id = " << session_id << "})";
173,106
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: PHP_FUNCTION(mb_split) { char *arg_pattern; int arg_pattern_len; php_mb_regex_t *re; OnigRegion *regs = NULL; char *string; OnigUChar *pos, *chunk_pos; int string_len; int n, err; long count = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", &arg_pattern, &arg_pattern_len, &string, &string_len, &count) == FAILURE) { RETURN_FALSE; } if (count > 0) { count--; } /* create regex pattern buffer */ if ((re = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, MBREX(regex_default_options), MBREX(current_mbctype), MBREX(regex_default_syntax) TSRMLS_CC)) == NULL) { RETURN_FALSE; } array_init(return_value); chunk_pos = pos = (OnigUChar *)string; err = 0; regs = onig_region_new(); /* churn through str, generating array entries as we go */ while (count != 0 && (pos - (OnigUChar *)string) < string_len) { int beg, end; err = onig_search(re, (OnigUChar *)string, (OnigUChar *)(string + string_len), pos, (OnigUChar *)(string + string_len), regs, 0); if (err < 0) { break; } beg = regs->beg[0], end = regs->end[0]; /* add it to the array */ if ((pos - (OnigUChar *)string) < end) { if (beg < string_len && beg >= (chunk_pos - (OnigUChar *)string)) { add_next_index_stringl(return_value, (char *)chunk_pos, ((OnigUChar *)(string + beg) - chunk_pos), 1); --count; } else { err = -2; break; } /* point at our new starting point */ chunk_pos = pos = (OnigUChar *)string + end; } else { pos++; } onig_region_free(regs, 0); } onig_region_free(regs, 1); /* see if we encountered an error */ if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); php_error_docref(NULL TSRMLS_CC, E_WARNING, "mbregex search failure in mbsplit(): %s", err_str); zval_dtor(return_value); RETURN_FALSE; } /* otherwise we just have one last element to add to the array */ n = ((OnigUChar *)(string + string_len) - chunk_pos); if (n > 0) { add_next_index_stringl(return_value, (char *)chunk_pos, n, 1); } else { add_next_index_stringl(return_value, "", 0, 1); } } Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free CWE ID: CWE-415
PHP_FUNCTION(mb_split) { char *arg_pattern; int arg_pattern_len; php_mb_regex_t *re; OnigRegion *regs = NULL; char *string; OnigUChar *pos, *chunk_pos; int string_len; int n, err; long count = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", &arg_pattern, &arg_pattern_len, &string, &string_len, &count) == FAILURE) { RETURN_FALSE; } if (count > 0) { count--; } /* create regex pattern buffer */ if ((re = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, MBREX(regex_default_options), MBREX(current_mbctype), MBREX(regex_default_syntax) TSRMLS_CC)) == NULL) { RETURN_FALSE; } array_init(return_value); chunk_pos = pos = (OnigUChar *)string; err = 0; regs = onig_region_new(); /* churn through str, generating array entries as we go */ while (count != 0 && (pos - (OnigUChar *)string) < string_len) { int beg, end; err = onig_search(re, (OnigUChar *)string, (OnigUChar *)(string + string_len), pos, (OnigUChar *)(string + string_len), regs, 0); if (err < 0) { break; } beg = regs->beg[0], end = regs->end[0]; /* add it to the array */ if ((pos - (OnigUChar *)string) < end) { if (beg < string_len && beg >= (chunk_pos - (OnigUChar *)string)) { add_next_index_stringl(return_value, (char *)chunk_pos, ((OnigUChar *)(string + beg) - chunk_pos), 1); --count; } else { err = -2; break; } /* point at our new starting point */ chunk_pos = pos = (OnigUChar *)string + end; } else { pos++; } onig_region_free(regs, 0); } onig_region_free(regs, 1); /* see if we encountered an error */ if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); php_error_docref(NULL TSRMLS_CC, E_WARNING, "mbregex search failure in mbsplit(): %s", err_str); zval_dtor(return_value); RETURN_FALSE; } /* otherwise we just have one last element to add to the array */ n = ((OnigUChar *)(string + string_len) - chunk_pos); if (n > 0) { add_next_index_stringl(return_value, (char *)chunk_pos, n, 1); } else { add_next_index_stringl(return_value, "", 0, 1); } }
167,115
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 __u8 *nci_extract_rf_params_nfcb_passive_poll(struct nci_dev *ndev, struct rf_tech_specific_params_nfcb_poll *nfcb_poll, __u8 *data) { nfcb_poll->sensb_res_len = *data++; pr_debug("sensb_res_len %d\n", nfcb_poll->sensb_res_len); memcpy(nfcb_poll->sensb_res, data, nfcb_poll->sensb_res_len); data += nfcb_poll->sensb_res_len; return data; } Commit Message: NFC: Prevent multiple buffer overflows in NCI Fix multiple remotely-exploitable stack-based buffer overflows due to the NCI code pulling length fields directly from incoming frames and copying too much data into statically-sized arrays. Signed-off-by: Dan Rosenberg <[email protected]> Cc: [email protected] Cc: [email protected] Cc: Lauro Ramos Venancio <[email protected]> Cc: Aloisio Almeida Jr <[email protected]> Cc: Samuel Ortiz <[email protected]> Cc: David S. Miller <[email protected]> Acked-by: Ilan Elias <[email protected]> Signed-off-by: Samuel Ortiz <[email protected]> CWE ID: CWE-119
static __u8 *nci_extract_rf_params_nfcb_passive_poll(struct nci_dev *ndev, struct rf_tech_specific_params_nfcb_poll *nfcb_poll, __u8 *data) { nfcb_poll->sensb_res_len = min_t(__u8, *data++, NFC_SENSB_RES_MAXSIZE); pr_debug("sensb_res_len %d\n", nfcb_poll->sensb_res_len); memcpy(nfcb_poll->sensb_res, data, nfcb_poll->sensb_res_len); data += nfcb_poll->sensb_res_len; return data; }
166,202
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 snd_timer_user_params(struct file *file, struct snd_timer_params __user *_params) { struct snd_timer_user *tu; struct snd_timer_params params; struct snd_timer *t; struct snd_timer_read *tr; struct snd_timer_tread *ttr; int err; tu = file->private_data; if (!tu->timeri) return -EBADFD; t = tu->timeri->timer; if (!t) return -EBADFD; if (copy_from_user(&params, _params, sizeof(params))) return -EFAULT; if (!(t->hw.flags & SNDRV_TIMER_HW_SLAVE) && params.ticks < 1) { err = -EINVAL; goto _end; } if (params.queue_size > 0 && (params.queue_size < 32 || params.queue_size > 1024)) { err = -EINVAL; goto _end; } if (params.filter & ~((1<<SNDRV_TIMER_EVENT_RESOLUTION)| (1<<SNDRV_TIMER_EVENT_TICK)| (1<<SNDRV_TIMER_EVENT_START)| (1<<SNDRV_TIMER_EVENT_STOP)| (1<<SNDRV_TIMER_EVENT_CONTINUE)| (1<<SNDRV_TIMER_EVENT_PAUSE)| (1<<SNDRV_TIMER_EVENT_SUSPEND)| (1<<SNDRV_TIMER_EVENT_RESUME)| (1<<SNDRV_TIMER_EVENT_MSTART)| (1<<SNDRV_TIMER_EVENT_MSTOP)| (1<<SNDRV_TIMER_EVENT_MCONTINUE)| (1<<SNDRV_TIMER_EVENT_MPAUSE)| (1<<SNDRV_TIMER_EVENT_MSUSPEND)| (1<<SNDRV_TIMER_EVENT_MRESUME))) { err = -EINVAL; goto _end; } snd_timer_stop(tu->timeri); spin_lock_irq(&t->lock); tu->timeri->flags &= ~(SNDRV_TIMER_IFLG_AUTO| SNDRV_TIMER_IFLG_EXCLUSIVE| SNDRV_TIMER_IFLG_EARLY_EVENT); if (params.flags & SNDRV_TIMER_PSFLG_AUTO) tu->timeri->flags |= SNDRV_TIMER_IFLG_AUTO; if (params.flags & SNDRV_TIMER_PSFLG_EXCLUSIVE) tu->timeri->flags |= SNDRV_TIMER_IFLG_EXCLUSIVE; if (params.flags & SNDRV_TIMER_PSFLG_EARLY_EVENT) tu->timeri->flags |= SNDRV_TIMER_IFLG_EARLY_EVENT; spin_unlock_irq(&t->lock); if (params.queue_size > 0 && (unsigned int)tu->queue_size != params.queue_size) { if (tu->tread) { ttr = kmalloc(params.queue_size * sizeof(*ttr), GFP_KERNEL); if (ttr) { kfree(tu->tqueue); tu->queue_size = params.queue_size; tu->tqueue = ttr; } } else { tr = kmalloc(params.queue_size * sizeof(*tr), GFP_KERNEL); if (tr) { kfree(tu->queue); tu->queue_size = params.queue_size; tu->queue = tr; } } } tu->qhead = tu->qtail = tu->qused = 0; if (tu->timeri->flags & SNDRV_TIMER_IFLG_EARLY_EVENT) { if (tu->tread) { struct snd_timer_tread tread; tread.event = SNDRV_TIMER_EVENT_EARLY; tread.tstamp.tv_sec = 0; tread.tstamp.tv_nsec = 0; tread.val = 0; snd_timer_user_append_to_tqueue(tu, &tread); } else { struct snd_timer_read *r = &tu->queue[0]; r->resolution = 0; r->ticks = 0; tu->qused++; tu->qtail++; } } tu->filter = params.filter; tu->ticks = params.ticks; err = 0; _end: if (copy_to_user(_params, &params, sizeof(params))) return -EFAULT; return err; } Commit Message: ALSA: timer: Fix leak in SNDRV_TIMER_IOCTL_PARAMS The stack object “tread” has a total size of 32 bytes. Its field “event” and “val” both contain 4 bytes padding. These 8 bytes padding bytes are sent to user without being initialized. Signed-off-by: Kangjie Lu <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-200
static int snd_timer_user_params(struct file *file, struct snd_timer_params __user *_params) { struct snd_timer_user *tu; struct snd_timer_params params; struct snd_timer *t; struct snd_timer_read *tr; struct snd_timer_tread *ttr; int err; tu = file->private_data; if (!tu->timeri) return -EBADFD; t = tu->timeri->timer; if (!t) return -EBADFD; if (copy_from_user(&params, _params, sizeof(params))) return -EFAULT; if (!(t->hw.flags & SNDRV_TIMER_HW_SLAVE) && params.ticks < 1) { err = -EINVAL; goto _end; } if (params.queue_size > 0 && (params.queue_size < 32 || params.queue_size > 1024)) { err = -EINVAL; goto _end; } if (params.filter & ~((1<<SNDRV_TIMER_EVENT_RESOLUTION)| (1<<SNDRV_TIMER_EVENT_TICK)| (1<<SNDRV_TIMER_EVENT_START)| (1<<SNDRV_TIMER_EVENT_STOP)| (1<<SNDRV_TIMER_EVENT_CONTINUE)| (1<<SNDRV_TIMER_EVENT_PAUSE)| (1<<SNDRV_TIMER_EVENT_SUSPEND)| (1<<SNDRV_TIMER_EVENT_RESUME)| (1<<SNDRV_TIMER_EVENT_MSTART)| (1<<SNDRV_TIMER_EVENT_MSTOP)| (1<<SNDRV_TIMER_EVENT_MCONTINUE)| (1<<SNDRV_TIMER_EVENT_MPAUSE)| (1<<SNDRV_TIMER_EVENT_MSUSPEND)| (1<<SNDRV_TIMER_EVENT_MRESUME))) { err = -EINVAL; goto _end; } snd_timer_stop(tu->timeri); spin_lock_irq(&t->lock); tu->timeri->flags &= ~(SNDRV_TIMER_IFLG_AUTO| SNDRV_TIMER_IFLG_EXCLUSIVE| SNDRV_TIMER_IFLG_EARLY_EVENT); if (params.flags & SNDRV_TIMER_PSFLG_AUTO) tu->timeri->flags |= SNDRV_TIMER_IFLG_AUTO; if (params.flags & SNDRV_TIMER_PSFLG_EXCLUSIVE) tu->timeri->flags |= SNDRV_TIMER_IFLG_EXCLUSIVE; if (params.flags & SNDRV_TIMER_PSFLG_EARLY_EVENT) tu->timeri->flags |= SNDRV_TIMER_IFLG_EARLY_EVENT; spin_unlock_irq(&t->lock); if (params.queue_size > 0 && (unsigned int)tu->queue_size != params.queue_size) { if (tu->tread) { ttr = kmalloc(params.queue_size * sizeof(*ttr), GFP_KERNEL); if (ttr) { kfree(tu->tqueue); tu->queue_size = params.queue_size; tu->tqueue = ttr; } } else { tr = kmalloc(params.queue_size * sizeof(*tr), GFP_KERNEL); if (tr) { kfree(tu->queue); tu->queue_size = params.queue_size; tu->queue = tr; } } } tu->qhead = tu->qtail = tu->qused = 0; if (tu->timeri->flags & SNDRV_TIMER_IFLG_EARLY_EVENT) { if (tu->tread) { struct snd_timer_tread tread; memset(&tread, 0, sizeof(tread)); tread.event = SNDRV_TIMER_EVENT_EARLY; tread.tstamp.tv_sec = 0; tread.tstamp.tv_nsec = 0; tread.val = 0; snd_timer_user_append_to_tqueue(tu, &tread); } else { struct snd_timer_read *r = &tu->queue[0]; r->resolution = 0; r->ticks = 0; tu->qused++; tu->qtail++; } } tu->filter = params.filter; tu->ticks = params.ticks; err = 0; _end: if (copy_to_user(_params, &params, sizeof(params))) return -EFAULT; return err; }
167,237
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 DoCanonicalizePathComponent(const CHAR* source, const Component& component, char separator, CanonOutput* output, Component* new_component) { bool success = true; if (component.is_valid()) { if (separator) output->push_back(separator); new_component->begin = output->length(); int end = component.end(); for (int i = component.begin; i < end; i++) { UCHAR uch = static_cast<UCHAR>(source[i]); if (uch < 0x20 || uch >= 0x80) success &= AppendUTF8EscapedChar(source, &i, end, output); else output->push_back(static_cast<char>(uch)); } new_component->len = output->length() - new_component->begin; } else { new_component->reset(); } return success; } Commit Message: [url] Make path URL parsing more lax Parsing the path component of a non-special URL like javascript or data should not fail for invalid URL characters like \uFFFF. See this bit in the spec: https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state Note: some failing WPTs are added which are because url parsing replaces invalid characters (e.g. \uFFFF) with the replacement char \uFFFD, when that isn't in the spec. Bug: 925614 Change-Id: I450495bfdfa68dc70334ebed16a3ecc0d5737e88 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1551917 Reviewed-by: Mike West <[email protected]> Commit-Queue: Charlie Harrison <[email protected]> Cr-Commit-Position: refs/heads/master@{#648155} CWE ID: CWE-20
bool DoCanonicalizePathComponent(const CHAR* source, template <typename CHAR, typename UCHAR> void DoCanonicalizePathComponent(const CHAR* source, const Component& component, char separator, CanonOutput* output, Component* new_component) { if (component.is_valid()) { if (separator) output->push_back(separator); new_component->begin = output->length(); int end = component.end(); for (int i = component.begin; i < end; i++) { UCHAR uch = static_cast<UCHAR>(source[i]); if (uch < 0x20 || uch >= 0x80) AppendUTF8EscapedChar(source, &i, end, output); else output->push_back(static_cast<char>(uch)); } new_component->len = output->length() - new_component->begin; } else { new_component->reset(); } }
173,011
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Chapters::Edition::Edition() { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
Chapters::Edition::Edition() const int size = (m_atoms_size == 0) ? 1 : 2 * m_atoms_size; Atom* const atoms = new (std::nothrow) Atom[size]; if (atoms == NULL) return false; for (int idx = 0; idx < m_atoms_count; ++idx) { m_atoms[idx].ShallowCopy(atoms[idx]); } delete[] m_atoms; m_atoms = atoms; m_atoms_size = size; return true; }
174,273
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 au1200fb_fb_mmap(struct fb_info *info, struct vm_area_struct *vma) { unsigned int len; unsigned long start=0, off; struct au1200fb_device *fbdev = info->par; if (vma->vm_pgoff > (~0UL >> PAGE_SHIFT)) { return -EINVAL; } start = fbdev->fb_phys & PAGE_MASK; len = PAGE_ALIGN((start & ~PAGE_MASK) + fbdev->fb_len); off = vma->vm_pgoff << PAGE_SHIFT; if ((vma->vm_end - vma->vm_start + off) > len) { return -EINVAL; } off += start; vma->vm_pgoff = off >> PAGE_SHIFT; vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); pgprot_val(vma->vm_page_prot) |= _CACHE_MASK; /* CCA=7 */ return io_remap_pfn_range(vma, vma->vm_start, off >> PAGE_SHIFT, vma->vm_end - vma->vm_start, vma->vm_page_prot); } Commit Message: Fix a few incorrectly checked [io_]remap_pfn_range() calls Nico Golde reports a few straggling uses of [io_]remap_pfn_range() that really should use the vm_iomap_memory() helper. This trivially converts two of them to the helper, and comments about why the third one really needs to continue to use remap_pfn_range(), and adds the missing size check. Reported-by: Nico Golde <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]. CWE ID: CWE-119
static int au1200fb_fb_mmap(struct fb_info *info, struct vm_area_struct *vma) { struct au1200fb_device *fbdev = info->par; vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); pgprot_val(vma->vm_page_prot) |= _CACHE_MASK; /* CCA=7 */ return vm_iomap_memory(vma, fbdev->fb_phys, fbdev->fb_len); }
165,936
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: transform_test(png_modifier *pmIn, PNG_CONST png_uint_32 idIn, PNG_CONST image_transform* transform_listIn, PNG_CONST char * volatile name) { transform_display d; context(&pmIn->this, fault); transform_display_init(&d, pmIn, idIn, transform_listIn); Try { size_t pos = 0; png_structp pp; png_infop pi; char full_name[256]; /* Make sure the encoding fields are correct and enter the required * modifications. */ transform_set_encoding(&d); /* Add any modifications required by the transform list. */ d.transform_list->ini(d.transform_list, &d); /* Add the color space information, if any, to the name. */ pos = safecat(full_name, sizeof full_name, pos, name); pos = safecat_current_encoding(full_name, sizeof full_name, pos, d.pm); /* Get a png_struct for reading the image. */ pp = set_modifier_for_read(d.pm, &pi, d.this.id, full_name); standard_palette_init(&d.this); # if 0 /* Logging (debugging only) */ { char buffer[256]; (void)store_message(&d.pm->this, pp, buffer, sizeof buffer, 0, "running test"); fprintf(stderr, "%s\n", buffer); } # endif /* Introduce the correct read function. */ if (d.pm->this.progressive) { /* Share the row function with the standard implementation. */ png_set_progressive_read_fn(pp, &d, transform_info, progressive_row, transform_end); /* Now feed data into the reader until we reach the end: */ modifier_progressive_read(d.pm, pp, pi); } else { /* modifier_read expects a png_modifier* */ png_set_read_fn(pp, d.pm, modifier_read); /* Check the header values: */ png_read_info(pp, pi); /* Process the 'info' requirements. Only one image is generated */ transform_info_imp(&d, pp, pi); sequential_row(&d.this, pp, pi, -1, 0); if (!d.this.speed) transform_image_validate(&d, pp, pi); else d.this.ps->validated = 1; } modifier_reset(d.pm); } Catch(fault) { modifier_reset(voidcast(png_modifier*,(void*)fault)); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
transform_test(png_modifier *pmIn, PNG_CONST png_uint_32 idIn, transform_test(png_modifier *pmIn, const png_uint_32 idIn, const image_transform* transform_listIn, const char * const name) { transform_display d; context(&pmIn->this, fault); transform_display_init(&d, pmIn, idIn, transform_listIn); Try { size_t pos = 0; png_structp pp; png_infop pi; char full_name[256]; /* Make sure the encoding fields are correct and enter the required * modifications. */ transform_set_encoding(&d); /* Add any modifications required by the transform list. */ d.transform_list->ini(d.transform_list, &d); /* Add the color space information, if any, to the name. */ pos = safecat(full_name, sizeof full_name, pos, name); pos = safecat_current_encoding(full_name, sizeof full_name, pos, d.pm); /* Get a png_struct for reading the image. */ pp = set_modifier_for_read(d.pm, &pi, d.this.id, full_name); standard_palette_init(&d.this); # if 0 /* Logging (debugging only) */ { char buffer[256]; (void)store_message(&d.pm->this, pp, buffer, sizeof buffer, 0, "running test"); fprintf(stderr, "%s\n", buffer); } # endif /* Introduce the correct read function. */ if (d.pm->this.progressive) { /* Share the row function with the standard implementation. */ png_set_progressive_read_fn(pp, &d, transform_info, progressive_row, transform_end); /* Now feed data into the reader until we reach the end: */ modifier_progressive_read(d.pm, pp, pi); } else { /* modifier_read expects a png_modifier* */ png_set_read_fn(pp, d.pm, modifier_read); /* Check the header values: */ png_read_info(pp, pi); /* Process the 'info' requirements. Only one image is generated */ transform_info_imp(&d, pp, pi); sequential_row(&d.this, pp, pi, -1, 0); if (!d.this.speed) transform_image_validate(&d, pp, pi); else d.this.ps->validated = 1; } modifier_reset(d.pm); } Catch(fault) { modifier_reset(voidcast(png_modifier*,(void*)fault)); } }
173,717
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 xenvif_disconnect(struct xenvif *vif) { struct net_device *dev = vif->dev; if (netif_carrier_ok(dev)) { rtnl_lock(); netif_carrier_off(dev); /* discard queued packets */ if (netif_running(dev)) xenvif_down(vif); rtnl_unlock(); xenvif_put(vif); } atomic_dec(&vif->refcnt); wait_event(vif->waiting_to_free, atomic_read(&vif->refcnt) == 0); del_timer_sync(&vif->credit_timeout); if (vif->irq) unbind_from_irqhandler(vif->irq, vif); unregister_netdev(vif->dev); xen_netbk_unmap_frontend_rings(vif); free_netdev(vif->dev); } Commit Message: xen/netback: shutdown the ring if it contains garbage. A buggy or malicious frontend should not be able to confuse netback. If we spot anything which is not as it should be then shutdown the device and don't try to continue with the ring in a potentially hostile state. Well behaved and non-hostile frontends will not be penalised. As well as making the existing checks for such errors fatal also add a new check that ensures that there isn't an insane number of requests on the ring (i.e. more than would fit in the ring). If the ring contains garbage then previously is was possible to loop over this insane number, getting an error each time and therefore not generating any more pending requests and therefore not exiting the loop in xen_netbk_tx_build_gops for an externded period. Also turn various netdev_dbg calls which no precipitate a fatal error into netdev_err, they are rate limited because the device is shutdown afterwards. This fixes at least one known DoS/softlockup of the backend domain. Signed-off-by: Ian Campbell <[email protected]> Reviewed-by: Konrad Rzeszutek Wilk <[email protected]> Acked-by: Jan Beulich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
void xenvif_disconnect(struct xenvif *vif) void xenvif_carrier_off(struct xenvif *vif) { struct net_device *dev = vif->dev; rtnl_lock(); netif_carrier_off(dev); /* discard queued packets */ if (netif_running(dev)) xenvif_down(vif); rtnl_unlock(); xenvif_put(vif); } void xenvif_disconnect(struct xenvif *vif) { if (netif_carrier_ok(vif->dev)) xenvif_carrier_off(vif); atomic_dec(&vif->refcnt); wait_event(vif->waiting_to_free, atomic_read(&vif->refcnt) == 0); del_timer_sync(&vif->credit_timeout); if (vif->irq) unbind_from_irqhandler(vif->irq, vif); unregister_netdev(vif->dev); xen_netbk_unmap_frontend_rings(vif); free_netdev(vif->dev); }
166,171
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadSCREENSHOTImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=(Image *) NULL; #if defined(MAGICKCORE_WINGDI32_DELEGATE) { BITMAPINFO bmi; DISPLAY_DEVICE device; HBITMAP bitmap, bitmapOld; HDC bitmapDC, hDC; Image *screen; int i; register PixelPacket *q; register ssize_t x; RGBTRIPLE *p; ssize_t y; assert(image_info != (const ImageInfo *) NULL); i=0; device.cb = sizeof(device); image=(Image *) NULL; while(EnumDisplayDevices(NULL,i,&device,0) && ++i) { if ((device.StateFlags & DISPLAY_DEVICE_ACTIVE) != DISPLAY_DEVICE_ACTIVE) continue; hDC=CreateDC(device.DeviceName,device.DeviceName,NULL,NULL); if (hDC == (HDC) NULL) ThrowReaderException(CoderError,"UnableToCreateDC"); screen=AcquireImage(image_info); screen->columns=(size_t) GetDeviceCaps(hDC,HORZRES); screen->rows=(size_t) GetDeviceCaps(hDC,VERTRES); screen->storage_class=DirectClass; if (image == (Image *) NULL) image=screen; else AppendImageToList(&image,screen); bitmapDC=CreateCompatibleDC(hDC); if (bitmapDC == (HDC) NULL) { DeleteDC(hDC); ThrowReaderException(CoderError,"UnableToCreateDC"); } (void) ResetMagickMemory(&bmi,0,sizeof(BITMAPINFO)); bmi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth=(LONG) screen->columns; bmi.bmiHeader.biHeight=(-1)*(LONG) screen->rows; bmi.bmiHeader.biPlanes=1; bmi.bmiHeader.biBitCount=24; bmi.bmiHeader.biCompression=BI_RGB; bitmap=CreateDIBSection(hDC,&bmi,DIB_RGB_COLORS,(void **) &p,NULL,0); if (bitmap == (HBITMAP) NULL) { DeleteDC(hDC); DeleteDC(bitmapDC); ThrowReaderException(CoderError,"UnableToCreateBitmap"); } bitmapOld=(HBITMAP) SelectObject(bitmapDC,bitmap); if (bitmapOld == (HBITMAP) NULL) { DeleteDC(hDC); DeleteDC(bitmapDC); DeleteObject(bitmap); ThrowReaderException(CoderError,"UnableToCreateBitmap"); } BitBlt(bitmapDC,0,0,(int) screen->columns,(int) screen->rows,hDC,0,0, SRCCOPY); (void) SelectObject(bitmapDC,bitmapOld); for (y=0; y < (ssize_t) screen->rows; y++) { q=QueueAuthenticPixels(screen,0,y,screen->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) screen->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(p->rgbtRed)); SetPixelGreen(q,ScaleCharToQuantum(p->rgbtGreen)); SetPixelBlue(q,ScaleCharToQuantum(p->rgbtBlue)); SetPixelOpacity(q,OpaqueOpacity); p++; q++; } if (SyncAuthenticPixels(screen,exception) == MagickFalse) break; } DeleteDC(hDC); DeleteDC(bitmapDC); DeleteObject(bitmap); } } #elif defined(MAGICKCORE_X11_DELEGATE) { const char *option; XImportInfo ximage_info; (void) exception; XGetImportInfo(&ximage_info); option=GetImageOption(image_info,"x:screen"); if (option != (const char *) NULL) ximage_info.screen=IsMagickTrue(option); option=GetImageOption(image_info,"x:silent"); if (option != (const char *) NULL) ximage_info.silent=IsMagickTrue(option); image=XImportImage(image_info,&ximage_info); } #endif return(image); } Commit Message: CWE ID: CWE-119
static Image *ReadSCREENSHOTImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=(Image *) NULL; #if defined(MAGICKCORE_WINGDI32_DELEGATE) { BITMAPINFO bmi; DISPLAY_DEVICE device; HBITMAP bitmap, bitmapOld; HDC bitmapDC, hDC; Image *screen; int i; MagickBooleanType status; register PixelPacket *q; register ssize_t x; RGBTRIPLE *p; ssize_t y; assert(image_info != (const ImageInfo *) NULL); i=0; device.cb = sizeof(device); image=(Image *) NULL; while(EnumDisplayDevices(NULL,i,&device,0) && ++i) { if ((device.StateFlags & DISPLAY_DEVICE_ACTIVE) != DISPLAY_DEVICE_ACTIVE) continue; hDC=CreateDC(device.DeviceName,device.DeviceName,NULL,NULL); if (hDC == (HDC) NULL) ThrowReaderException(CoderError,"UnableToCreateDC"); screen=AcquireImage(image_info); screen->columns=(size_t) GetDeviceCaps(hDC,HORZRES); screen->rows=(size_t) GetDeviceCaps(hDC,VERTRES); screen->storage_class=DirectClass; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (image == (Image *) NULL) image=screen; else AppendImageToList(&image,screen); bitmapDC=CreateCompatibleDC(hDC); if (bitmapDC == (HDC) NULL) { DeleteDC(hDC); ThrowReaderException(CoderError,"UnableToCreateDC"); } (void) ResetMagickMemory(&bmi,0,sizeof(BITMAPINFO)); bmi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth=(LONG) screen->columns; bmi.bmiHeader.biHeight=(-1)*(LONG) screen->rows; bmi.bmiHeader.biPlanes=1; bmi.bmiHeader.biBitCount=24; bmi.bmiHeader.biCompression=BI_RGB; bitmap=CreateDIBSection(hDC,&bmi,DIB_RGB_COLORS,(void **) &p,NULL,0); if (bitmap == (HBITMAP) NULL) { DeleteDC(hDC); DeleteDC(bitmapDC); ThrowReaderException(CoderError,"UnableToCreateBitmap"); } bitmapOld=(HBITMAP) SelectObject(bitmapDC,bitmap); if (bitmapOld == (HBITMAP) NULL) { DeleteDC(hDC); DeleteDC(bitmapDC); DeleteObject(bitmap); ThrowReaderException(CoderError,"UnableToCreateBitmap"); } BitBlt(bitmapDC,0,0,(int) screen->columns,(int) screen->rows,hDC,0,0, SRCCOPY); (void) SelectObject(bitmapDC,bitmapOld); for (y=0; y < (ssize_t) screen->rows; y++) { q=QueueAuthenticPixels(screen,0,y,screen->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) screen->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(p->rgbtRed)); SetPixelGreen(q,ScaleCharToQuantum(p->rgbtGreen)); SetPixelBlue(q,ScaleCharToQuantum(p->rgbtBlue)); SetPixelOpacity(q,OpaqueOpacity); p++; q++; } if (SyncAuthenticPixels(screen,exception) == MagickFalse) break; } DeleteDC(hDC); DeleteDC(bitmapDC); DeleteObject(bitmap); } } #elif defined(MAGICKCORE_X11_DELEGATE) { const char *option; XImportInfo ximage_info; (void) exception; XGetImportInfo(&ximage_info); option=GetImageOption(image_info,"x:screen"); if (option != (const char *) NULL) ximage_info.screen=IsMagickTrue(option); option=GetImageOption(image_info,"x:silent"); if (option != (const char *) NULL) ximage_info.silent=IsMagickTrue(option); image=XImportImage(image_info,&ximage_info); } #endif return(image); }
168,602
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 _dbus_printf_string_upper_bound (const char *format, va_list args) { /* MSVCRT's vsnprintf semantics are a bit different */ char buf[1024]; int bufsize; int len; bufsize = sizeof (buf); len = _vsnprintf (buf, bufsize - 1, format, args); while (len == -1) /* try again */ { p = malloc (bufsize); if (p == NULL) return -1; if (p == NULL) return -1; len = _vsnprintf (p, bufsize - 1, format, args); free (p); } * Returns the UTF-16 form of a UTF-8 string. The result should be * freed with dbus_free() when no longer needed. * * @param str the UTF-8 string * @param error return location for error code */ wchar_t * _dbus_win_utf8_to_utf16 (const char *str, DBusError *error) { DBusString s; int n; wchar_t *retval; _dbus_string_init_const (&s, str); if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s))) { dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8"); return NULL; } n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0); if (n == 0) { _dbus_win_set_error_from_win_error (error, GetLastError ()); return NULL; } retval = dbus_new (wchar_t, n); if (!retval) { _DBUS_SET_OOM (error); return NULL; } if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n) { dbus_free (retval); dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency"); return NULL; } return retval; } /** * Returns the UTF-8 form of a UTF-16 string. The result should be * freed with dbus_free() when no longer needed. * * @param str the UTF-16 string * @param error return location for error code */ char * _dbus_win_utf16_to_utf8 (const wchar_t *str, DBusError *error) { int n; char *retval; n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL); if (n == 0) { _dbus_win_set_error_from_win_error (error, GetLastError ()); return NULL; } retval = dbus_malloc (n); if (!retval) { _DBUS_SET_OOM (error); return NULL; } if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n) { dbus_free (retval); dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency"); return NULL; } return retval; } /************************************************************************ ************************************************************************/ dbus_bool_t _dbus_win_account_to_sid (const wchar_t *waccount, void **ppsid, DBusError *error) { dbus_bool_t retval = FALSE; DWORD sid_length, wdomain_length; SID_NAME_USE use; wchar_t *wdomain; *ppsid = NULL; sid_length = 0; wdomain_length = 0; if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length, NULL, &wdomain_length, &use) && GetLastError () != ERROR_INSUFFICIENT_BUFFER) { _dbus_win_set_error_from_win_error (error, GetLastError ()); return FALSE; } *ppsid = dbus_malloc (sid_length); if (!*ppsid) { _DBUS_SET_OOM (error); return FALSE; } wdomain = dbus_new (wchar_t, wdomain_length); if (!wdomain) { _DBUS_SET_OOM (error); goto out1; } if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length, wdomain, &wdomain_length, &use)) { _dbus_win_set_error_from_win_error (error, GetLastError ()); goto out2; } if (!IsValidSid ((PSID) *ppsid)) { dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID"); goto out2; } retval = TRUE; out2: dbus_free (wdomain); out1: if (!retval) { dbus_free (*ppsid); *ppsid = NULL; } return retval; } /** @} end of sysdeps-win */ Commit Message: CWE ID: CWE-20
int _dbus_printf_string_upper_bound (const char *format, va_list args) { /* MSVCRT's vsnprintf semantics are a bit different */ char buf[1024]; int bufsize; int len; va_list args_copy; bufsize = sizeof (buf); DBUS_VA_COPY (args_copy, args); len = _vsnprintf (buf, bufsize - 1, format, args_copy); va_end (args_copy); while (len == -1) /* try again */ { p = malloc (bufsize); if (p == NULL) return -1; if (p == NULL) return -1; DBUS_VA_COPY (args_copy, args); len = _vsnprintf (p, bufsize - 1, format, args_copy); va_end (args_copy); free (p); } * Returns the UTF-16 form of a UTF-8 string. The result should be * freed with dbus_free() when no longer needed. * * @param str the UTF-8 string * @param error return location for error code */ wchar_t * _dbus_win_utf8_to_utf16 (const char *str, DBusError *error) { DBusString s; int n; wchar_t *retval; _dbus_string_init_const (&s, str); if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s))) { dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8"); return NULL; } n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0); if (n == 0) { _dbus_win_set_error_from_win_error (error, GetLastError ()); return NULL; } retval = dbus_new (wchar_t, n); if (!retval) { _DBUS_SET_OOM (error); return NULL; } if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n) { dbus_free (retval); dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency"); return NULL; } return retval; } /** * Returns the UTF-8 form of a UTF-16 string. The result should be * freed with dbus_free() when no longer needed. * * @param str the UTF-16 string * @param error return location for error code */ char * _dbus_win_utf16_to_utf8 (const wchar_t *str, DBusError *error) { int n; char *retval; n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL); if (n == 0) { _dbus_win_set_error_from_win_error (error, GetLastError ()); return NULL; } retval = dbus_malloc (n); if (!retval) { _DBUS_SET_OOM (error); return NULL; } if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n) { dbus_free (retval); dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency"); return NULL; } return retval; } /************************************************************************ ************************************************************************/ dbus_bool_t _dbus_win_account_to_sid (const wchar_t *waccount, void **ppsid, DBusError *error) { dbus_bool_t retval = FALSE; DWORD sid_length, wdomain_length; SID_NAME_USE use; wchar_t *wdomain; *ppsid = NULL; sid_length = 0; wdomain_length = 0; if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length, NULL, &wdomain_length, &use) && GetLastError () != ERROR_INSUFFICIENT_BUFFER) { _dbus_win_set_error_from_win_error (error, GetLastError ()); return FALSE; } *ppsid = dbus_malloc (sid_length); if (!*ppsid) { _DBUS_SET_OOM (error); return FALSE; } wdomain = dbus_new (wchar_t, wdomain_length); if (!wdomain) { _DBUS_SET_OOM (error); goto out1; } if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length, wdomain, &wdomain_length, &use)) { _dbus_win_set_error_from_win_error (error, GetLastError ()); goto out2; } if (!IsValidSid ((PSID) *ppsid)) { dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID"); goto out2; } retval = TRUE; out2: dbus_free (wdomain); out1: if (!retval) { dbus_free (*ppsid); *ppsid = NULL; } return retval; } /** @} end of sysdeps-win */
164,723
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: v8::MaybeLocal<v8::Value> V8Debugger::functionScopes(v8::Local<v8::Function> function) { if (!enabled()) { NOTREACHED(); return v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate)); } v8::Local<v8::Value> argv[] = { function }; v8::Local<v8::Value> scopesValue; if (!callDebuggerMethod("getFunctionScopes", 1, argv).ToLocal(&scopesValue) || !scopesValue->IsArray()) return v8::MaybeLocal<v8::Value>(); v8::Local<v8::Array> scopes = scopesValue.As<v8::Array>(); v8::Local<v8::Context> context = m_debuggerContext.Get(m_isolate); if (!markAsInternal(context, scopes, V8InternalValueType::kScopeList)) return v8::MaybeLocal<v8::Value>(); if (!markArrayEntriesAsInternal(context, scopes, V8InternalValueType::kScope)) return v8::MaybeLocal<v8::Value>(); if (!scopes->SetPrototype(context, v8::Null(m_isolate)).FromMaybe(false)) return v8::Undefined(m_isolate); return scopes; } Commit Message: [DevTools] Copy objects from debugger context to inspected context properly. BUG=637594 Review-Url: https://codereview.chromium.org/2253643002 Cr-Commit-Position: refs/heads/master@{#412436} CWE ID: CWE-79
v8::MaybeLocal<v8::Value> V8Debugger::functionScopes(v8::Local<v8::Function> function) v8::MaybeLocal<v8::Value> V8Debugger::functionScopes(v8::Local<v8::Context> context, v8::Local<v8::Function> function) { if (!enabled()) { NOTREACHED(); return v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate)); } v8::Local<v8::Value> argv[] = { function }; v8::Local<v8::Value> scopesValue; if (!callDebuggerMethod("getFunctionScopes", 1, argv).ToLocal(&scopesValue)) return v8::MaybeLocal<v8::Value>(); v8::Local<v8::Value> copied; if (!copyValueFromDebuggerContext(m_isolate, debuggerContext(), context, scopesValue).ToLocal(&copied) || !copied->IsArray()) return v8::MaybeLocal<v8::Value>(); if (!markAsInternal(context, v8::Local<v8::Array>::Cast(copied), V8InternalValueType::kScopeList)) return v8::MaybeLocal<v8::Value>(); if (!markArrayEntriesAsInternal(context, v8::Local<v8::Array>::Cast(copied), V8InternalValueType::kScope)) return v8::MaybeLocal<v8::Value>(); return copied; }
172,066
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 InspectorPageAgent::setDeviceOrientationOverride(ErrorString* error, double alpha, double beta, double gamma) { DeviceOrientationController* controller = DeviceOrientationController::from(mainFrame()->document()); if (!controller) { *error = "Internal error: unable to override device orientation"; return; } controller->didChangeDeviceOrientation(DeviceOrientationData::create(true, alpha, true, beta, true, gamma).get()); } Commit Message: DevTools: remove references to modules/device_orientation from core BUG=340221 Review URL: https://codereview.chromium.org/150913003 git-svn-id: svn://svn.chromium.org/blink/trunk@166493 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void InspectorPageAgent::setDeviceOrientationOverride(ErrorString* error, double alpha, double beta, double gamma)
171,403
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline bool elementCanUseSimpleDefaultStyle(Element* e) { return isHTMLHtmlElement(e) || e->hasTagName(headTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || isHTMLAnchorElement(e); } Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun. We've been bitten by the Simple Default Stylesheet being out of sync with the real html.css twice this week. The Simple Default Stylesheet was invented years ago for Mac: http://trac.webkit.org/changeset/36135 It nicely handles the case where you just want to create a single WebView and parse some simple HTML either without styling said HTML, or only to display a small string, etc. Note that this optimization/complexity *only* helps for the very first document, since the default stylesheets are all static (process-global) variables. Since any real page on the internet uses a tag not covered by the simple default stylesheet, not real load benefits from this optimization. Only uses of WebView which were just rendering small bits of text might have benefited from this. about:blank would also have used this sheet. This was a common application for some uses of WebView back in those days. These days, even with WebView on Android, there are likely much larger overheads than parsing the html.css stylesheet, so making it required seems like the right tradeoff of code-simplicity for this case. BUG=319556 Review URL: https://codereview.chromium.org/73723005 git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static inline bool elementCanUseSimpleDefaultStyle(Element* e)
171,578
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 v9fs_xattr_set_acl(const struct xattr_handler *handler, struct dentry *dentry, struct inode *inode, const char *name, const void *value, size_t size, int flags) { int retval; struct posix_acl *acl; struct v9fs_session_info *v9ses; v9ses = v9fs_dentry2v9ses(dentry); /* * set the attribute on the remote. Without even looking at the * xattr value. We leave it to the server to validate */ if ((v9ses->flags & V9FS_ACCESS_MASK) != V9FS_ACCESS_CLIENT) return v9fs_xattr_set(dentry, handler->name, value, size, flags); if (S_ISLNK(inode->i_mode)) return -EOPNOTSUPP; if (!inode_owner_or_capable(inode)) return -EPERM; if (value) { /* update the cached acl value */ acl = posix_acl_from_xattr(&init_user_ns, value, size); if (IS_ERR(acl)) return PTR_ERR(acl); else if (acl) { retval = posix_acl_valid(inode->i_sb->s_user_ns, acl); if (retval) goto err_out; } } else acl = NULL; switch (handler->flags) { case ACL_TYPE_ACCESS: if (acl) { umode_t mode = inode->i_mode; retval = posix_acl_equiv_mode(acl, &mode); if (retval < 0) goto err_out; else { struct iattr iattr; if (retval == 0) { /* * ACL can be represented * by the mode bits. So don't * update ACL. */ acl = NULL; value = NULL; size = 0; } /* Updte the mode bits */ iattr.ia_mode = ((mode & S_IALLUGO) | (inode->i_mode & ~S_IALLUGO)); iattr.ia_valid = ATTR_MODE; /* FIXME should we update ctime ? * What is the following setxattr update the * mode ? */ v9fs_vfs_setattr_dotl(dentry, &iattr); } } break; case ACL_TYPE_DEFAULT: if (!S_ISDIR(inode->i_mode)) { retval = acl ? -EINVAL : 0; goto err_out; } break; default: BUG(); } retval = v9fs_xattr_set(dentry, handler->name, value, size, flags); if (!retval) set_cached_acl(inode, handler->flags, acl); err_out: posix_acl_release(acl); return retval; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Andreas Gruenbacher <[email protected]> CWE ID: CWE-285
static int v9fs_xattr_set_acl(const struct xattr_handler *handler, struct dentry *dentry, struct inode *inode, const char *name, const void *value, size_t size, int flags) { int retval; struct posix_acl *acl; struct v9fs_session_info *v9ses; v9ses = v9fs_dentry2v9ses(dentry); /* * set the attribute on the remote. Without even looking at the * xattr value. We leave it to the server to validate */ if ((v9ses->flags & V9FS_ACCESS_MASK) != V9FS_ACCESS_CLIENT) return v9fs_xattr_set(dentry, handler->name, value, size, flags); if (S_ISLNK(inode->i_mode)) return -EOPNOTSUPP; if (!inode_owner_or_capable(inode)) return -EPERM; if (value) { /* update the cached acl value */ acl = posix_acl_from_xattr(&init_user_ns, value, size); if (IS_ERR(acl)) return PTR_ERR(acl); else if (acl) { retval = posix_acl_valid(inode->i_sb->s_user_ns, acl); if (retval) goto err_out; } } else acl = NULL; switch (handler->flags) { case ACL_TYPE_ACCESS: if (acl) { struct iattr iattr; retval = posix_acl_update_mode(inode, &iattr.ia_mode, &acl); if (retval) goto err_out; if (!acl) { /* * ACL can be represented * by the mode bits. So don't * update ACL. */ value = NULL; size = 0; } iattr.ia_valid = ATTR_MODE; /* FIXME should we update ctime ? * What is the following setxattr update the * mode ? */ v9fs_vfs_setattr_dotl(dentry, &iattr); } break; case ACL_TYPE_DEFAULT: if (!S_ISDIR(inode->i_mode)) { retval = acl ? -EINVAL : 0; goto err_out; } break; default: BUG(); } retval = v9fs_xattr_set(dentry, handler->name, value, size, flags); if (!retval) set_cached_acl(inode, handler->flags, acl); err_out: posix_acl_release(acl); return retval; }
166,966
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: SSLErrorInfo SSLErrorInfo::CreateError(ErrorType error_type, net::X509Certificate* cert, const GURL& request_url) { string16 title, details, short_description; std::vector<string16> extra_info; switch (error_type) { case CERT_COMMON_NAME_INVALID: { title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_COMMON_NAME_INVALID_TITLE); std::vector<std::string> dns_names; cert->GetDNSNames(&dns_names); DCHECK(!dns_names.empty()); size_t i = 0; for (; i < dns_names.size(); ++i) { if (dns_names[i] == cert->subject().common_name) break; } if (i == dns_names.size()) i = 0; details = l10n_util::GetStringFUTF16(IDS_CERT_ERROR_COMMON_NAME_INVALID_DETAILS, UTF8ToUTF16(request_url.host()), UTF8ToUTF16(dns_names[i]), UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_COMMON_NAME_INVALID_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back( l10n_util::GetStringFUTF16( IDS_CERT_ERROR_COMMON_NAME_INVALID_EXTRA_INFO_2, UTF8ToUTF16(cert->subject().common_name), UTF8ToUTF16(request_url.host()))); break; } case CERT_DATE_INVALID: extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); if (cert->HasExpired()) { title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXPIRED_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_EXPIRED_DETAILS, UTF8ToUTF16(request_url.host()), UTF8ToUTF16(request_url.host()), base::TimeFormatFriendlyDateAndTime(base::Time::Now())); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXPIRED_DESCRIPTION); extra_info.push_back(l10n_util::GetStringUTF16( IDS_CERT_ERROR_EXPIRED_DETAILS_EXTRA_INFO_2)); } else { title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_NOT_YET_VALID_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_NOT_YET_VALID_DETAILS, UTF8ToUTF16(request_url.host()), UTF8ToUTF16(request_url.host()), base::TimeFormatFriendlyDateAndTime(base::Time::Now())); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_NOT_YET_VALID_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16( IDS_CERT_ERROR_NOT_YET_VALID_DETAILS_EXTRA_INFO_2)); } break; case CERT_AUTHORITY_INVALID: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_AUTHORITY_INVALID_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_AUTHORITY_INVALID_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_AUTHORITY_INVALID_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back(l10n_util::GetStringFUTF16( IDS_CERT_ERROR_AUTHORITY_INVALID_EXTRA_INFO_2, UTF8ToUTF16(request_url.host()), UTF8ToUTF16(request_url.host()))); extra_info.push_back(l10n_util::GetStringUTF16( IDS_CERT_ERROR_AUTHORITY_INVALID_EXTRA_INFO_3)); break; case CERT_CONTAINS_ERRORS: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_CONTAINS_ERRORS_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_CONTAINS_ERRORS_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_CONTAINS_ERRORS_DESCRIPTION); extra_info.push_back( l10n_util::GetStringFUTF16(IDS_CERT_ERROR_EXTRA_INFO_1, UTF8ToUTF16(request_url.host()))); extra_info.push_back(l10n_util::GetStringUTF16( IDS_CERT_ERROR_CONTAINS_ERRORS_EXTRA_INFO_2)); break; case CERT_NO_REVOCATION_MECHANISM: title = l10n_util::GetStringUTF16( IDS_CERT_ERROR_NO_REVOCATION_MECHANISM_TITLE); details = l10n_util::GetStringUTF16( IDS_CERT_ERROR_NO_REVOCATION_MECHANISM_DETAILS); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_NO_REVOCATION_MECHANISM_DESCRIPTION); break; case CERT_UNABLE_TO_CHECK_REVOCATION: title = l10n_util::GetStringUTF16( IDS_CERT_ERROR_UNABLE_TO_CHECK_REVOCATION_TITLE); details = l10n_util::GetStringUTF16( IDS_CERT_ERROR_UNABLE_TO_CHECK_REVOCATION_DETAILS); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_UNABLE_TO_CHECK_REVOCATION_DESCRIPTION); break; case CERT_REVOKED: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_REVOKED_CERT_TITLE); details = l10n_util::GetStringFUTF16(IDS_CERT_ERROR_REVOKED_CERT_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_REVOKED_CERT_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_REVOKED_CERT_EXTRA_INFO_2)); break; case CERT_INVALID: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_INVALID_CERT_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_INVALID_CERT_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_INVALID_CERT_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back(l10n_util::GetStringUTF16( IDS_CERT_ERROR_INVALID_CERT_EXTRA_INFO_2)); break; case CERT_WEAK_SIGNATURE_ALGORITHM: title = l10n_util::GetStringUTF16( IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back( l10n_util::GetStringUTF16( IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_EXTRA_INFO_2)); break; case CERT_WEAK_KEY: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_WEAK_KEY_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_WEAK_KEY_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_WEAK_KEY_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back( l10n_util::GetStringUTF16( IDS_CERT_ERROR_WEAK_KEY_EXTRA_INFO_2)); break; case UNKNOWN: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_UNKNOWN_ERROR_TITLE); details = l10n_util::GetStringUTF16(IDS_CERT_ERROR_UNKNOWN_ERROR_DETAILS); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_UNKNOWN_ERROR_DESCRIPTION); break; default: NOTREACHED(); } return SSLErrorInfo(title, details, short_description, extra_info); } Commit Message: Properly EscapeForHTML potentially malicious input from X.509 certificates. BUG=142956 TEST=Create an X.509 certificate with a CN field that contains JavaScript. When you get the SSL error screen, check that the HTML + JavaScript is escape instead of being treated as HTML and/or script. Review URL: https://chromiumcodereview.appspot.com/10827364 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152210 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-79
SSLErrorInfo SSLErrorInfo::CreateError(ErrorType error_type, net::X509Certificate* cert, const GURL& request_url) { string16 title, details, short_description; std::vector<string16> extra_info; switch (error_type) { case CERT_COMMON_NAME_INVALID: { title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_COMMON_NAME_INVALID_TITLE); std::vector<std::string> dns_names; cert->GetDNSNames(&dns_names); DCHECK(!dns_names.empty()); size_t i = 0; for (; i < dns_names.size(); ++i) { if (dns_names[i] == cert->subject().common_name) break; } if (i == dns_names.size()) i = 0; details = l10n_util::GetStringFUTF16(IDS_CERT_ERROR_COMMON_NAME_INVALID_DETAILS, UTF8ToUTF16(request_url.host()), net::EscapeForHTML( UTF8ToUTF16(dns_names[i])), UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_COMMON_NAME_INVALID_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back( l10n_util::GetStringFUTF16( IDS_CERT_ERROR_COMMON_NAME_INVALID_EXTRA_INFO_2, net::EscapeForHTML(UTF8ToUTF16(cert->subject().common_name)), UTF8ToUTF16(request_url.host()))); break; } case CERT_DATE_INVALID: extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); if (cert->HasExpired()) { title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXPIRED_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_EXPIRED_DETAILS, UTF8ToUTF16(request_url.host()), UTF8ToUTF16(request_url.host()), base::TimeFormatFriendlyDateAndTime(base::Time::Now())); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXPIRED_DESCRIPTION); extra_info.push_back(l10n_util::GetStringUTF16( IDS_CERT_ERROR_EXPIRED_DETAILS_EXTRA_INFO_2)); } else { title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_NOT_YET_VALID_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_NOT_YET_VALID_DETAILS, UTF8ToUTF16(request_url.host()), UTF8ToUTF16(request_url.host()), base::TimeFormatFriendlyDateAndTime(base::Time::Now())); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_NOT_YET_VALID_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16( IDS_CERT_ERROR_NOT_YET_VALID_DETAILS_EXTRA_INFO_2)); } break; case CERT_AUTHORITY_INVALID: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_AUTHORITY_INVALID_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_AUTHORITY_INVALID_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_AUTHORITY_INVALID_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back(l10n_util::GetStringFUTF16( IDS_CERT_ERROR_AUTHORITY_INVALID_EXTRA_INFO_2, UTF8ToUTF16(request_url.host()), UTF8ToUTF16(request_url.host()))); extra_info.push_back(l10n_util::GetStringUTF16( IDS_CERT_ERROR_AUTHORITY_INVALID_EXTRA_INFO_3)); break; case CERT_CONTAINS_ERRORS: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_CONTAINS_ERRORS_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_CONTAINS_ERRORS_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_CONTAINS_ERRORS_DESCRIPTION); extra_info.push_back( l10n_util::GetStringFUTF16(IDS_CERT_ERROR_EXTRA_INFO_1, UTF8ToUTF16(request_url.host()))); extra_info.push_back(l10n_util::GetStringUTF16( IDS_CERT_ERROR_CONTAINS_ERRORS_EXTRA_INFO_2)); break; case CERT_NO_REVOCATION_MECHANISM: title = l10n_util::GetStringUTF16( IDS_CERT_ERROR_NO_REVOCATION_MECHANISM_TITLE); details = l10n_util::GetStringUTF16( IDS_CERT_ERROR_NO_REVOCATION_MECHANISM_DETAILS); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_NO_REVOCATION_MECHANISM_DESCRIPTION); break; case CERT_UNABLE_TO_CHECK_REVOCATION: title = l10n_util::GetStringUTF16( IDS_CERT_ERROR_UNABLE_TO_CHECK_REVOCATION_TITLE); details = l10n_util::GetStringUTF16( IDS_CERT_ERROR_UNABLE_TO_CHECK_REVOCATION_DETAILS); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_UNABLE_TO_CHECK_REVOCATION_DESCRIPTION); break; case CERT_REVOKED: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_REVOKED_CERT_TITLE); details = l10n_util::GetStringFUTF16(IDS_CERT_ERROR_REVOKED_CERT_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_REVOKED_CERT_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_REVOKED_CERT_EXTRA_INFO_2)); break; case CERT_INVALID: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_INVALID_CERT_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_INVALID_CERT_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_INVALID_CERT_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back(l10n_util::GetStringUTF16( IDS_CERT_ERROR_INVALID_CERT_EXTRA_INFO_2)); break; case CERT_WEAK_SIGNATURE_ALGORITHM: title = l10n_util::GetStringUTF16( IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back( l10n_util::GetStringUTF16( IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_EXTRA_INFO_2)); break; case CERT_WEAK_KEY: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_WEAK_KEY_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_WEAK_KEY_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_WEAK_KEY_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back( l10n_util::GetStringUTF16( IDS_CERT_ERROR_WEAK_KEY_EXTRA_INFO_2)); break; case UNKNOWN: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_UNKNOWN_ERROR_TITLE); details = l10n_util::GetStringUTF16(IDS_CERT_ERROR_UNKNOWN_ERROR_DETAILS); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_UNKNOWN_ERROR_DESCRIPTION); break; default: NOTREACHED(); } return SSLErrorInfo(title, details, short_description, extra_info); }
170,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: static void perform_gamma_sbit_tests(png_modifier *pm) { png_byte sbit; /* The only interesting cases are colour and grayscale, alpha is ignored here * for overall speed. Only bit depths where sbit is less than the bit depth * are tested. */ for (sbit=pm->sbitlow; sbit<(1<<READ_BDHI); ++sbit) { png_byte colour_type = 0, bit_depth = 0; unsigned int npalette = 0; while (next_format(&colour_type, &bit_depth, &npalette, 1/*gamma*/)) if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 && ((colour_type == 3 && sbit < 8) || (colour_type != 3 && sbit < bit_depth))) { unsigned int i; for (i=0; i<pm->ngamma_tests; ++i) { unsigned int j; for (j=0; j<pm->ngamma_tests; ++j) if (i != j) { gamma_transform_test(pm, colour_type, bit_depth, npalette, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], sbit, pm->use_input_precision_sbit, 0 /*scale16*/); if (fail(pm)) return; } } } } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static void perform_gamma_sbit_tests(png_modifier *pm) { png_byte sbit; /* The only interesting cases are colour and grayscale, alpha is ignored here * for overall speed. Only bit depths where sbit is less than the bit depth * are tested. */ for (sbit=pm->sbitlow; sbit<(1<<READ_BDHI); ++sbit) { png_byte colour_type = 0, bit_depth = 0; unsigned int npalette = 0; while (next_format(&colour_type, &bit_depth, &npalette, pm->test_lbg_gamma_sbit, pm->test_tRNS)) if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 && ((colour_type == 3 && sbit < 8) || (colour_type != 3 && sbit < bit_depth))) { unsigned int i; for (i=0; i<pm->ngamma_tests; ++i) { unsigned int j; for (j=0; j<pm->ngamma_tests; ++j) if (i != j) { gamma_transform_test(pm, colour_type, bit_depth, npalette, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], sbit, pm->use_input_precision_sbit, 0 /*scale16*/); if (fail(pm)) return; } } } } }
173,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: static void usb_xhci_exit(PCIDevice *dev) { int i; XHCIState *xhci = XHCI(dev); trace_usb_xhci_exit(); for (i = 0; i < xhci->numslots; i++) { xhci_disable_slot(xhci, i + 1); } if (xhci->mfwrap_timer) { timer_del(xhci->mfwrap_timer); timer_free(xhci->mfwrap_timer); xhci->mfwrap_timer = NULL; } memory_region_del_subregion(&xhci->mem, &xhci->mem_cap); memory_region_del_subregion(&xhci->mem, &xhci->mem_oper); memory_region_del_subregion(&xhci->mem, &xhci->mem_runtime); memory_region_del_subregion(&xhci->mem, &xhci->mem_doorbell); for (i = 0; i < xhci->numports; i++) { XHCIPort *port = &xhci->ports[i]; memory_region_del_subregion(&xhci->mem, &port->mem); } /* destroy msix memory region */ if (dev->msix_table && dev->msix_pba && dev->msix_entry_used) { memory_region_del_subregion(&xhci->mem, &dev->msix_table_mmio); memory_region_del_subregion(&xhci->mem, &dev->msix_pba_mmio); } usb_bus_release(&xhci->bus); usb_bus_release(&xhci->bus); } Commit Message: CWE ID: CWE-399
static void usb_xhci_exit(PCIDevice *dev) { int i; XHCIState *xhci = XHCI(dev); trace_usb_xhci_exit(); for (i = 0; i < xhci->numslots; i++) { xhci_disable_slot(xhci, i + 1); } if (xhci->mfwrap_timer) { timer_del(xhci->mfwrap_timer); timer_free(xhci->mfwrap_timer); xhci->mfwrap_timer = NULL; } memory_region_del_subregion(&xhci->mem, &xhci->mem_cap); memory_region_del_subregion(&xhci->mem, &xhci->mem_oper); memory_region_del_subregion(&xhci->mem, &xhci->mem_runtime); memory_region_del_subregion(&xhci->mem, &xhci->mem_doorbell); for (i = 0; i < xhci->numports; i++) { XHCIPort *port = &xhci->ports[i]; memory_region_del_subregion(&xhci->mem, &port->mem); } /* destroy msix memory region */ if (dev->msix_table && dev->msix_pba && dev->msix_entry_used) { msix_uninit(dev, &xhci->mem, &xhci->mem); } usb_bus_release(&xhci->bus); usb_bus_release(&xhci->bus); }
164,926
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: png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) /* Note: this does not properly handle chunks that are > 64K under DOS */ { png_byte compression_type; png_bytep pC; png_charp profile; png_uint_32 skip = 0; png_uint_32 profile_size, profile_length; png_size_t slength, prefix_length, data_length; png_debug(1, "in png_handle_iCCP"); if (!(png_ptr->mode & PNG_HAVE_IHDR)) png_error(png_ptr, "Missing IHDR before iCCP"); else if (png_ptr->mode & PNG_HAVE_IDAT) { png_warning(png_ptr, "Invalid iCCP after IDAT"); png_crc_finish(png_ptr, length); return; } else if (png_ptr->mode & PNG_HAVE_PLTE) /* Should be an error, but we can cope with it */ png_warning(png_ptr, "Out of place iCCP chunk"); if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)) { png_warning(png_ptr, "Duplicate iCCP chunk"); png_crc_finish(png_ptr, length); return; } #ifdef PNG_MAX_MALLOC_64K if (length > (png_uint_32)65535L) { png_warning(png_ptr, "iCCP chunk too large to fit in memory"); skip = length - (png_uint_32)65535L; length = (png_uint_32)65535L; } #endif png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = (png_charp)png_malloc(png_ptr, length + 1); slength = (png_size_t)length; png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength); if (png_crc_finish(png_ptr, skip)) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; return; } png_ptr->chunkdata[slength] = 0x00; for (profile = png_ptr->chunkdata; *profile; profile++) /* Empty loop to find end of name */ ; ++profile; /* There should be at least one zero (the compression type byte) * following the separator, and we should be on it */ if ( profile >= png_ptr->chunkdata + slength - 1) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Malformed iCCP chunk"); return; } /* Compression_type should always be zero */ compression_type = *profile++; if (compression_type) { png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk"); compression_type = 0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8 wrote nonzero) */ } prefix_length = profile - png_ptr->chunkdata; png_decompress_chunk(png_ptr, compression_type, slength, prefix_length, &data_length); profile_length = data_length - prefix_length; if ( prefix_length > data_length || profile_length < 4) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Profile size field missing from iCCP chunk"); return; } /* Check the profile_size recorded in the first 32 bits of the ICC profile */ pC = (png_bytep)(png_ptr->chunkdata + prefix_length); profile_size = ((*(pC ))<<24) | ((*(pC + 1))<<16) | ((*(pC + 2))<< 8) | ((*(pC + 3)) ); if (profile_size < profile_length) profile_length = profile_size; if (profile_size > profile_length) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Ignoring truncated iCCP profile."); return; } png_set_iCCP(png_ptr, info_ptr, png_ptr->chunkdata, compression_type, png_ptr->chunkdata + prefix_length, profile_length); png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) /* Note: this does not properly handle chunks that are > 64K under DOS */ { png_byte compression_type; png_bytep pC; png_charp profile; png_uint_32 skip = 0; png_uint_32 profile_size, profile_length; png_size_t slength, prefix_length, data_length; png_debug(1, "in png_handle_iCCP"); if (!(png_ptr->mode & PNG_HAVE_IHDR)) png_error(png_ptr, "Missing IHDR before iCCP"); else if (png_ptr->mode & PNG_HAVE_IDAT) { png_warning(png_ptr, "Invalid iCCP after IDAT"); png_crc_finish(png_ptr, length); return; } else if (png_ptr->mode & PNG_HAVE_PLTE) /* Should be an error, but we can cope with it */ png_warning(png_ptr, "Out of place iCCP chunk"); if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)) { png_warning(png_ptr, "Duplicate iCCP chunk"); png_crc_finish(png_ptr, length); return; } #ifdef PNG_MAX_MALLOC_64K if (length > (png_uint_32)65535L) { png_warning(png_ptr, "iCCP chunk too large to fit in memory"); skip = length - (png_uint_32)65535L; length = (png_uint_32)65535L; } #endif png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = (png_charp)png_malloc(png_ptr, length + 1); slength = (png_size_t)length; png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength); if (png_crc_finish(png_ptr, skip)) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; return; } png_ptr->chunkdata[slength] = 0x00; for (profile = png_ptr->chunkdata; *profile; profile++) /* Empty loop to find end of name */ ; ++profile; /* There should be at least one zero (the compression type byte) * following the separator, and we should be on it */ if ( profile >= png_ptr->chunkdata + slength - 1) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Malformed iCCP chunk"); return; } /* Compression_type should always be zero */ compression_type = *profile++; if (compression_type) { png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk"); compression_type = 0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8 wrote nonzero) */ } prefix_length = profile - png_ptr->chunkdata; png_decompress_chunk(png_ptr, compression_type, slength, prefix_length, &data_length); profile_length = data_length - prefix_length; if ( prefix_length > data_length || profile_length < 4) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Profile size field missing from iCCP chunk"); return; } /* Check the profile_size recorded in the first 32 bits of the ICC profile */ pC = (png_bytep)(png_ptr->chunkdata + prefix_length); profile_size = ((png_uint_32) (*(pC )<<24)) | ((png_uint_32) (*(pC + 1)<<16)) | ((png_uint_32) (*(pC + 2)<< 8)) | ((png_uint_32) (*(pC + 3) )); if (profile_size < profile_length) profile_length = profile_size; if (profile_size > profile_length) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Ignoring truncated iCCP profile."); return; } png_set_iCCP(png_ptr, info_ptr, png_ptr->chunkdata, compression_type, png_ptr->chunkdata + prefix_length, profile_length); png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; }
172,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: static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu) { u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO); struct vcpu_vmx *vmx = to_vmx(vcpu); struct vmcs12 *vmcs12 = get_vmcs12(vcpu); u32 exit_reason = vmx->exit_reason; trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason, vmcs_readl(EXIT_QUALIFICATION), vmx->idt_vectoring_info, intr_info, vmcs_read32(VM_EXIT_INTR_ERROR_CODE), KVM_ISA_VMX); if (vmx->nested.nested_run_pending) return 0; if (unlikely(vmx->fail)) { pr_info_ratelimited("%s failed vm entry %x\n", __func__, vmcs_read32(VM_INSTRUCTION_ERROR)); return 1; } switch (exit_reason) { case EXIT_REASON_EXCEPTION_NMI: if (!is_exception(intr_info)) return 0; else if (is_page_fault(intr_info)) return enable_ept; else if (is_no_device(intr_info) && !(vmcs12->guest_cr0 & X86_CR0_TS)) return 0; return vmcs12->exception_bitmap & (1u << (intr_info & INTR_INFO_VECTOR_MASK)); case EXIT_REASON_EXTERNAL_INTERRUPT: return 0; case EXIT_REASON_TRIPLE_FAULT: return 1; case EXIT_REASON_PENDING_INTERRUPT: return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING); case EXIT_REASON_NMI_WINDOW: return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING); case EXIT_REASON_TASK_SWITCH: return 1; case EXIT_REASON_CPUID: if (kvm_register_read(vcpu, VCPU_REGS_RAX) == 0xa) return 0; return 1; case EXIT_REASON_HLT: return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING); case EXIT_REASON_INVD: return 1; case EXIT_REASON_INVLPG: return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING); case EXIT_REASON_RDPMC: return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING); case EXIT_REASON_RDTSC: return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING); case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR: case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD: case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD: case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE: case EXIT_REASON_VMOFF: case EXIT_REASON_VMON: case EXIT_REASON_INVEPT: /* * VMX instructions trap unconditionally. This allows L1 to * emulate them for its L2 guest, i.e., allows 3-level nesting! */ return 1; case EXIT_REASON_CR_ACCESS: return nested_vmx_exit_handled_cr(vcpu, vmcs12); case EXIT_REASON_DR_ACCESS: return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING); case EXIT_REASON_IO_INSTRUCTION: return nested_vmx_exit_handled_io(vcpu, vmcs12); case EXIT_REASON_MSR_READ: case EXIT_REASON_MSR_WRITE: return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason); case EXIT_REASON_INVALID_STATE: return 1; case EXIT_REASON_MWAIT_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING); case EXIT_REASON_MONITOR_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING); case EXIT_REASON_PAUSE_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) || nested_cpu_has2(vmcs12, SECONDARY_EXEC_PAUSE_LOOP_EXITING); case EXIT_REASON_MCE_DURING_VMENTRY: return 0; case EXIT_REASON_TPR_BELOW_THRESHOLD: return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW); case EXIT_REASON_APIC_ACCESS: return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES); case EXIT_REASON_EPT_VIOLATION: /* * L0 always deals with the EPT violation. If nested EPT is * used, and the nested mmu code discovers that the address is * missing in the guest EPT table (EPT12), the EPT violation * will be injected with nested_ept_inject_page_fault() */ return 0; case EXIT_REASON_EPT_MISCONFIG: /* * L2 never uses directly L1's EPT, but rather L0's own EPT * table (shadow on EPT) or a merged EPT table that L0 built * (EPT on EPT). So any problems with the structure of the * table is L0's fault. */ return 0; case EXIT_REASON_WBINVD: return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING); case EXIT_REASON_XSETBV: return 1; default: return 1; } } Commit Message: kvm: vmx: handle invvpid vm exit gracefully On systems with invvpid instruction support (corresponding bit in IA32_VMX_EPT_VPID_CAP MSR is set) guest invocation of invvpid causes vm exit, which is currently not handled and results in propagation of unknown exit to userspace. Fix this by installing an invvpid vm exit handler. This is CVE-2014-3646. Cc: [email protected] Signed-off-by: Petr Matousek <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264
static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu) { u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO); struct vcpu_vmx *vmx = to_vmx(vcpu); struct vmcs12 *vmcs12 = get_vmcs12(vcpu); u32 exit_reason = vmx->exit_reason; trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason, vmcs_readl(EXIT_QUALIFICATION), vmx->idt_vectoring_info, intr_info, vmcs_read32(VM_EXIT_INTR_ERROR_CODE), KVM_ISA_VMX); if (vmx->nested.nested_run_pending) return 0; if (unlikely(vmx->fail)) { pr_info_ratelimited("%s failed vm entry %x\n", __func__, vmcs_read32(VM_INSTRUCTION_ERROR)); return 1; } switch (exit_reason) { case EXIT_REASON_EXCEPTION_NMI: if (!is_exception(intr_info)) return 0; else if (is_page_fault(intr_info)) return enable_ept; else if (is_no_device(intr_info) && !(vmcs12->guest_cr0 & X86_CR0_TS)) return 0; return vmcs12->exception_bitmap & (1u << (intr_info & INTR_INFO_VECTOR_MASK)); case EXIT_REASON_EXTERNAL_INTERRUPT: return 0; case EXIT_REASON_TRIPLE_FAULT: return 1; case EXIT_REASON_PENDING_INTERRUPT: return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING); case EXIT_REASON_NMI_WINDOW: return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING); case EXIT_REASON_TASK_SWITCH: return 1; case EXIT_REASON_CPUID: if (kvm_register_read(vcpu, VCPU_REGS_RAX) == 0xa) return 0; return 1; case EXIT_REASON_HLT: return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING); case EXIT_REASON_INVD: return 1; case EXIT_REASON_INVLPG: return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING); case EXIT_REASON_RDPMC: return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING); case EXIT_REASON_RDTSC: return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING); case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR: case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD: case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD: case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE: case EXIT_REASON_VMOFF: case EXIT_REASON_VMON: case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID: /* * VMX instructions trap unconditionally. This allows L1 to * emulate them for its L2 guest, i.e., allows 3-level nesting! */ return 1; case EXIT_REASON_CR_ACCESS: return nested_vmx_exit_handled_cr(vcpu, vmcs12); case EXIT_REASON_DR_ACCESS: return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING); case EXIT_REASON_IO_INSTRUCTION: return nested_vmx_exit_handled_io(vcpu, vmcs12); case EXIT_REASON_MSR_READ: case EXIT_REASON_MSR_WRITE: return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason); case EXIT_REASON_INVALID_STATE: return 1; case EXIT_REASON_MWAIT_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING); case EXIT_REASON_MONITOR_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING); case EXIT_REASON_PAUSE_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) || nested_cpu_has2(vmcs12, SECONDARY_EXEC_PAUSE_LOOP_EXITING); case EXIT_REASON_MCE_DURING_VMENTRY: return 0; case EXIT_REASON_TPR_BELOW_THRESHOLD: return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW); case EXIT_REASON_APIC_ACCESS: return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES); case EXIT_REASON_EPT_VIOLATION: /* * L0 always deals with the EPT violation. If nested EPT is * used, and the nested mmu code discovers that the address is * missing in the guest EPT table (EPT12), the EPT violation * will be injected with nested_ept_inject_page_fault() */ return 0; case EXIT_REASON_EPT_MISCONFIG: /* * L2 never uses directly L1's EPT, but rather L0's own EPT * table (shadow on EPT) or a merged EPT table that L0 built * (EPT on EPT). So any problems with the structure of the * table is L0's fault. */ return 0; case EXIT_REASON_WBINVD: return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING); case EXIT_REASON_XSETBV: return 1; default: return 1; } }
166,344
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: parse_netscreen_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer* buf, char *line, int *err, gchar **err_info) { int sec; int dsec; char cap_int[NETSCREEN_MAX_INT_NAME_LENGTH]; char direction[2]; guint pkt_len; char cap_src[13]; char cap_dst[13]; guint8 *pd; gchar *p; int n, i = 0; guint offset = 0; gchar dststr[13]; phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; if (sscanf(line, "%9d.%9d: %15[a-z0-9/:.-](%1[io]) len=%9u:%12s->%12s/", &sec, &dsec, cap_int, direction, &pkt_len, cap_src, cap_dst) < 5) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: Can't parse packet-header"); return -1; } if (pkt_len > WTAP_MAX_PACKET_SIZE) { /* * Probably a corrupt capture file; don't blow up trying * to allocate space for an immensely-large packet. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("netscreen: File has %u-byte packet, bigger than maximum of %u", pkt_len, WTAP_MAX_PACKET_SIZE); return FALSE; } /* * If direction[0] is 'o', the direction is NETSCREEN_EGRESS, * otherwise it's NETSCREEN_INGRESS. */ phdr->ts.secs = sec; phdr->ts.nsecs = dsec * 100000000; phdr->len = pkt_len; /* Make sure we have enough room for the packet */ ws_buffer_assure_space(buf, pkt_len); pd = ws_buffer_start_ptr(buf); while(1) { /* The last packet is not delimited by an empty line, but by EOF * So accept EOF as a valid delimiter too */ if (file_gets(line, NETSCREEN_LINE_LENGTH, fh) == NULL) { break; } /* * Skip blanks. * The number of blanks is not fixed - for wireless * interfaces, there may be 14 extra spaces before * the hex data. */ for (p = &line[0]; g_ascii_isspace(*p); p++) ; /* packets are delimited with empty lines */ if (*p == '\0') { break; } n = parse_single_hex_dump_line(p, pd, offset); /* the smallest packet has a length of 6 bytes, if * the first hex-data is less then check whether * it is a info-line and act accordingly */ if (offset == 0 && n < 6) { if (info_line(line)) { if (++i <= NETSCREEN_MAX_INFOLINES) { continue; } } else { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: cannot parse hex-data"); return FALSE; } } /* If there is no more data and the line was not empty, * then there must be an error in the file */ if (n == -1) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: cannot parse hex-data"); return FALSE; } /* Adjust the offset to the data that was just added to the buffer */ offset += n; /* If there was more hex-data than was announced in the len=x * header, then then there must be an error in the file */ if (offset > pkt_len) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: too much hex-data"); return FALSE; } } /* * Determine the encapsulation type, based on the * first 4 characters of the interface name * * XXX convert this to a 'case' structure when adding more * (non-ethernet) interfacetypes */ if (strncmp(cap_int, "adsl", 4) == 0) { /* The ADSL interface can be bridged with or without * PPP encapsulation. Check whether the first six bytes * of the hex data are the same as the destination mac * address in the header. If they are, assume ethernet * LinkLayer or else PPP */ g_snprintf(dststr, 13, "%02x%02x%02x%02x%02x%02x", pd[0], pd[1], pd[2], pd[3], pd[4], pd[5]); if (strncmp(dststr, cap_dst, 12) == 0) phdr->pkt_encap = WTAP_ENCAP_ETHERNET; else phdr->pkt_encap = WTAP_ENCAP_PPP; } else if (strncmp(cap_int, "seri", 4) == 0) phdr->pkt_encap = WTAP_ENCAP_PPP; else phdr->pkt_encap = WTAP_ENCAP_ETHERNET; phdr->caplen = offset; return TRUE; } Commit Message: Don't treat the packet length as unsigned. The scanf family of functions are as annoyingly bad at handling unsigned numbers as strtoul() is - both of them are perfectly willing to accept a value beginning with a negative sign as an unsigned value. When using strtoul(), you can compensate for this by explicitly checking for a '-' as the first character of the string, but you can't do that with sscanf(). So revert to having pkt_len be signed, and scanning it with %d, but check for a negative value and fail if we see a negative value. Bug: 12396 Change-Id: I54fe8f61f42c32b5ef33da633ece51bbcda8c95f Reviewed-on: https://code.wireshark.org/review/15220 Reviewed-by: Guy Harris <[email protected]> CWE ID: CWE-20
parse_netscreen_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer* buf, char *line, int *err, gchar **err_info) { int pkt_len; int sec; int dsec; char cap_int[NETSCREEN_MAX_INT_NAME_LENGTH]; char direction[2]; char cap_src[13]; char cap_dst[13]; guint8 *pd; gchar *p; int n, i = 0; int offset = 0; gchar dststr[13]; phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; if (sscanf(line, "%9d.%9d: %15[a-z0-9/:.-](%1[io]) len=%9d:%12s->%12s/", &sec, &dsec, cap_int, direction, &pkt_len, cap_src, cap_dst) < 5) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: Can't parse packet-header"); return -1; } if (pkt_len < 0) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: packet header has a negative packet length"); return FALSE; } if (pkt_len > WTAP_MAX_PACKET_SIZE) { /* * Probably a corrupt capture file; don't blow up trying * to allocate space for an immensely-large packet. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("netscreen: File has %u-byte packet, bigger than maximum of %u", pkt_len, WTAP_MAX_PACKET_SIZE); return FALSE; } /* * If direction[0] is 'o', the direction is NETSCREEN_EGRESS, * otherwise it's NETSCREEN_INGRESS. */ phdr->ts.secs = sec; phdr->ts.nsecs = dsec * 100000000; phdr->len = pkt_len; /* Make sure we have enough room for the packet */ ws_buffer_assure_space(buf, pkt_len); pd = ws_buffer_start_ptr(buf); while(1) { /* The last packet is not delimited by an empty line, but by EOF * So accept EOF as a valid delimiter too */ if (file_gets(line, NETSCREEN_LINE_LENGTH, fh) == NULL) { break; } /* * Skip blanks. * The number of blanks is not fixed - for wireless * interfaces, there may be 14 extra spaces before * the hex data. */ for (p = &line[0]; g_ascii_isspace(*p); p++) ; /* packets are delimited with empty lines */ if (*p == '\0') { break; } n = parse_single_hex_dump_line(p, pd, offset); /* the smallest packet has a length of 6 bytes, if * the first hex-data is less then check whether * it is a info-line and act accordingly */ if (offset == 0 && n < 6) { if (info_line(line)) { if (++i <= NETSCREEN_MAX_INFOLINES) { continue; } } else { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: cannot parse hex-data"); return FALSE; } } /* If there is no more data and the line was not empty, * then there must be an error in the file */ if (n == -1) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: cannot parse hex-data"); return FALSE; } /* Adjust the offset to the data that was just added to the buffer */ offset += n; /* If there was more hex-data than was announced in the len=x * header, then then there must be an error in the file */ if (offset > pkt_len) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: too much hex-data"); return FALSE; } } /* * Determine the encapsulation type, based on the * first 4 characters of the interface name * * XXX convert this to a 'case' structure when adding more * (non-ethernet) interfacetypes */ if (strncmp(cap_int, "adsl", 4) == 0) { /* The ADSL interface can be bridged with or without * PPP encapsulation. Check whether the first six bytes * of the hex data are the same as the destination mac * address in the header. If they are, assume ethernet * LinkLayer or else PPP */ g_snprintf(dststr, 13, "%02x%02x%02x%02x%02x%02x", pd[0], pd[1], pd[2], pd[3], pd[4], pd[5]); if (strncmp(dststr, cap_dst, 12) == 0) phdr->pkt_encap = WTAP_ENCAP_ETHERNET; else phdr->pkt_encap = WTAP_ENCAP_PPP; } else if (strncmp(cap_int, "seri", 4) == 0) phdr->pkt_encap = WTAP_ENCAP_PPP; else phdr->pkt_encap = WTAP_ENCAP_ETHERNET; phdr->caplen = offset; return TRUE; }
169,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: static void read_conf(FILE *conffile) { char *buffer, *line, *val; buffer = loadfile(conffile); for (line = strtok(buffer, "\r\n"); line; line = strtok(NULL, "\r\n")) { if (!strncmp(line, "export ", 7)) continue; val = strchr(line, '='); if (!val) { printf("invalid configuration line\n"); break; } *val++ = '\0'; if (!strcmp(line, "JSON_INDENT")) conf.indent = atoi(val); if (!strcmp(line, "JSON_COMPACT")) conf.compact = atoi(val); if (!strcmp(line, "JSON_ENSURE_ASCII")) conf.ensure_ascii = atoi(val); if (!strcmp(line, "JSON_PRESERVE_ORDER")) conf.preserve_order = atoi(val); if (!strcmp(line, "JSON_SORT_KEYS")) conf.sort_keys = atoi(val); if (!strcmp(line, "STRIP")) conf.strip = atoi(val); } free(buffer); } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
static void read_conf(FILE *conffile) { char *buffer, *line, *val; buffer = loadfile(conffile); for (line = strtok(buffer, "\r\n"); line; line = strtok(NULL, "\r\n")) { if (!strncmp(line, "export ", 7)) continue; val = strchr(line, '='); if (!val) { printf("invalid configuration line\n"); break; } *val++ = '\0'; if (!strcmp(line, "JSON_INDENT")) conf.indent = atoi(val); if (!strcmp(line, "JSON_COMPACT")) conf.compact = atoi(val); if (!strcmp(line, "JSON_ENSURE_ASCII")) conf.ensure_ascii = atoi(val); if (!strcmp(line, "JSON_PRESERVE_ORDER")) conf.preserve_order = atoi(val); if (!strcmp(line, "JSON_SORT_KEYS")) conf.sort_keys = atoi(val); if (!strcmp(line, "STRIP")) conf.strip = atoi(val); if (!strcmp(line, "HASHSEED")) { conf.have_hashseed = 1; conf.hashseed = atoi(val); } else { conf.have_hashseed = 0; } } free(buffer); }
166,536
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: cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SHORT_SEC_SIZE(h); size_t pos = CDF_SHORT_SEC_POS(h, id); assert(ss == len); if (pos > CDF_SEC_SIZE(h) * sst->sst_len) { DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", pos, CDF_SEC_SIZE(h) * sst->sst_len)); return -1; } (void)memcpy(((char *)buf) + offs, ((const char *)sst->sst_tab) + pos, len); return len; } Commit Message: Apply patches from file-CVE-2012-1571.patch From Francisco Alonso Espejo: file < 5.18/git version can be made to crash when checking some corrupt CDF files (Using an invalid cdf_read_short_sector size) The problem I found here, is that in most situations (if h_short_sec_size_p2 > 8) because the blocksize is 512 and normal values are 06 which means reading 64 bytes.As long as the check for the block size copy is not checked properly (there's an assert that makes wrong/invalid assumptions) CWE ID: CWE-119
cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SHORT_SEC_SIZE(h); size_t pos = CDF_SHORT_SEC_POS(h, id); assert(ss == len); if (pos + len > CDF_SEC_SIZE(h) * sst->sst_len) { DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", pos + len, CDF_SEC_SIZE(h) * sst->sst_len)); return -1; } (void)memcpy(((char *)buf) + offs, ((const char *)sst->sst_tab) + pos, len); return len; }
166,444
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: cf2_initGlobalRegionBuffer( CFF_Decoder* decoder, CF2_UInt idx, CF2_Buffer buf ) { FT_ASSERT( decoder && decoder->globals ); FT_ZERO( buf ); idx += decoder->globals_bias; if ( idx >= decoder->num_globals ) return TRUE; /* error */ buf->start = buf->ptr = decoder->globals[idx]; buf->end = decoder->globals[idx + 1]; } Commit Message: CWE ID: CWE-20
cf2_initGlobalRegionBuffer( CFF_Decoder* decoder, CF2_UInt idx, CF2_Buffer buf ) { FT_ASSERT( decoder ); FT_ZERO( buf ); idx += decoder->globals_bias; if ( idx >= decoder->num_globals ) return TRUE; /* error */ FT_ASSERT( decoder->globals ); buf->start = buf->ptr = decoder->globals[idx]; buf->end = decoder->globals[idx + 1]; }
165,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: static void calcstepsizes(uint_fast16_t refstepsize, int numrlvls, uint_fast16_t *stepsizes) { int bandno; int numbands; uint_fast16_t expn; uint_fast16_t mant; expn = JPC_QCX_GETEXPN(refstepsize); mant = JPC_QCX_GETMANT(refstepsize); numbands = 3 * numrlvls - 2; for (bandno = 0; bandno < numbands; ++bandno) { ////jas_eprintf("DEBUG %d %d %d %d %d\n", bandno, expn, numrlvls, bandno, ((numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0))))); stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn + (numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))); } } Commit Message: Changed the JPC bitstream code to more gracefully handle a request for a larger sized integer than what can be handled (i.e., return with an error instead of failing an assert). CWE ID:
static void calcstepsizes(uint_fast16_t refstepsize, int numrlvls, uint_fast16_t *stepsizes) { int bandno; int numbands; uint_fast16_t expn; uint_fast16_t mant; expn = JPC_QCX_GETEXPN(refstepsize); mant = JPC_QCX_GETMANT(refstepsize); numbands = 3 * numrlvls - 2; for (bandno = 0; bandno < numbands; ++bandno) { ////jas_eprintf("DEBUG %d %d %d %d %d\n", bandno, expn, numrlvls, bandno, ((numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0))))); stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn + (numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))); } }
168,735
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 RilSapSocket::sendResponse(MsgHeader* hdr) { size_t encoded_size = 0; uint32_t written_size; size_t buffer_size = 0; pb_ostream_t ostream; bool success = false; pthread_mutex_lock(&write_lock); if ((success = pb_get_encoded_size(&encoded_size, MsgHeader_fields, hdr)) && encoded_size <= INT32_MAX && commandFd != -1) { buffer_size = encoded_size + sizeof(uint32_t); uint8_t buffer[buffer_size]; written_size = htonl((uint32_t) encoded_size); ostream = pb_ostream_from_buffer(buffer, buffer_size); pb_write(&ostream, (uint8_t *)&written_size, sizeof(written_size)); success = pb_encode(&ostream, MsgHeader_fields, hdr); if (success) { RLOGD("Size: %d (0x%x) Size as written: 0x%x", encoded_size, encoded_size, written_size); log_hex("onRequestComplete", &buffer[sizeof(written_size)], encoded_size); RLOGI("[%d] < SAP RESPONSE type: %d. id: %d. error: %d", hdr->token, hdr->type, hdr->id,hdr->error ); if ( 0 != blockingWrite_helper(commandFd, buffer, buffer_size)) { RLOGE("Error %d while writing to fd", errno); } else { RLOGD("Write successful"); } } else { RLOGE("Error while encoding response of type %d id %d buffer_size: %d: %s.", hdr->type, hdr->id, buffer_size, PB_GET_ERROR(&ostream)); } } else { RLOGE("Not sending response type %d: encoded_size: %u. commandFd: %d. encoded size result: %d", hdr->type, encoded_size, commandFd, success); } pthread_mutex_unlock(&write_lock); } Commit Message: Replace variable-length arrays on stack with malloc. Bug: 30202619 Change-Id: Ib95e08a1c009d88a4b4fd8d8fdba0641c6129008 (cherry picked from commit 943905bb9f99e3caa856b42c531e2be752da8834) CWE ID: CWE-264
void RilSapSocket::sendResponse(MsgHeader* hdr) { size_t encoded_size = 0; uint32_t written_size; size_t buffer_size = 0; pb_ostream_t ostream; bool success = false; pthread_mutex_lock(&write_lock); if ((success = pb_get_encoded_size(&encoded_size, MsgHeader_fields, hdr)) && encoded_size <= INT32_MAX && commandFd != -1) { buffer_size = encoded_size + sizeof(uint32_t); uint8_t* buffer = (uint8_t*)malloc(buffer_size); if (!buffer) { RLOGE("sendResponse: OOM"); pthread_mutex_unlock(&write_lock); return; } written_size = htonl((uint32_t) encoded_size); ostream = pb_ostream_from_buffer(buffer, buffer_size); pb_write(&ostream, (uint8_t *)&written_size, sizeof(written_size)); success = pb_encode(&ostream, MsgHeader_fields, hdr); if (success) { RLOGD("Size: %d (0x%x) Size as written: 0x%x", encoded_size, encoded_size, written_size); log_hex("onRequestComplete", &buffer[sizeof(written_size)], encoded_size); RLOGI("[%d] < SAP RESPONSE type: %d. id: %d. error: %d", hdr->token, hdr->type, hdr->id,hdr->error ); if ( 0 != blockingWrite_helper(commandFd, buffer, buffer_size)) { RLOGE("Error %d while writing to fd", errno); } else { RLOGD("Write successful"); } } else { RLOGE("Error while encoding response of type %d id %d buffer_size: %d: %s.", hdr->type, hdr->id, buffer_size, PB_GET_ERROR(&ostream)); } free(buffer); } else { RLOGE("Not sending response type %d: encoded_size: %u. commandFd: %d. encoded size result: %d", hdr->type, encoded_size, commandFd, success); } pthread_mutex_unlock(&write_lock); }
173,389
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 BaseRenderingContext2D::ClearResolvedFilters() { for (auto& state : state_stack_) state->ClearResolvedFilter(); } Commit Message: [PE] Distinguish between tainting due to canvas content and filter. A filter on a canvas can itself lead to origin tainting, for reasons other than that the canvas contents are tainted. This CL changes to distinguish these two causes, so that we recompute filters on content-tainting change. Bug: 778506 Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6 Reviewed-on: https://chromium-review.googlesource.com/811767 Reviewed-by: Fredrik Söderquist <[email protected]> Commit-Queue: Chris Harrelson <[email protected]> Cr-Commit-Position: refs/heads/master@{#522274} CWE ID: CWE-200
void BaseRenderingContext2D::ClearResolvedFilters() { void BaseRenderingContext2D::SetOriginTaintedByContent() { SetOriginTainted(); origin_tainted_by_content_ = true; for (auto& state : state_stack_) state->ClearResolvedFilter(); }
172,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: smbhash(unsigned char *out, const unsigned char *in, unsigned char *key) { int rc; unsigned char key2[8]; struct crypto_skcipher *tfm_des; struct scatterlist sgin, sgout; struct skcipher_request *req; str_to_key(key, key2); tfm_des = crypto_alloc_skcipher("ecb(des)", 0, CRYPTO_ALG_ASYNC); if (IS_ERR(tfm_des)) { rc = PTR_ERR(tfm_des); cifs_dbg(VFS, "could not allocate des crypto API\n"); goto smbhash_err; } req = skcipher_request_alloc(tfm_des, GFP_KERNEL); if (!req) { rc = -ENOMEM; cifs_dbg(VFS, "could not allocate des crypto API\n"); goto smbhash_free_skcipher; } crypto_skcipher_setkey(tfm_des, key2, 8); sg_init_one(&sgin, in, 8); sg_init_one(&sgout, out, 8); skcipher_request_set_callback(req, 0, NULL, NULL); skcipher_request_set_crypt(req, &sgin, &sgout, 8, NULL); rc = crypto_skcipher_encrypt(req); if (rc) cifs_dbg(VFS, "could not encrypt crypt key rc: %d\n", rc); skcipher_request_free(req); smbhash_free_skcipher: crypto_free_skcipher(tfm_des); smbhash_err: return rc; } Commit Message: cifs: Fix smbencrypt() to stop pointing a scatterlist at the stack smbencrypt() points a scatterlist to the stack, which is breaks if CONFIG_VMAP_STACK=y. Fix it by switching to crypto_cipher_encrypt_one(). The new code should be considerably faster as an added benefit. This code is nearly identical to some code that Eric Biggers suggested. Cc: [email protected] # 4.9 only Reported-by: Eric Biggers <[email protected]> Signed-off-by: Andy Lutomirski <[email protected]> Acked-by: Jeff Layton <[email protected]> Signed-off-by: Steve French <[email protected]> CWE ID: CWE-119
smbhash(unsigned char *out, const unsigned char *in, unsigned char *key) { unsigned char key2[8]; struct crypto_cipher *tfm_des; str_to_key(key, key2); tfm_des = crypto_alloc_cipher("des", 0, 0); if (IS_ERR(tfm_des)) { cifs_dbg(VFS, "could not allocate des crypto API\n"); return PTR_ERR(tfm_des); } crypto_cipher_setkey(tfm_des, key2, 8); crypto_cipher_encrypt_one(tfm_des, out, in); crypto_free_cipher(tfm_des); return 0; }
168,518
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 SpdyWriteQueue::RemovePendingWritesForStream( const base::WeakPtr<SpdyStream>& stream) { CHECK(!removing_writes_); removing_writes_ = true; RequestPriority priority = stream->priority(); CHECK_GE(priority, MINIMUM_PRIORITY); CHECK_LE(priority, MAXIMUM_PRIORITY); DCHECK(stream.get()); #if DCHECK_IS_ON for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) { if (priority == i) continue; for (std::deque<PendingWrite>::const_iterator it = queue_[i].begin(); it != queue_[i].end(); ++it) { DCHECK_NE(it->stream.get(), stream.get()); } } #endif std::deque<PendingWrite>* queue = &queue_[priority]; std::deque<PendingWrite>::iterator out_it = queue->begin(); for (std::deque<PendingWrite>::const_iterator it = queue->begin(); it != queue->end(); ++it) { if (it->stream.get() == stream.get()) { delete it->frame_producer; } else { *out_it = *it; ++out_it; } } queue->erase(out_it, queue->end()); removing_writes_ = false; } Commit Message: These can post callbacks which re-enter into SpdyWriteQueue. BUG=369539 Review URL: https://codereview.chromium.org/265933007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268730 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void SpdyWriteQueue::RemovePendingWritesForStream( const base::WeakPtr<SpdyStream>& stream) { CHECK(!removing_writes_); removing_writes_ = true; RequestPriority priority = stream->priority(); CHECK_GE(priority, MINIMUM_PRIORITY); CHECK_LE(priority, MAXIMUM_PRIORITY); DCHECK(stream.get()); #if DCHECK_IS_ON for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) { if (priority == i) continue; for (std::deque<PendingWrite>::const_iterator it = queue_[i].begin(); it != queue_[i].end(); ++it) { DCHECK_NE(it->stream.get(), stream.get()); } } #endif // Defer deletion until queue iteration is complete, as // SpdyBuffer::~SpdyBuffer() can result in callbacks into SpdyWriteQueue. std::vector<SpdyBufferProducer*> erased_buffer_producers; std::deque<PendingWrite>* queue = &queue_[priority]; std::deque<PendingWrite>::iterator out_it = queue->begin(); for (std::deque<PendingWrite>::const_iterator it = queue->begin(); it != queue->end(); ++it) { if (it->stream.get() == stream.get()) { erased_buffer_producers.push_back(it->frame_producer); } else { *out_it = *it; ++out_it; } } queue->erase(out_it, queue->end()); removing_writes_ = false; STLDeleteElements(&erased_buffer_producers); // Invokes callbacks. }
171,674
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 BaseAudioContext::Initialize() { if (IsDestinationInitialized()) return; FFTFrame::Initialize(); audio_worklet_ = AudioWorklet::Create(this); if (destination_node_) { destination_node_->Handler().Initialize(); listener_ = AudioListener::Create(*this); } } Commit Message: Audio thread should not access destination node The AudioDestinationNode is an object managed by Oilpan so the audio thread should not access it. However, the audio thread needs information (currentTime, etc) from the destination node. So instead of accessing the audio destination handler (a scoped_refptr) via the destination node, add a new member to the base audio context that holds onto the destination handler. The destination handler is not an oilpan object and lives at least as long as the base audio context. Bug: 860626, 860522, 863951 Test: Test case from 860522 doesn't crash on asan build Change-Id: I3add844d4eb8fdc7e05b89292938b843a0abbb99 Reviewed-on: https://chromium-review.googlesource.com/1138974 Commit-Queue: Raymond Toy <[email protected]> Reviewed-by: Hongchan Choi <[email protected]> Cr-Commit-Position: refs/heads/master@{#575509} CWE ID: CWE-416
void BaseAudioContext::Initialize() { if (IsDestinationInitialized()) return; FFTFrame::Initialize(); audio_worklet_ = AudioWorklet::Create(this); if (destination_node_) { destination_node_->Handler().Initialize(); // TODO(crbug.com/863951). The audio thread needs some things from the // destination handler like the currentTime. But the audio thread // shouldn't access the |destination_node_| since it's an Oilpan object. // Thus, get the destination handler, a non-oilpan object, so we can get // the items directly from the handler instead of through the destination // node. destination_handler_ = &destination_node_->GetAudioDestinationHandler(); listener_ = AudioListener::Create(*this); } }
173,175
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 iriap_getvaluebyclass_indication(struct iriap_cb *self, struct sk_buff *skb) { struct ias_object *obj; struct ias_attrib *attrib; int name_len; int attr_len; char name[IAS_MAX_CLASSNAME + 1]; /* 60 bytes */ char attr[IAS_MAX_ATTRIBNAME + 1]; /* 60 bytes */ __u8 *fp; int n; IRDA_DEBUG(4, "%s()\n", __func__); IRDA_ASSERT(self != NULL, return;); IRDA_ASSERT(self->magic == IAS_MAGIC, return;); IRDA_ASSERT(skb != NULL, return;); fp = skb->data; n = 1; name_len = fp[n++]; memcpy(name, fp+n, name_len); n+=name_len; name[name_len] = '\0'; attr_len = fp[n++]; memcpy(attr, fp+n, attr_len); n+=attr_len; attr[attr_len] = '\0'; IRDA_DEBUG(4, "LM-IAS: Looking up %s: %s\n", name, attr); obj = irias_find_object(name); if (obj == NULL) { IRDA_DEBUG(2, "LM-IAS: Object %s not found\n", name); iriap_getvaluebyclass_response(self, 0x1235, IAS_CLASS_UNKNOWN, &irias_missing); return; } IRDA_DEBUG(4, "LM-IAS: found %s, id=%d\n", obj->name, obj->id); attrib = irias_find_attrib(obj, attr); if (attrib == NULL) { IRDA_DEBUG(2, "LM-IAS: Attribute %s not found\n", attr); iriap_getvaluebyclass_response(self, obj->id, IAS_ATTRIB_UNKNOWN, &irias_missing); return; } /* We have a match; send the value. */ iriap_getvaluebyclass_response(self, obj->id, IAS_SUCCESS, attrib->value); } Commit Message: irda: validate peer name and attribute lengths Length fields provided by a peer for names and attributes may be longer than the destination array sizes. Validate lengths to prevent stack buffer overflows. Signed-off-by: Dan Rosenberg <[email protected]> Cc: [email protected] Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119
static void iriap_getvaluebyclass_indication(struct iriap_cb *self, struct sk_buff *skb) { struct ias_object *obj; struct ias_attrib *attrib; int name_len; int attr_len; char name[IAS_MAX_CLASSNAME + 1]; /* 60 bytes */ char attr[IAS_MAX_ATTRIBNAME + 1]; /* 60 bytes */ __u8 *fp; int n; IRDA_DEBUG(4, "%s()\n", __func__); IRDA_ASSERT(self != NULL, return;); IRDA_ASSERT(self->magic == IAS_MAGIC, return;); IRDA_ASSERT(skb != NULL, return;); fp = skb->data; n = 1; name_len = fp[n++]; IRDA_ASSERT(name_len < IAS_MAX_CLASSNAME + 1, return;); memcpy(name, fp+n, name_len); n+=name_len; name[name_len] = '\0'; attr_len = fp[n++]; IRDA_ASSERT(attr_len < IAS_MAX_ATTRIBNAME + 1, return;); memcpy(attr, fp+n, attr_len); n+=attr_len; attr[attr_len] = '\0'; IRDA_DEBUG(4, "LM-IAS: Looking up %s: %s\n", name, attr); obj = irias_find_object(name); if (obj == NULL) { IRDA_DEBUG(2, "LM-IAS: Object %s not found\n", name); iriap_getvaluebyclass_response(self, 0x1235, IAS_CLASS_UNKNOWN, &irias_missing); return; } IRDA_DEBUG(4, "LM-IAS: found %s, id=%d\n", obj->name, obj->id); attrib = irias_find_attrib(obj, attr); if (attrib == NULL) { IRDA_DEBUG(2, "LM-IAS: Attribute %s not found\n", attr); iriap_getvaluebyclass_response(self, obj->id, IAS_ATTRIB_UNKNOWN, &irias_missing); return; } /* We have a match; send the value. */ iriap_getvaluebyclass_response(self, obj->id, IAS_SUCCESS, attrib->value); }
166,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: static UINT drdynvc_process_capability_request(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s) { UINT status; if (!drdynvc) return CHANNEL_RC_BAD_INIT_HANDLE; WLog_Print(drdynvc->log, WLOG_TRACE, "capability_request Sp=%d cbChId=%d", Sp, cbChId); Stream_Seek(s, 1); /* pad */ Stream_Read_UINT16(s, drdynvc->version); /* RDP8 servers offer version 3, though Microsoft forgot to document it * in their early documents. It behaves the same as version 2. */ if ((drdynvc->version == 2) || (drdynvc->version == 3)) { Stream_Read_UINT16(s, drdynvc->PriorityCharge0); Stream_Read_UINT16(s, drdynvc->PriorityCharge1); Stream_Read_UINT16(s, drdynvc->PriorityCharge2); Stream_Read_UINT16(s, drdynvc->PriorityCharge3); } status = drdynvc_send_capability_response(drdynvc); drdynvc->state = DRDYNVC_STATE_READY; return status; } Commit Message: Fix for #4866: Added additional length checks CWE ID:
static UINT drdynvc_process_capability_request(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s) { UINT status; if (!drdynvc) return CHANNEL_RC_BAD_INIT_HANDLE; if (Stream_GetRemainingLength(s) < 3) return ERROR_INVALID_DATA; WLog_Print(drdynvc->log, WLOG_TRACE, "capability_request Sp=%d cbChId=%d", Sp, cbChId); Stream_Seek(s, 1); /* pad */ Stream_Read_UINT16(s, drdynvc->version); /* RDP8 servers offer version 3, though Microsoft forgot to document it * in their early documents. It behaves the same as version 2. */ if ((drdynvc->version == 2) || (drdynvc->version == 3)) { if (Stream_GetRemainingLength(s) < 8) return ERROR_INVALID_DATA; Stream_Read_UINT16(s, drdynvc->PriorityCharge0); Stream_Read_UINT16(s, drdynvc->PriorityCharge1); Stream_Read_UINT16(s, drdynvc->PriorityCharge2); Stream_Read_UINT16(s, drdynvc->PriorityCharge3); } status = drdynvc_send_capability_response(drdynvc); drdynvc->state = DRDYNVC_STATE_READY; return status; }
168,934
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: BlockEntry::Kind Track::EOSBlock::GetKind() const { return kBlockEOS; } 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
BlockEntry::Kind Track::EOSBlock::GetKind() const
174,331
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::OnCompositorSurfaceBuffersSwapped( int32 surface_id, uint64 surface_handle, int32 route_id, const gfx::Size& size, int32 gpu_process_host_id) { TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped"); if (!view_) { RenderWidgetHostImpl::AcknowledgeBufferPresent(route_id, gpu_process_host_id, false, 0); return; } GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params gpu_params; gpu_params.surface_id = surface_id; gpu_params.surface_handle = surface_handle; gpu_params.route_id = route_id; gpu_params.size = size; #if defined(OS_MACOSX) gpu_params.window = gfx::kNullPluginWindow; #endif view_->AcceleratedSurfaceBuffersSwapped(gpu_params, gpu_process_host_id); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped( int32 surface_id, uint64 surface_handle, int32 route_id, const gfx::Size& size, int32 gpu_process_host_id) { TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped"); if (!view_) { RenderWidgetHostImpl::AcknowledgeBufferPresent(route_id, gpu_process_host_id, surface_handle, 0); return; } GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params gpu_params; gpu_params.surface_id = surface_id; gpu_params.surface_handle = surface_handle; gpu_params.route_id = route_id; gpu_params.size = size; #if defined(OS_MACOSX) gpu_params.window = gfx::kNullPluginWindow; #endif view_->AcceleratedSurfaceBuffersSwapped(gpu_params, gpu_process_host_id); }
171,367
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 wait_for_fpga_config(void) { int ret = 0, done; /* approx 5 s */ u32 timeout = 500000; printf("PCIe FPGA config:"); do { done = qrio_get_gpio(GPIO_A, FPGA_DONE); if (timeout-- == 0) { printf(" FPGA_DONE timeout\n"); ret = -EFAULT; goto err_out; } udelay(10); } while (!done); printf(" done\n"); err_out: /* deactive CONF_SEL and give the CPU conf EEPROM access */ qrio_set_gpio(GPIO_A, CONF_SEL_L, 1); toggle_fpga_eeprom_bus(true); return ret; } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
static int wait_for_fpga_config(void) { int ret = 0, done; /* approx 5 s */ u32 timeout = 500000; printf("PCIe FPGA config:"); do { done = qrio_get_gpio(QRIO_GPIO_A, FPGA_DONE); if (timeout-- == 0) { printf(" FPGA_DONE timeout\n"); ret = -EFAULT; goto err_out; } udelay(10); } while (!done); printf(" done\n"); err_out: /* deactive CONF_SEL and give the CPU conf EEPROM access */ qrio_set_gpio(QRIO_GPIO_A, CONF_SEL_L, 1); toggle_fpga_eeprom_bus(true); return ret; }
169,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 uint32_t readU32(const uint8_t* data, size_t offset) { return data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]; } Commit Message: Avoid integer overflows in parsing fonts A malformed TTF can cause size calculations to overflow. This patch checks the maximum reasonable value so that the total size fits in 32 bits. It also adds some explicit casting to avoid possible technical undefined behavior when parsing sized unsigned values. Bug: 25645298 Change-Id: Id4716132041a6f4f1fbb73ec4e445391cf7d9616 (cherry picked from commit 183c9ec2800baa2ce099ee260c6cbc6121cf1274) CWE ID: CWE-19
static uint32_t readU32(const uint8_t* data, size_t offset) { return ((uint32_t)data[offset]) << 24 | ((uint32_t)data[offset + 1]) << 16 | ((uint32_t)data[offset + 2]) << 8 | ((uint32_t)data[offset + 3]); }
173,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: void Browser::SetWebContentsBlocked(content::WebContents* web_contents, bool blocked) { int index = tab_strip_model_->GetIndexOfWebContents(web_contents); if (index == TabStripModel::kNoTab) { return; } tab_strip_model_->SetTabBlocked(index, blocked); bool browser_active = BrowserList::GetInstance()->GetLastActive() == this; bool contents_is_active = tab_strip_model_->GetActiveWebContents() == web_contents; if (!blocked && contents_is_active && browser_active) web_contents->Focus(); } Commit Message: If a dialog is shown, drop fullscreen. BUG=875066, 817809, 792876, 812769, 813815 TEST=included Change-Id: Ic3d697fa3c4b01f5d7fea77391857177ada660db Reviewed-on: https://chromium-review.googlesource.com/1185208 Reviewed-by: Sidney San Martín <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#586418} CWE ID: CWE-20
void Browser::SetWebContentsBlocked(content::WebContents* web_contents, bool blocked) { int index = tab_strip_model_->GetIndexOfWebContents(web_contents); if (index == TabStripModel::kNoTab) { return; } // For security, if the WebContents is in fullscreen, have it drop fullscreen. // This gives the user the context they need in order to make informed // decisions. if (web_contents->IsFullscreenForCurrentTab()) web_contents->ExitFullscreen(true); tab_strip_model_->SetTabBlocked(index, blocked); bool browser_active = BrowserList::GetInstance()->GetLastActive() == this; bool contents_is_active = tab_strip_model_->GetActiveWebContents() == web_contents; if (!blocked && contents_is_active && browser_active) web_contents->Focus(); }
172,664
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 BlockEntry* Cluster::GetEntry( const Track* pTrack, long long time_ns) const { assert(pTrack); if (m_pSegment == NULL) //this is the special EOS cluster return pTrack->GetEOS(); #if 0 LoadBlockEntries(); if ((m_entries == NULL) || (m_entries_count <= 0)) return NULL; //return EOS here? const BlockEntry* pResult = pTrack->GetEOS(); BlockEntry** i = m_entries; assert(i); BlockEntry** const j = i + m_entries_count; while (i != j) { const BlockEntry* const pEntry = *i++; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != pTrack->GetNumber()) continue; if (pTrack->VetEntry(pEntry)) { if (time_ns < 0) //just want first candidate block return pEntry; const long long ns = pBlock->GetTime(this); if (ns > time_ns) break; pResult = pEntry; } else if (time_ns >= 0) { const long long ns = pBlock->GetTime(this); if (ns > time_ns) break; } } return pResult; #else const BlockEntry* pResult = pTrack->GetEOS(); long index = 0; for (;;) { if (index >= m_entries_count) { long long pos; long len; const long status = Parse(pos, len); assert(status >= 0); if (status > 0) //completely parsed, and no more entries return pResult; if (status < 0) //should never happen return 0; assert(m_entries); assert(index < m_entries_count); } const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != pTrack->GetNumber()) { ++index; continue; } if (pTrack->VetEntry(pEntry)) { if (time_ns < 0) //just want first candidate block return pEntry; const long long ns = pBlock->GetTime(this); if (ns > time_ns) return pResult; pResult = pEntry; //have a candidate } else if (time_ns >= 0) { const long long ns = pBlock->GetTime(this); if (ns > time_ns) return pResult; } ++index; } #endif } 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 BlockEntry* Cluster::GetEntry( if (m_pSegment == NULL) // this is the special EOS cluster return pTrack->GetEOS(); #if 0 LoadBlockEntries(); if ((m_entries == NULL) || (m_entries_count <= 0)) return NULL; //return EOS here? const BlockEntry* pResult = pTrack->GetEOS(); BlockEntry** i = m_entries; assert(i); BlockEntry** const j = i + m_entries_count; while (i != j) { const BlockEntry* const pEntry = *i++; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != pTrack->GetNumber()) continue; if (pTrack->VetEntry(pEntry)) { if (time_ns < 0) //just want first candidate block return pEntry; const long long ns = pBlock->GetTime(this); if (ns > time_ns) break; pResult = pEntry; } else if (time_ns >= 0) { const long long ns = pBlock->GetTime(this); if (ns > time_ns) break; } } return pResult; #else const BlockEntry* pResult = pTrack->GetEOS(); long index = 0; for (;;) { if (index >= m_entries_count) { long long pos; long len; const long status = Parse(pos, len); assert(status >= 0); if (status > 0) // completely parsed, and no more entries return pResult; if (status < 0) // should never happen return 0; assert(m_entries); assert(index < m_entries_count); } const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != pTrack->GetNumber()) { ++index; continue; } if (pTrack->VetEntry(pEntry)) { if (time_ns < 0) // just want first candidate block return pEntry; const long long ns = pBlock->GetTime(this); if (ns > time_ns) return pResult; pResult = pEntry; // have a candidate } else if (time_ns >= 0) { const long long ns = pBlock->GetTime(this); if (ns > time_ns) return pResult; } ++index; } #endif }
174,315
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: cib_remote_dispatch(gpointer user_data) { cib_t *cib = user_data; cib_remote_opaque_t *private = cib->variant_opaque; xmlNode *msg = NULL; const char *type = NULL; crm_info("Message on callback channel"); msg = crm_recv_remote_msg(private->callback.session, private->callback.encrypted); type = crm_element_value(msg, F_TYPE); crm_trace("Activating %s callbacks...", type); if (safe_str_eq(type, T_CIB)) { cib_native_callback(cib, msg, 0, 0); } else if (safe_str_eq(type, T_CIB_NOTIFY)) { g_list_foreach(cib->notify_list, cib_native_notify, msg); } else { crm_err("Unknown message type: %s", type); } if (msg != NULL) { free_xml(msg); return 0; } return -1; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
cib_remote_dispatch(gpointer user_data) cib_remote_command_dispatch(gpointer user_data) { int disconnected = 0; cib_t *cib = user_data; cib_remote_opaque_t *private = cib->variant_opaque; crm_recv_remote_msg(private->command.session, &private->command.recv_buf, private->command.encrypted, -1, &disconnected); free(private->command.recv_buf); private->command.recv_buf = NULL; crm_err("received late reply for remote cib connection, discarding"); if (disconnected) { return -1; } return 0; } int cib_remote_callback_dispatch(gpointer user_data) { cib_t *cib = user_data; cib_remote_opaque_t *private = cib->variant_opaque; xmlNode *msg = NULL; int disconnected = 0; crm_info("Message on callback channel"); crm_recv_remote_msg(private->callback.session, &private->callback.recv_buf, private->callback.encrypted, -1, &disconnected); msg = crm_parse_remote_buffer(&private->callback.recv_buf); while (msg) { const char *type = crm_element_value(msg, F_TYPE); crm_trace("Activating %s callbacks...", type); if (safe_str_eq(type, T_CIB)) { cib_native_callback(cib, msg, 0, 0); } else if (safe_str_eq(type, T_CIB_NOTIFY)) { g_list_foreach(cib->notify_list, cib_native_notify, msg); } else { crm_err("Unknown message type: %s", type); } free_xml(msg); msg = crm_parse_remote_buffer(&private->callback.recv_buf); } if (disconnected) { return -1; } return 0; }
166,151
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Chapters::ParseEdition( long long pos, long long size) { if (!ExpandEditionsArray()) return -1; Edition& e = m_editions[m_editions_count++]; e.Init(); return e.Parse(m_pSegment->m_pReader, pos, size); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Chapters::ParseEdition( Atom& a = m_atoms[m_atoms_count++]; a.Init(); return a.Parse(pReader, pos, size); }
174,423
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 UpdateProperty(IBusProperty* ibus_prop) { DLOG(INFO) << "UpdateProperty"; DCHECK(ibus_prop); ImePropertyList prop_list; // our representation. if (!FlattenProperty(ibus_prop, &prop_list)) { LOG(ERROR) << "Malformed properties are detected"; return; } if (!prop_list.empty()) { update_ime_property_(language_library_, prop_list); } } 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 UpdateProperty(IBusProperty* ibus_prop) { FOR_EACH_OBSERVER(Observer, observers_, OnRegisterImeProperties(prop_list)); }
170,550
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 dccp_v6_send_response(const struct sock *sk, struct request_sock *req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *np = inet6_sk(sk); struct sk_buff *skb; struct in6_addr *final_p, final; struct flowi6 fl6; int err = -1; struct dst_entry *dst; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = IPPROTO_DCCP; fl6.daddr = ireq->ir_v6_rmt_addr; fl6.saddr = ireq->ir_v6_loc_addr; fl6.flowlabel = 0; fl6.flowi6_oif = ireq->ir_iif; fl6.fl6_dport = ireq->ir_rmt_port; fl6.fl6_sport = htons(ireq->ir_num); security_req_classify_flow(req, flowi6_to_flowi(&fl6)); final_p = fl6_update_dst(&fl6, np->opt, &final); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { err = PTR_ERR(dst); dst = NULL; goto done; } skb = dccp_make_response(sk, dst, req); if (skb != NULL) { struct dccp_hdr *dh = dccp_hdr(skb); dh->dccph_checksum = dccp_v6_csum_finish(skb, &ireq->ir_v6_loc_addr, &ireq->ir_v6_rmt_addr); fl6.daddr = ireq->ir_v6_rmt_addr; err = ip6_xmit(sk, skb, &fl6, np->opt, np->tclass); err = net_xmit_eval(err); } done: dst_release(dst); 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 dccp_v6_send_response(const struct sock *sk, struct request_sock *req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *np = inet6_sk(sk); struct sk_buff *skb; struct in6_addr *final_p, final; struct flowi6 fl6; int err = -1; struct dst_entry *dst; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = IPPROTO_DCCP; fl6.daddr = ireq->ir_v6_rmt_addr; fl6.saddr = ireq->ir_v6_loc_addr; fl6.flowlabel = 0; fl6.flowi6_oif = ireq->ir_iif; fl6.fl6_dport = ireq->ir_rmt_port; fl6.fl6_sport = htons(ireq->ir_num); security_req_classify_flow(req, flowi6_to_flowi(&fl6)); rcu_read_lock(); final_p = fl6_update_dst(&fl6, rcu_dereference(np->opt), &final); rcu_read_unlock(); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { err = PTR_ERR(dst); dst = NULL; goto done; } skb = dccp_make_response(sk, dst, req); if (skb != NULL) { struct dccp_hdr *dh = dccp_hdr(skb); dh->dccph_checksum = dccp_v6_csum_finish(skb, &ireq->ir_v6_loc_addr, &ireq->ir_v6_rmt_addr); fl6.daddr = ireq->ir_v6_rmt_addr; rcu_read_lock(); err = ip6_xmit(sk, skb, &fl6, rcu_dereference(np->opt), np->tclass); rcu_read_unlock(); err = net_xmit_eval(err); } done: dst_release(dst); return err; }
167,326
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AddPolicyForRenderer(sandbox::TargetPolicy* policy) { sandbox::ResultCode result; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) return false; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Event"); if (result != sandbox::SBOX_ALL_OK) return false; policy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0); sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED; if (base::win::GetVersion() > base::win::VERSION_XP) { initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS; } policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN); policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAltWinstation); if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) { DLOG(WARNING) << "Failed to apply desktop security to the renderer"; } AddGenericDllEvictionPolicy(policy); return true; } Commit Message: Prevent sandboxed processes from opening each other TBR=brettw BUG=117627 BUG=119150 TEST=sbox_validation_tests Review URL: https://chromiumcodereview.appspot.com/9716027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132477 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool AddPolicyForRenderer(sandbox::TargetPolicy* policy) { sandbox::ResultCode result; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) return false; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Event"); if (result != sandbox::SBOX_ALL_OK) return false; policy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0); sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED; if (base::win::GetVersion() > base::win::VERSION_XP) { initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS; } policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN); // Prevents the renderers from manipulating low-integrity processes. policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED); bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAltWinstation); if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) { DLOG(WARNING) << "Failed to apply desktop security to the renderer"; } AddGenericDllEvictionPolicy(policy); return true; }
170,912
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<base::DictionaryValue> ParsePrintSettings( int command_id, const base::DictionaryValue* params, HeadlessPrintSettings* settings) { if (const base::Value* landscape_value = params->FindKey("landscape")) settings->landscape = landscape_value->GetBool(); if (const base::Value* display_header_footer_value = params->FindKey("displayHeaderFooter")) { settings->display_header_footer = display_header_footer_value->GetBool(); } if (const base::Value* should_print_backgrounds_value = params->FindKey("printBackground")) { settings->should_print_backgrounds = should_print_backgrounds_value->GetBool(); } if (const base::Value* scale_value = params->FindKey("scale")) settings->scale = scale_value->GetDouble(); if (settings->scale > kScaleMaxVal / 100 || settings->scale < kScaleMinVal / 100) return CreateInvalidParamResponse(command_id, "scale"); if (const base::Value* page_ranges_value = params->FindKey("pageRanges")) settings->page_ranges = page_ranges_value->GetString(); if (const base::Value* ignore_invalid_page_ranges_value = params->FindKey("ignoreInvalidPageRanges")) { settings->ignore_invalid_page_ranges = ignore_invalid_page_ranges_value->GetBool(); } double paper_width_in_inch = printing::kLetterWidthInch; if (const base::Value* paper_width_value = params->FindKey("paperWidth")) paper_width_in_inch = paper_width_value->GetDouble(); double paper_height_in_inch = printing::kLetterHeightInch; if (const base::Value* paper_height_value = params->FindKey("paperHeight")) paper_height_in_inch = paper_height_value->GetDouble(); if (paper_width_in_inch <= 0) return CreateInvalidParamResponse(command_id, "paperWidth"); if (paper_height_in_inch <= 0) return CreateInvalidParamResponse(command_id, "paperHeight"); settings->paper_size_in_points = gfx::Size(paper_width_in_inch * printing::kPointsPerInch, paper_height_in_inch * printing::kPointsPerInch); double default_margin_in_inch = 1000.0 / printing::kHundrethsMMPerInch; double margin_top_in_inch = default_margin_in_inch; double margin_bottom_in_inch = default_margin_in_inch; double margin_left_in_inch = default_margin_in_inch; double margin_right_in_inch = default_margin_in_inch; if (const base::Value* margin_top_value = params->FindKey("marginTop")) margin_top_in_inch = margin_top_value->GetDouble(); if (const base::Value* margin_bottom_value = params->FindKey("marginBottom")) margin_bottom_in_inch = margin_bottom_value->GetDouble(); if (const base::Value* margin_left_value = params->FindKey("marginLeft")) margin_left_in_inch = margin_left_value->GetDouble(); if (const base::Value* margin_right_value = params->FindKey("marginRight")) margin_right_in_inch = margin_right_value->GetDouble(); if (margin_top_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginTop"); if (margin_bottom_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginBottom"); if (margin_left_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginLeft"); if (margin_right_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginRight"); settings->margins_in_points.top = margin_top_in_inch * printing::kPointsPerInch; settings->margins_in_points.bottom = margin_bottom_in_inch * printing::kPointsPerInch; settings->margins_in_points.left = margin_left_in_inch * printing::kPointsPerInch; settings->margins_in_points.right = margin_right_in_inch * printing::kPointsPerInch; return nullptr; } Commit Message: DevTools: allow styling the page number element when printing over the protocol. Bug: none Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4 Reviewed-on: https://chromium-review.googlesource.com/809759 Commit-Queue: Pavel Feldman <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: Tom Sepez <[email protected]> Reviewed-by: Jianzhou Feng <[email protected]> Cr-Commit-Position: refs/heads/master@{#523966} CWE ID: CWE-20
std::unique_ptr<base::DictionaryValue> ParsePrintSettings( int command_id, const base::DictionaryValue* params, HeadlessPrintSettings* settings) { if (const base::Value* landscape_value = params->FindKey("landscape")) settings->landscape = landscape_value->GetBool(); if (const base::Value* display_header_footer_value = params->FindKey("displayHeaderFooter")) { settings->display_header_footer = display_header_footer_value->GetBool(); } if (const base::Value* should_print_backgrounds_value = params->FindKey("printBackground")) { settings->should_print_backgrounds = should_print_backgrounds_value->GetBool(); } if (const base::Value* scale_value = params->FindKey("scale")) settings->scale = scale_value->GetDouble(); if (settings->scale > kScaleMaxVal / 100 || settings->scale < kScaleMinVal / 100) return CreateInvalidParamResponse(command_id, "scale"); if (const base::Value* page_ranges_value = params->FindKey("pageRanges")) settings->page_ranges = page_ranges_value->GetString(); if (const base::Value* ignore_invalid_page_ranges_value = params->FindKey("ignoreInvalidPageRanges")) { settings->ignore_invalid_page_ranges = ignore_invalid_page_ranges_value->GetBool(); } double paper_width_in_inch = printing::kLetterWidthInch; if (const base::Value* paper_width_value = params->FindKey("paperWidth")) paper_width_in_inch = paper_width_value->GetDouble(); double paper_height_in_inch = printing::kLetterHeightInch; if (const base::Value* paper_height_value = params->FindKey("paperHeight")) paper_height_in_inch = paper_height_value->GetDouble(); if (paper_width_in_inch <= 0) return CreateInvalidParamResponse(command_id, "paperWidth"); if (paper_height_in_inch <= 0) return CreateInvalidParamResponse(command_id, "paperHeight"); settings->paper_size_in_points = gfx::Size(paper_width_in_inch * printing::kPointsPerInch, paper_height_in_inch * printing::kPointsPerInch); double default_margin_in_inch = 1000.0 / printing::kHundrethsMMPerInch; double margin_top_in_inch = default_margin_in_inch; double margin_bottom_in_inch = default_margin_in_inch; double margin_left_in_inch = default_margin_in_inch; double margin_right_in_inch = default_margin_in_inch; if (const base::Value* margin_top_value = params->FindKey("marginTop")) margin_top_in_inch = margin_top_value->GetDouble(); if (const base::Value* margin_bottom_value = params->FindKey("marginBottom")) margin_bottom_in_inch = margin_bottom_value->GetDouble(); if (const base::Value* margin_left_value = params->FindKey("marginLeft")) margin_left_in_inch = margin_left_value->GetDouble(); if (const base::Value* margin_right_value = params->FindKey("marginRight")) margin_right_in_inch = margin_right_value->GetDouble(); if (const base::Value* header_template_value = params->FindKey("headerTemplate")) { settings->header_template = header_template_value->GetString(); } if (const base::Value* footer_template_value = params->FindKey("footerTemplate")) { settings->footer_template = footer_template_value->GetString(); } if (margin_top_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginTop"); if (margin_bottom_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginBottom"); if (margin_left_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginLeft"); if (margin_right_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginRight"); settings->margins_in_points.top = margin_top_in_inch * printing::kPointsPerInch; settings->margins_in_points.bottom = margin_bottom_in_inch * printing::kPointsPerInch; settings->margins_in_points.left = margin_left_in_inch * printing::kPointsPerInch; settings->margins_in_points.right = margin_right_in_inch * printing::kPointsPerInch; return nullptr; }
172,901
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadOTBImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define GetBit(a,i) (((a) >> (i)) & 1L) Image *image; int byte; MagickBooleanType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; ssize_t y; unsigned char bit, info, depth; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize image structure. */ info=(unsigned char) ReadBlobByte(image); if (GetBit(info,4) == 0) { image->columns=(size_t) ReadBlobByte(image); image->rows=(size_t) ReadBlobByte(image); } else { image->columns=(size_t) ReadBlobMSBShort(image); image->rows=(size_t) ReadBlobMSBShort(image); } if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); depth=(unsigned char) ReadBlobByte(image); if (depth != 1) ThrowReaderException(CoderError,"OnlyLevelZerofilesSupported"); if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Convert bi-level image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { if (bit == 0) { byte=ReadBlobByte(image); if (byte == EOF) ThrowReaderException(CorruptImageError,"CorruptImage"); } SetPixelIndex(indexes+x,(byte & (0x01 << (7-bit))) ? 0x00 : 0x01); bit++; if (bit == 8) bit=0; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadOTBImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define GetBit(a,i) (((a) >> (i)) & 1L) Image *image; int byte; MagickBooleanType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; ssize_t y; unsigned char bit, info, depth; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize image structure. */ info=(unsigned char) ReadBlobByte(image); if (GetBit(info,4) == 0) { image->columns=(size_t) ReadBlobByte(image); image->rows=(size_t) ReadBlobByte(image); } else { image->columns=(size_t) ReadBlobMSBShort(image); image->rows=(size_t) ReadBlobMSBShort(image); } if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); depth=(unsigned char) ReadBlobByte(image); if (depth != 1) ThrowReaderException(CoderError,"OnlyLevelZerofilesSupported"); if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Convert bi-level image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { if (bit == 0) { byte=ReadBlobByte(image); if (byte == EOF) ThrowReaderException(CorruptImageError,"CorruptImage"); } SetPixelIndex(indexes+x,(byte & (0x01 << (7-bit))) ? 0x00 : 0x01); bit++; if (bit == 8) bit=0; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,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 Chapters::Display::Init() { m_string = NULL; m_language = NULL; m_country = NULL; } 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
void Chapters::Display::Init()
174,388
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: cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size) { size_t i, j; cdf_secid_t maxsector = (cdf_secid_t)(sat->sat_len * size); DPRINTF(("Chain:")); for (j = i = 0; sid >= 0; i++, j++) { DPRINTF((" %d", sid)); if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Counting chain loop limit")); errno = EFTYPE; return (size_t)-1; } if (sid > maxsector) { DPRINTF(("Sector %d > %d\n", sid, maxsector)); errno = EFTYPE; return (size_t)-1; } sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]); } if (i == 0) { DPRINTF((" none, sid: %d\n", sid)); return (size_t)-1; } DPRINTF(("\n")); return i; } Commit Message: Fix incorrect bounds check for sector count. (Francisco Alonso and Jan Kaluza at RedHat) CWE ID: CWE-20
cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size) { size_t i, j; cdf_secid_t maxsector = (cdf_secid_t)((sat->sat_len * size) / sizeof(maxsector)); DPRINTF(("Chain:")); for (j = i = 0; sid >= 0; i++, j++) { DPRINTF((" %d", sid)); if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Counting chain loop limit")); errno = EFTYPE; return (size_t)-1; } if (sid >= maxsector) { DPRINTF(("Sector %d >= %d\n", sid, maxsector)); errno = EFTYPE; return (size_t)-1; } sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]); } if (i == 0) { DPRINTF((" none, sid: %d\n", sid)); return (size_t)-1; } DPRINTF(("\n")); return i; }
166,365
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: native_handle_t* native_handle_create(int numFds, int numInts) { native_handle_t* h = malloc( sizeof(native_handle_t) + sizeof(int)*(numFds+numInts)); if (h) { h->version = sizeof(native_handle_t); h->numFds = numFds; h->numInts = numInts; } return h; } Commit Message: Prevent integer overflow when allocating native_handle_t User specified values of numInts and numFds can overflow and cause malloc to allocate less than we expect, causing heap corruption in subsequent operations on the allocation. Bug: 19334482 Change-Id: I43c75f536ea4c08f14ca12ca6288660fd2d1ec55 CWE ID: CWE-189
native_handle_t* native_handle_create(int numFds, int numInts) { if (numFds < 0 || numInts < 0 || numFds > kMaxNativeFds || numInts > kMaxNativeInts) { return NULL; } size_t mallocSize = sizeof(native_handle_t) + (sizeof(int) * (numFds + numInts)); native_handle_t* h = malloc(mallocSize); if (h) { h->version = sizeof(native_handle_t); h->numFds = numFds; h->numInts = numInts; } return h; }
174,123
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: newEntry(struct rx_call *call, char aname[], afs_int32 flag, afs_int32 oid, afs_int32 *aid, afs_int32 *cid) { afs_int32 code; struct ubik_trans *tt; int admin; char cname[PR_MAXNAMELEN]; stolower(aname); code = Initdb(); if (code) return code; code = ubik_BeginTrans(dbase, UBIK_WRITETRANS, &tt); if (code) return code; code = ubik_SetLock(tt, 1, 1, LOCKWRITE); if (code) ABORT_WITH(tt, code); code = read_DbHeader(tt); if (code) ABORT_WITH(tt, code); /* this is for cross-cell self registration. It is not added in the * SPR_INewEntry because we want self-registration to only do * automatic id assignment. */ code = WhoIsThisWithName(call, tt, cid, cname); if (code != 2) { /* 2 specifies that this is a foreign cell request */ if (code) ABORT_WITH(tt, PRPERM); admin = IsAMemberOf(tt, *cid, SYSADMINID); } else { admin = ((!restricted && !strcmp(aname, cname))) || IsAMemberOf(tt, *cid, SYSADMINID); oid = *cid = SYSADMINID; } if (!CreateOK(tt, *cid, oid, flag, admin)) ABORT_WITH(tt, PRPERM); if (code) return code; return PRSUCCESS; } Commit Message: CWE ID: CWE-284
newEntry(struct rx_call *call, char aname[], afs_int32 flag, afs_int32 oid, afs_int32 *aid, afs_int32 *cid) { afs_int32 code; struct ubik_trans *tt; int admin; char cname[PR_MAXNAMELEN]; stolower(aname); code = Initdb(); if (code) return code; code = ubik_BeginTrans(dbase, UBIK_WRITETRANS, &tt); if (code) return code; code = ubik_SetLock(tt, 1, 1, LOCKWRITE); if (code) ABORT_WITH(tt, code); code = read_DbHeader(tt); if (code) ABORT_WITH(tt, code); /* this is for cross-cell self registration. It is not added in the * SPR_INewEntry because we want self-registration to only do * automatic id assignment. */ code = WhoIsThisWithName(call, tt, cid, cname); if (code && code != 2) ABORT_WITH(tt, PRPERM); admin = IsAMemberOf(tt, *cid, SYSADMINID); if (code == 2 /* foreign cell request */) { if (!restricted && (strcmp(aname, cname) == 0)) { /* can't autoregister while providing an owner id */ if (oid != 0) ABORT_WITH(tt, PRPERM); admin = 1; oid = SYSADMINID; *cid = SYSADMINID; } } if (!CreateOK(tt, *cid, oid, flag, admin)) ABORT_WITH(tt, PRPERM); if (code) return code; return PRSUCCESS; }
165,179
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: init_rc(void) { int i; struct stat st; FILE *f; if (rc_dir != NULL) goto open_rc; rc_dir = expandPath(RC_DIR); i = strlen(rc_dir); if (i > 1 && rc_dir[i - 1] == '/') rc_dir[i - 1] = '\0'; #ifdef USE_M17N display_charset_str = wc_get_ces_list(); document_charset_str = display_charset_str; system_charset_str = display_charset_str; #endif if (stat(rc_dir, &st) < 0) { if (errno == ENOENT) { /* no directory */ if (do_mkdir(rc_dir, 0700) < 0) { /* fprintf(stderr, "Can't create config directory (%s)!\n", rc_dir); */ goto rc_dir_err; } else { stat(rc_dir, &st); } } else { /* fprintf(stderr, "Can't open config directory (%s)!\n", rc_dir); */ goto rc_dir_err; } } if (!S_ISDIR(st.st_mode)) { /* not a directory */ /* fprintf(stderr, "%s is not a directory!\n", rc_dir); */ goto rc_dir_err; } if (!(st.st_mode & S_IWUSR)) { /* fprintf(stderr, "%s is not writable!\n", rc_dir); */ goto rc_dir_err; } no_rc_dir = FALSE; tmp_dir = rc_dir; if (config_file == NULL) config_file = rcFile(CONFIG_FILE); create_option_search_table(); open_rc: /* open config file */ if ((f = fopen(etcFile(W3MCONFIG), "rt")) != NULL) { interpret_rc(f); fclose(f); } if ((f = fopen(confFile(CONFIG_FILE), "rt")) != NULL) { interpret_rc(f); fclose(f); } if (config_file && (f = fopen(config_file, "rt")) != NULL) { interpret_rc(f); fclose(f); } return; rc_dir_err: no_rc_dir = TRUE; if (((tmp_dir = getenv("TMPDIR")) == NULL || *tmp_dir == '\0') && ((tmp_dir = getenv("TMP")) == NULL || *tmp_dir == '\0') && ((tmp_dir = getenv("TEMP")) == NULL || *tmp_dir == '\0')) tmp_dir = "/tmp"; create_option_search_table(); goto open_rc; } Commit Message: Make temporary directory safely when ~/.w3m is unwritable CWE ID: CWE-59
init_rc(void) { int i; struct stat st; FILE *f; if (rc_dir != NULL) goto open_rc; rc_dir = expandPath(RC_DIR); i = strlen(rc_dir); if (i > 1 && rc_dir[i - 1] == '/') rc_dir[i - 1] = '\0'; #ifdef USE_M17N display_charset_str = wc_get_ces_list(); document_charset_str = display_charset_str; system_charset_str = display_charset_str; #endif if (stat(rc_dir, &st) < 0) { if (errno == ENOENT) { /* no directory */ if (do_mkdir(rc_dir, 0700) < 0) { /* fprintf(stderr, "Can't create config directory (%s)!\n", rc_dir); */ goto rc_dir_err; } else { stat(rc_dir, &st); } } else { /* fprintf(stderr, "Can't open config directory (%s)!\n", rc_dir); */ goto rc_dir_err; } } if (!S_ISDIR(st.st_mode)) { /* not a directory */ /* fprintf(stderr, "%s is not a directory!\n", rc_dir); */ goto rc_dir_err; } if (!(st.st_mode & S_IWUSR)) { /* fprintf(stderr, "%s is not writable!\n", rc_dir); */ goto rc_dir_err; } no_rc_dir = FALSE; tmp_dir = rc_dir; if (config_file == NULL) config_file = rcFile(CONFIG_FILE); create_option_search_table(); open_rc: /* open config file */ if ((f = fopen(etcFile(W3MCONFIG), "rt")) != NULL) { interpret_rc(f); fclose(f); } if ((f = fopen(confFile(CONFIG_FILE), "rt")) != NULL) { interpret_rc(f); fclose(f); } if (config_file && (f = fopen(config_file, "rt")) != NULL) { interpret_rc(f); fclose(f); } return; rc_dir_err: no_rc_dir = TRUE; if (((tmp_dir = getenv("TMPDIR")) == NULL || *tmp_dir == '\0') && ((tmp_dir = getenv("TMP")) == NULL || *tmp_dir == '\0') && ((tmp_dir = getenv("TEMP")) == NULL || *tmp_dir == '\0')) tmp_dir = "/tmp"; #ifdef HAVE_MKDTEMP tmp_dir = mkdtemp(Strnew_m_charp(tmp_dir, "/w3m-XXXXXX", NULL)->ptr); if (tmp_dir == NULL) tmp_dir = rc_dir; #endif create_option_search_table(); goto open_rc; }
169,346
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 ConvertProperty(IBusProperty* ibus_prop, int selection_item_id, ImePropertyList* out_prop_list) { DCHECK(ibus_prop); DCHECK(ibus_prop->key); DCHECK(out_prop_list); const bool has_sub_props = PropertyHasChildren(ibus_prop); if (has_sub_props && (ibus_prop->type != PROP_TYPE_MENU)) { LOG(ERROR) << "The property has sub properties, " << "but the type of the property is not PROP_TYPE_MENU"; return false; } if ((!has_sub_props) && (ibus_prop->type == PROP_TYPE_MENU)) { DLOG(INFO) << "Property list is empty"; return false; } if (ibus_prop->type == PROP_TYPE_SEPARATOR || ibus_prop->type == PROP_TYPE_MENU) { return true; } const bool is_selection_item = (ibus_prop->type == PROP_TYPE_RADIO); selection_item_id = is_selection_item ? selection_item_id : ImeProperty::kInvalidSelectionItemId; bool is_selection_item_checked = false; if (ibus_prop->state == PROP_STATE_INCONSISTENT) { LOG(WARNING) << "The property is in PROP_STATE_INCONSISTENT, " << "which is not supported."; } else if ((!is_selection_item) && (ibus_prop->state == PROP_STATE_CHECKED)) { LOG(WARNING) << "PROP_STATE_CHECKED is meaningful only if the type is " << "PROP_TYPE_RADIO."; } else { is_selection_item_checked = (ibus_prop->state == PROP_STATE_CHECKED); } if (!ibus_prop->key) { LOG(ERROR) << "key is NULL"; } if (ibus_prop->tooltip && (!ibus_prop->tooltip->text)) { LOG(ERROR) << "tooltip is NOT NULL, but tooltip->text IS NULL: key=" << Or(ibus_prop->key, ""); } if (ibus_prop->label && (!ibus_prop->label->text)) { LOG(ERROR) << "label is NOT NULL, but label->text IS NULL: key=" << Or(ibus_prop->key, ""); } std::string label = ((ibus_prop->tooltip && ibus_prop->tooltip->text) ? ibus_prop->tooltip->text : ""); if (label.empty()) { label = (ibus_prop->label && ibus_prop->label->text) ? ibus_prop->label->text : ""; } if (label.empty()) { label = Or(ibus_prop->key, ""); } out_prop_list->push_back(ImeProperty(ibus_prop->key, label, is_selection_item, is_selection_item_checked, selection_item_id)); return true; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ConvertProperty(IBusProperty* ibus_prop, int selection_item_id, ImePropertyList* out_prop_list) { DCHECK(ibus_prop); DCHECK(ibus_prop->key); DCHECK(out_prop_list); const bool has_sub_props = PropertyHasChildren(ibus_prop); if (has_sub_props && (ibus_prop->type != PROP_TYPE_MENU)) { LOG(ERROR) << "The property has sub properties, " << "but the type of the property is not PROP_TYPE_MENU"; return false; } if ((!has_sub_props) && (ibus_prop->type == PROP_TYPE_MENU)) { VLOG(1) << "Property list is empty"; return false; } if (ibus_prop->type == PROP_TYPE_SEPARATOR || ibus_prop->type == PROP_TYPE_MENU) { return true; } const bool is_selection_item = (ibus_prop->type == PROP_TYPE_RADIO); selection_item_id = is_selection_item ? selection_item_id : ImeProperty::kInvalidSelectionItemId; bool is_selection_item_checked = false; if (ibus_prop->state == PROP_STATE_INCONSISTENT) { LOG(WARNING) << "The property is in PROP_STATE_INCONSISTENT, " << "which is not supported."; } else if ((!is_selection_item) && (ibus_prop->state == PROP_STATE_CHECKED)) { LOG(WARNING) << "PROP_STATE_CHECKED is meaningful only if the type is " << "PROP_TYPE_RADIO."; } else { is_selection_item_checked = (ibus_prop->state == PROP_STATE_CHECKED); } if (!ibus_prop->key) { LOG(ERROR) << "key is NULL"; } if (ibus_prop->tooltip && (!ibus_prop->tooltip->text)) { LOG(ERROR) << "tooltip is NOT NULL, but tooltip->text IS NULL: key=" << Or(ibus_prop->key, ""); } if (ibus_prop->label && (!ibus_prop->label->text)) { LOG(ERROR) << "label is NOT NULL, but label->text IS NULL: key=" << Or(ibus_prop->key, ""); } std::string label = ((ibus_prop->tooltip && ibus_prop->tooltip->text) ? ibus_prop->tooltip->text : ""); if (label.empty()) { label = (ibus_prop->label && ibus_prop->label->text) ? ibus_prop->label->text : ""; } if (label.empty()) { label = Or(ibus_prop->key, ""); } out_prop_list->push_back(ImeProperty(ibus_prop->key, label, is_selection_item, is_selection_item_checked, selection_item_id)); return true; }
170,531
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: PHP_FUNCTION(stream_resolve_include_path) { char *filename, *resolved_path; int filename_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &filename, &filename_len) == FAILURE) { return; } resolved_path = zend_resolve_path(filename, filename_len TSRMLS_CC); if (resolved_path) { RETURN_STRING(resolved_path, 0); } RETURN_FALSE; } Commit Message: CWE ID: CWE-254
PHP_FUNCTION(stream_resolve_include_path) { char *filename, *resolved_path; int filename_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &filename, &filename_len) == FAILURE) { return; } resolved_path = zend_resolve_path(filename, filename_len TSRMLS_CC); if (resolved_path) { RETURN_STRING(resolved_path, 0); } RETURN_FALSE; }
165,317
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: OTRBrowserContextImpl::OTRBrowserContextImpl( BrowserContextImpl* original, BrowserContextIODataImpl* original_io_data) : BrowserContext(new OTRBrowserContextIODataImpl(original_io_data)), original_context_(original), weak_ptr_factory_(this) { BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServices(this); } Commit Message: CWE ID: CWE-20
OTRBrowserContextImpl::OTRBrowserContextImpl( BrowserContextImpl* original, BrowserContextIODataImpl* original_io_data) : BrowserContext(new OTRBrowserContextIODataImpl(original_io_data)), original_context_(original) { BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServices(this); }
165,416
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: _php_mb_regex_init_options(const char *parg, int narg, OnigOptionType *option, OnigSyntaxType **syntax, int *eval) { int n; char c; int optm = 0; *syntax = ONIG_SYNTAX_RUBY; if (parg != NULL) { n = 0; while(n < narg) { c = parg[n++]; switch (c) { case 'i': optm |= ONIG_OPTION_IGNORECASE; break; case 'x': optm |= ONIG_OPTION_EXTEND; break; case 'm': optm |= ONIG_OPTION_MULTILINE; break; case 's': optm |= ONIG_OPTION_SINGLELINE; break; case 'p': optm |= ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE; break; case 'l': optm |= ONIG_OPTION_FIND_LONGEST; break; case 'n': optm |= ONIG_OPTION_FIND_NOT_EMPTY; break; case 'j': *syntax = ONIG_SYNTAX_JAVA; break; case 'u': *syntax = ONIG_SYNTAX_GNU_REGEX; break; case 'g': *syntax = ONIG_SYNTAX_GREP; break; case 'c': *syntax = ONIG_SYNTAX_EMACS; break; case 'r': *syntax = ONIG_SYNTAX_RUBY; break; case 'z': *syntax = ONIG_SYNTAX_PERL; break; case 'b': *syntax = ONIG_SYNTAX_POSIX_BASIC; break; case 'd': *syntax = ONIG_SYNTAX_POSIX_EXTENDED; break; case 'e': if (eval != NULL) *eval = 1; break; default: break; } } if (option != NULL) *option|=optm; } } Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free CWE ID: CWE-415
_php_mb_regex_init_options(const char *parg, int narg, OnigOptionType *option, OnigSyntaxType **syntax, int *eval) _php_mb_regex_init_options(const char *parg, int narg, OnigOptionType *option, OnigSyntaxType **syntax, int *eval) { int n; char c; int optm = 0; *syntax = ONIG_SYNTAX_RUBY; if (parg != NULL) { n = 0; while(n < narg) { c = parg[n++]; switch (c) { case 'i': optm |= ONIG_OPTION_IGNORECASE; break; case 'x': optm |= ONIG_OPTION_EXTEND; break; case 'm': optm |= ONIG_OPTION_MULTILINE; break; case 's': optm |= ONIG_OPTION_SINGLELINE; break; case 'p': optm |= ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE; break; case 'l': optm |= ONIG_OPTION_FIND_LONGEST; break; case 'n': optm |= ONIG_OPTION_FIND_NOT_EMPTY; break; case 'j': *syntax = ONIG_SYNTAX_JAVA; break; case 'u': *syntax = ONIG_SYNTAX_GNU_REGEX; break; case 'g': *syntax = ONIG_SYNTAX_GREP; break; case 'c': *syntax = ONIG_SYNTAX_EMACS; break; case 'r': *syntax = ONIG_SYNTAX_RUBY; break; case 'z': *syntax = ONIG_SYNTAX_PERL; break; case 'b': *syntax = ONIG_SYNTAX_POSIX_BASIC; break; case 'd': *syntax = ONIG_SYNTAX_POSIX_EXTENDED; break; case 'e': if (eval != NULL) *eval = 1; break; default: break; } } if (option != NULL) *option|=optm; } }
167,120
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 vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length) { struct pipe_vertex_element *ve = NULL; int num_elements; int i; int ret; if (length < 1) return EINVAL; if ((length - 1) % 4) return EINVAL; num_elements = (length - 1) / 4; if (num_elements) { ve = calloc(num_elements, sizeof(struct pipe_vertex_element)); if (!ve) return ENOMEM; for (i = 0; i < num_elements; i++) { ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i)); ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i)); ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i)); ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i)); } } return ret; } Commit Message: CWE ID: CWE-125
static int vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length) { struct pipe_vertex_element *ve = NULL; int num_elements; int i; int ret; if (length < 1) return EINVAL; if ((length - 1) % 4) return EINVAL; num_elements = (length - 1) / 4; if (num_elements) { ve = calloc(num_elements, sizeof(struct pipe_vertex_element)); if (!ve) return ENOMEM; for (i = 0; i < num_elements; i++) { ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i)); ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i)); ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i)); if (ve[i].vertex_buffer_index >= PIPE_MAX_ATTRIBS) return EINVAL; ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i)); } } return ret; }
164,957
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 JSON_INLINE size_t num_buckets(hashtable_t *hashtable) { return primes[hashtable->num_buckets]; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
static JSON_INLINE size_t num_buckets(hashtable_t *hashtable)
166,534
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bgp_nlri_parse_vpnv4 (struct peer *peer, struct attr *attr, struct bgp_nlri *packet) { u_char *pnt; u_char *lim; struct prefix p; int psize; int prefixlen; u_int16_t type; struct rd_as rd_as; struct rd_ip rd_ip; struct prefix_rd prd; u_char *tagpnt; /* Check peer status. */ if (peer->status != Established) return 0; /* Make prefix_rd */ prd.family = AF_UNSPEC; prd.prefixlen = 64; pnt = packet->nlri; lim = pnt + packet->length; for (; pnt < lim; pnt += psize) { /* Clear prefix structure. */ /* Fetch prefix length. */ prefixlen = *pnt++; p.family = AF_INET; psize = PSIZE (prefixlen); if (prefixlen < 88) { zlog_err ("prefix length is less than 88: %d", prefixlen); return -1; } /* Copyr label to prefix. */ tagpnt = pnt;; /* Copy routing distinguisher to rd. */ memcpy (&prd.val, pnt + 3, 8); else if (type == RD_TYPE_IP) zlog_info ("prefix %ld:%s:%ld:%s/%d", label, inet_ntoa (rd_ip.ip), rd_ip.val, inet_ntoa (p.u.prefix4), p.prefixlen); #endif /* 0 */ if (pnt + psize > lim) return -1; if (attr) bgp_update (peer, &p, attr, AFI_IP, SAFI_MPLS_VPN, ZEBRA_ROUTE_BGP, BGP_ROUTE_NORMAL, &prd, tagpnt, 0); else return -1; } p.prefixlen = prefixlen - 88; memcpy (&p.u.prefix, pnt + 11, psize - 11); #if 0 if (type == RD_TYPE_AS) } Commit Message: CWE ID: CWE-119
bgp_nlri_parse_vpnv4 (struct peer *peer, struct attr *attr, struct bgp_nlri *packet) { u_char *pnt; u_char *lim; struct prefix p; int psize; int prefixlen; u_int16_t type; struct rd_as rd_as; struct rd_ip rd_ip; struct prefix_rd prd; u_char *tagpnt; /* Check peer status. */ if (peer->status != Established) return 0; /* Make prefix_rd */ prd.family = AF_UNSPEC; prd.prefixlen = 64; pnt = packet->nlri; lim = pnt + packet->length; #define VPN_PREFIXLEN_MIN_BYTES (3 + 8) /* label + RD */ for (; pnt < lim; pnt += psize) { /* Clear prefix structure. */ /* Fetch prefix length. */ prefixlen = *pnt++; p.family = afi2family (packet->afi); psize = PSIZE (prefixlen); /* sanity check against packet data */ if (prefixlen < VPN_PREFIXLEN_MIN_BYTES*8 || (pnt + psize) > lim) { zlog_err ("prefix length (%d) is less than 88" " or larger than received (%u)", prefixlen, (uint)(lim-pnt)); return -1; } /* sanity check against storage for the IP address portion */ if ((psize - VPN_PREFIXLEN_MIN_BYTES) > (ssize_t) sizeof(p.u)) { zlog_err ("prefix length (%d) exceeds prefix storage (%zu)", prefixlen - VPN_PREFIXLEN_MIN_BYTES*8, sizeof(p.u)); return -1; } /* Sanity check against max bitlen of the address family */ if ((psize - VPN_PREFIXLEN_MIN_BYTES) > prefix_blen (&p)) { zlog_err ("prefix length (%d) exceeds family (%u) max byte length (%u)", prefixlen - VPN_PREFIXLEN_MIN_BYTES*8, p.family, prefix_blen (&p)); return -1; } /* Copyr label to prefix. */ tagpnt = pnt; /* Copy routing distinguisher to rd. */ memcpy (&prd.val, pnt + 3, 8); else if (type == RD_TYPE_IP) zlog_info ("prefix %ld:%s:%ld:%s/%d", label, inet_ntoa (rd_ip.ip), rd_ip.val, inet_ntoa (p.u.prefix4), p.prefixlen); #endif /* 0 */ if (pnt + psize > lim) return -1; if (attr) bgp_update (peer, &p, attr, AFI_IP, SAFI_MPLS_VPN, ZEBRA_ROUTE_BGP, BGP_ROUTE_NORMAL, &prd, tagpnt, 0); else return -1; } p.prefixlen = prefixlen - VPN_PREFIXLEN_MIN_BYTES*8; memcpy (&p.u.prefix, pnt + VPN_PREFIXLEN_MIN_BYTES, psize - VPN_PREFIXLEN_MIN_BYTES); #if 0 if (type == RD_TYPE_AS) }
165,189
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 decode_bit_string(const u8 * inbuf, size_t inlen, void *outbuf, size_t outlen, int invert) { const u8 *in = inbuf; u8 *out = (u8 *) outbuf; int zero_bits = *in & 0x07; size_t octets_left = inlen - 1; int i, count = 0; memset(outbuf, 0, outlen); in++; if (outlen < octets_left) return SC_ERROR_BUFFER_TOO_SMALL; if (inlen < 1) return SC_ERROR_INVALID_ASN1_OBJECT; while (octets_left) { /* 1st octet of input: ABCDEFGH, where A is the MSB */ /* 1st octet of output: HGFEDCBA, where A is the LSB */ /* first bit in bit string is the LSB in first resulting octet */ int bits_to_go; *out = 0; if (octets_left == 1) bits_to_go = 8 - zero_bits; else bits_to_go = 8; if (invert) for (i = 0; i < bits_to_go; i++) { *out |= ((*in >> (7 - i)) & 1) << i; } else { *out = *in; } out++; in++; octets_left--; count++; } return (count * 8) - zero_bits; } Commit Message: fixed out of bounds access of ASN.1 Bitstring Credit to OSS-Fuzz CWE ID: CWE-119
static int decode_bit_string(const u8 * inbuf, size_t inlen, void *outbuf, size_t outlen, int invert) { const u8 *in = inbuf; u8 *out = (u8 *) outbuf; int i, count = 0; int zero_bits; size_t octets_left; if (outlen < octets_left) return SC_ERROR_BUFFER_TOO_SMALL; if (inlen < 1) return SC_ERROR_INVALID_ASN1_OBJECT; zero_bits = *in & 0x07; octets_left = inlen - 1; in++; memset(outbuf, 0, outlen); while (octets_left) { /* 1st octet of input: ABCDEFGH, where A is the MSB */ /* 1st octet of output: HGFEDCBA, where A is the LSB */ /* first bit in bit string is the LSB in first resulting octet */ int bits_to_go; *out = 0; if (octets_left == 1) bits_to_go = 8 - zero_bits; else bits_to_go = 8; if (invert) for (i = 0; i < bits_to_go; i++) { *out |= ((*in >> (7 - i)) & 1) << i; } else { *out = *in; } out++; in++; octets_left--; count++; } return (count * 8) - zero_bits; }
169,515
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: WtsSessionProcessDelegate::Core::Core( scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, const FilePath& binary_path, bool launch_elevated, const std::string& channel_security) : main_task_runner_(main_task_runner), io_task_runner_(io_task_runner), binary_path_(binary_path), channel_security_(channel_security), launch_elevated_(launch_elevated), stopping_(false) { DCHECK(main_task_runner_->BelongsToCurrentThread()); } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
WtsSessionProcessDelegate::Core::Core( scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, const FilePath& binary_path, bool launch_elevated, const std::string& channel_security) : main_task_runner_(main_task_runner), io_task_runner_(io_task_runner), binary_path_(binary_path), channel_security_(channel_security), get_named_pipe_client_pid_(NULL), launch_elevated_(launch_elevated), stopping_(false) { DCHECK(main_task_runner_->BelongsToCurrentThread()); }
171,555
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 get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c) { uint8_t byte; if (bytestream2_get_bytes_left(&s->g) < 5) return AVERROR_INVALIDDATA; /* nreslevels = number of resolution levels = number of decomposition level +1 */ c->nreslevels = bytestream2_get_byteu(&s->g) + 1; if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) { av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels); return AVERROR_INVALIDDATA; } /* compute number of resolution levels to decode */ if (c->nreslevels < s->reduction_factor) c->nreslevels2decode = 1; else c->nreslevels2decode = c->nreslevels - s->reduction_factor; c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 || c->log2_cblk_width + c->log2_cblk_height > 12) { av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n"); return AVERROR_INVALIDDATA; } if (c->log2_cblk_width > 6 || c->log2_cblk_height > 6) { avpriv_request_sample(s->avctx, "cblk size > 64"); return AVERROR_PATCHWELCOME; } c->cblk_style = bytestream2_get_byteu(&s->g); if (c->cblk_style != 0) { // cblk style av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style); } c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type /* set integer 9/7 DWT in case of BITEXACT flag */ if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97)) c->transform = FF_DWT97_INT; if (c->csty & JPEG2000_CSTY_PREC) { int i; for (i = 0; i < c->nreslevels; i++) { byte = bytestream2_get_byte(&s->g); c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy } } else { memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths )); memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights)); } return 0; } Commit Message: avcodec/jpeg2000dec: fix context consistency with too large lowres Fixes out of array accesses Fixes Ticket2898 Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-20
static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c) { uint8_t byte; if (bytestream2_get_bytes_left(&s->g) < 5) return AVERROR_INVALIDDATA; /* nreslevels = number of resolution levels = number of decomposition level +1 */ c->nreslevels = bytestream2_get_byteu(&s->g) + 1; if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) { av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels); return AVERROR_INVALIDDATA; } if (c->nreslevels <= s->reduction_factor) { /* we are forced to update reduction_factor as its requested value is not compatible with this bitstream, and as we might have used it already in setup earlier we have to fail this frame until reinitialization is implemented */ av_log(s->avctx, AV_LOG_ERROR, "reduction_factor too large for this bitstream, max is %d\n", c->nreslevels - 1); s->reduction_factor = c->nreslevels - 1; return AVERROR(EINVAL); } /* compute number of resolution levels to decode */ c->nreslevels2decode = c->nreslevels - s->reduction_factor; c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 || c->log2_cblk_width + c->log2_cblk_height > 12) { av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n"); return AVERROR_INVALIDDATA; } if (c->log2_cblk_width > 6 || c->log2_cblk_height > 6) { avpriv_request_sample(s->avctx, "cblk size > 64"); return AVERROR_PATCHWELCOME; } c->cblk_style = bytestream2_get_byteu(&s->g); if (c->cblk_style != 0) { // cblk style av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style); } c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type /* set integer 9/7 DWT in case of BITEXACT flag */ if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97)) c->transform = FF_DWT97_INT; if (c->csty & JPEG2000_CSTY_PREC) { int i; for (i = 0; i < c->nreslevels; i++) { byte = bytestream2_get_byte(&s->g); c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy } } else { memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths )); memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights)); } return 0; }
165,918
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: raptor_libxml_getEntity(void* user_data, const xmlChar *name) { raptor_sax2* sax2 = (raptor_sax2*)user_data; return libxml2_getEntity(sax2->xc, name); } Commit Message: CVE-2012-0037 Enforce entity loading policy in raptor_libxml_resolveEntity and raptor_libxml_getEntity by checking for file URIs and network URIs. Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for turning on loading of XML external entity loading, disabled by default. This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and aliases) and rdfa. CWE ID: CWE-200
raptor_libxml_getEntity(void* user_data, const xmlChar *name) { raptor_libxml_getEntity(void* user_data, const xmlChar *name) { raptor_sax2* sax2 = (raptor_sax2*)user_data; xmlParserCtxtPtr xc = sax2->xc; xmlEntityPtr ret = NULL; if(!xc) return NULL; if(!xc->inSubset) { /* looks for hardcoded set of entity names - lt, gt etc. */ ret = xmlGetPredefinedEntity(name); if(ret) { RAPTOR_DEBUG2("Entity '%s' found in predefined set\n", name); return ret; } } /* This section uses xmlGetDocEntity which looks for entities in * memory only, never from a file or URI */ if(xc->myDoc && (xc->myDoc->standalone == 1)) { RAPTOR_DEBUG2("Entity '%s' document is standalone\n", name); /* Document is standalone: no entities are required to interpret doc */ if(xc->inSubset == 2) { xc->myDoc->standalone = 0; ret = xmlGetDocEntity(xc->myDoc, name); xc->myDoc->standalone = 1; } else { ret = xmlGetDocEntity(xc->myDoc, name); if(!ret) { xc->myDoc->standalone = 0; ret = xmlGetDocEntity(xc->myDoc, name); xc->myDoc->standalone = 1; } } } else { ret = xmlGetDocEntity(xc->myDoc, name); } if(ret && !ret->children && (ret->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) { /* Entity is an external general parsed entity. It may be in a * catalog file, user file or user URI */ int val = 0; xmlNodePtr children; int load_entity = 0; load_entity = RAPTOR_OPTIONS_GET_NUMERIC(sax2, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES); if(load_entity) load_entity = raptor_sax2_check_load_uri_string(sax2, ret->URI); if(!load_entity) { RAPTOR_DEBUG2("Not getting entity URI %s by policy\n", ret->URI); children = xmlNewText((const xmlChar*)""); } else { /* Disable SAX2 handlers so that the SAX2 events do not all get * sent to callbacks during dealing with the entity parsing. */ sax2->enabled = 0; val = xmlParseCtxtExternalEntity(xc, ret->URI, ret->ExternalID, &children); sax2->enabled = 1; } if(!val) { xmlAddChildList((xmlNodePtr)ret, children); } else { xc->validate = 0; return NULL; } ret->owner = 1; /* Mark this entity as having been checked - never do this again */ if(!ret->checked) ret->checked = 1; } return ret; }
165,658
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 BrowserLauncherItemController::TabDetachedAt(TabContents* contents, int index) { launcher_controller()->UpdateAppState( contents->web_contents(), ChromeLauncherController::APP_STATE_REMOVED); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void BrowserLauncherItemController::TabDetachedAt(TabContents* contents, void BrowserLauncherItemController::TabDetachedAt( content::WebContents* contents, int index) { launcher_controller()->UpdateAppState( contents, ChromeLauncherController::APP_STATE_REMOVED); }
171,506
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: WORD32 ih264d_parse_nal_unit(iv_obj_t *dec_hdl, ivd_video_decode_op_t *ps_dec_op, UWORD8 *pu1_buf, UWORD32 u4_length) { dec_bit_stream_t *ps_bitstrm; dec_struct_t *ps_dec = (dec_struct_t *)dec_hdl->pv_codec_handle; ivd_video_decode_ip_t *ps_dec_in = (ivd_video_decode_ip_t *)ps_dec->pv_dec_in; dec_slice_params_t * ps_cur_slice = ps_dec->ps_cur_slice; UWORD8 u1_first_byte, u1_nal_ref_idc; UWORD8 u1_nal_unit_type; WORD32 i_status = OK; ps_bitstrm = ps_dec->ps_bitstrm; if(pu1_buf) { if(u4_length) { ps_dec_op->u4_frame_decoded_flag = 0; ih264d_process_nal_unit(ps_dec->ps_bitstrm, pu1_buf, u4_length); SWITCHOFFTRACE; u1_first_byte = ih264d_get_bits_h264(ps_bitstrm, 8); if(NAL_FORBIDDEN_BIT(u1_first_byte)) { H264_DEC_DEBUG_PRINT("\nForbidden bit set in Nal Unit, Let's try\n"); } u1_nal_unit_type = NAL_UNIT_TYPE(u1_first_byte); ps_dec->u1_nal_unit_type = u1_nal_unit_type; u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_first_byte)); switch(u1_nal_unit_type) { case SLICE_DATA_PARTITION_A_NAL: case SLICE_DATA_PARTITION_B_NAL: case SLICE_DATA_PARTITION_C_NAL: if(!ps_dec->i4_decode_header) ih264d_parse_slice_partition(ps_dec, ps_bitstrm); break; case IDR_SLICE_NAL: case SLICE_NAL: /* ! */ DEBUG_THREADS_PRINTF("Decoding a slice NAL\n"); if(!ps_dec->i4_decode_header) { if(ps_dec->i4_header_decoded == 3) { /* ! */ ps_dec->u4_slice_start_code_found = 1; ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_decode_slice( (UWORD8)(u1_nal_unit_type == IDR_SLICE_NAL), u1_nal_ref_idc, ps_dec); if((ps_dec->u4_first_slice_in_pic != 0)&& ((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0)) { /* if the first slice header was not valid set to 1 */ ps_dec->u4_first_slice_in_pic = 1; } if(i_status != OK) { return i_status; } } else { H264_DEC_DEBUG_PRINT( "\nSlice NAL Supplied but no header has been supplied\n"); } } break; case SEI_NAL: if(!ps_dec->i4_decode_header) { ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_sei_message(ps_dec, ps_bitstrm); if(i_status != OK) return i_status; ih264d_parse_sei(ps_dec, ps_bitstrm); } break; case SEQ_PARAM_NAL: /* ! */ ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_sps(ps_dec, ps_bitstrm); if(i_status == ERROR_INV_SPS_PPS_T) return i_status; if(!i_status) ps_dec->i4_header_decoded |= 0x1; break; case PIC_PARAM_NAL: /* ! */ ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_pps(ps_dec, ps_bitstrm); if(i_status == ERROR_INV_SPS_PPS_T) return i_status; if(!i_status) ps_dec->i4_header_decoded |= 0x2; break; case ACCESS_UNIT_DELIMITER_RBSP: if(!ps_dec->i4_decode_header) { ih264d_access_unit_delimiter_rbsp(ps_dec); } break; case END_OF_STREAM_RBSP: if(!ps_dec->i4_decode_header) { ih264d_parse_end_of_stream(ps_dec); } break; case FILLER_DATA_NAL: if(!ps_dec->i4_decode_header) { ih264d_parse_filler_data(ps_dec, ps_bitstrm); } break; default: H264_DEC_DEBUG_PRINT("\nUnknown NAL type %d\n", u1_nal_unit_type); break; } } } return i_status; } Commit Message: Decoder: Fix slice number increment for error clips Bug: 28673410 CWE ID: CWE-119
WORD32 ih264d_parse_nal_unit(iv_obj_t *dec_hdl, ivd_video_decode_op_t *ps_dec_op, UWORD8 *pu1_buf, UWORD32 u4_length) { dec_bit_stream_t *ps_bitstrm; dec_struct_t *ps_dec = (dec_struct_t *)dec_hdl->pv_codec_handle; ivd_video_decode_ip_t *ps_dec_in = (ivd_video_decode_ip_t *)ps_dec->pv_dec_in; dec_slice_params_t * ps_cur_slice = ps_dec->ps_cur_slice; UWORD8 u1_first_byte, u1_nal_ref_idc; UWORD8 u1_nal_unit_type; WORD32 i_status = OK; ps_bitstrm = ps_dec->ps_bitstrm; if(pu1_buf) { if(u4_length) { ps_dec_op->u4_frame_decoded_flag = 0; ih264d_process_nal_unit(ps_dec->ps_bitstrm, pu1_buf, u4_length); SWITCHOFFTRACE; u1_first_byte = ih264d_get_bits_h264(ps_bitstrm, 8); if(NAL_FORBIDDEN_BIT(u1_first_byte)) { H264_DEC_DEBUG_PRINT("\nForbidden bit set in Nal Unit, Let's try\n"); } u1_nal_unit_type = NAL_UNIT_TYPE(u1_first_byte); // if any other nal unit other than slice nal is encountered in between a // frame break out of loop without consuming header if((ps_dec->u2_total_mbs_coded != 0) && (u1_nal_unit_type > IDR_SLICE_NAL)) { return ERROR_INCOMPLETE_FRAME; } ps_dec->u1_nal_unit_type = u1_nal_unit_type; u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_first_byte)); switch(u1_nal_unit_type) { case SLICE_DATA_PARTITION_A_NAL: case SLICE_DATA_PARTITION_B_NAL: case SLICE_DATA_PARTITION_C_NAL: if(!ps_dec->i4_decode_header) ih264d_parse_slice_partition(ps_dec, ps_bitstrm); break; case IDR_SLICE_NAL: case SLICE_NAL: /* ! */ DEBUG_THREADS_PRINTF("Decoding a slice NAL\n"); if(!ps_dec->i4_decode_header) { if(ps_dec->i4_header_decoded == 3) { /* ! */ ps_dec->u4_slice_start_code_found = 1; ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_decode_slice( (UWORD8)(u1_nal_unit_type == IDR_SLICE_NAL), u1_nal_ref_idc, ps_dec); if((ps_dec->u4_first_slice_in_pic != 0)&& ((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0)) { /* if the first slice header was not valid set to 1 */ ps_dec->u4_first_slice_in_pic = 1; } if(i_status != OK) { return i_status; } } else { H264_DEC_DEBUG_PRINT( "\nSlice NAL Supplied but no header has been supplied\n"); } } break; case SEI_NAL: if(!ps_dec->i4_decode_header) { ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_sei_message(ps_dec, ps_bitstrm); if(i_status != OK) return i_status; ih264d_parse_sei(ps_dec, ps_bitstrm); } break; case SEQ_PARAM_NAL: /* ! */ ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_sps(ps_dec, ps_bitstrm); if(i_status == ERROR_INV_SPS_PPS_T) return i_status; if(!i_status) ps_dec->i4_header_decoded |= 0x1; break; case PIC_PARAM_NAL: /* ! */ ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_pps(ps_dec, ps_bitstrm); if(i_status == ERROR_INV_SPS_PPS_T) return i_status; if(!i_status) ps_dec->i4_header_decoded |= 0x2; break; case ACCESS_UNIT_DELIMITER_RBSP: if(!ps_dec->i4_decode_header) { ih264d_access_unit_delimiter_rbsp(ps_dec); } break; case END_OF_STREAM_RBSP: if(!ps_dec->i4_decode_header) { ih264d_parse_end_of_stream(ps_dec); } break; case FILLER_DATA_NAL: if(!ps_dec->i4_decode_header) { ih264d_parse_filler_data(ps_dec, ps_bitstrm); } break; default: H264_DEC_DEBUG_PRINT("\nUnknown NAL type %d\n", u1_nal_unit_type); break; } } } return i_status; }
173,542
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 SharedWorkerDevToolsAgentHost::WorkerRestarted( SharedWorkerHost* worker_host) { DCHECK_EQ(WORKER_TERMINATED, state_); DCHECK(!worker_host_); state_ = WORKER_NOT_READY; worker_host_ = worker_host; for (DevToolsSession* session : sessions()) session->SetRenderer(GetProcess(), nullptr); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void SharedWorkerDevToolsAgentHost::WorkerRestarted( SharedWorkerHost* worker_host) { DCHECK_EQ(WORKER_TERMINATED, state_); DCHECK(!worker_host_); state_ = WORKER_NOT_READY; worker_host_ = worker_host; for (DevToolsSession* session : sessions()) session->SetRenderer(worker_host_->process_id(), nullptr); }
172,791
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 filter_frame(AVFilterLink *inlink, AVFrame *in) { DelogoContext *s = inlink->dst->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format); AVFrame *out; int hsub0 = desc->log2_chroma_w; int vsub0 = desc->log2_chroma_h; int direct = 0; int plane; AVRational sar; if (av_frame_is_writable(in)) { direct = 1; out = in; } else { out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } sar = in->sample_aspect_ratio; /* Assume square pixels if SAR is unknown */ if (!sar.num) sar.num = sar.den = 1; for (plane = 0; plane < 4 && in->data[plane]; plane++) { int hsub = plane == 1 || plane == 2 ? hsub0 : 0; int vsub = plane == 1 || plane == 2 ? vsub0 : 0; apply_delogo(out->data[plane], out->linesize[plane], in ->data[plane], in ->linesize[plane], FF_CEIL_RSHIFT(inlink->w, hsub), FF_CEIL_RSHIFT(inlink->h, vsub), sar, s->x>>hsub, s->y>>vsub, /* Up and left borders were rounded down, inject lost bits * into width and height to avoid error accumulation */ FF_CEIL_RSHIFT(s->w + (s->x & ((1<<hsub)-1)), hsub), FF_CEIL_RSHIFT(s->h + (s->y & ((1<<vsub)-1)), vsub), s->band>>FFMIN(hsub, vsub), s->show, direct); } if (!direct) av_frame_free(&in); return ff_filter_frame(outlink, out); } Commit Message: avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int filter_frame(AVFilterLink *inlink, AVFrame *in) { DelogoContext *s = inlink->dst->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format); AVFrame *out; int hsub0 = desc->log2_chroma_w; int vsub0 = desc->log2_chroma_h; int direct = 0; int plane; AVRational sar; if (av_frame_is_writable(in)) { direct = 1; out = in; } else { out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } sar = in->sample_aspect_ratio; /* Assume square pixels if SAR is unknown */ if (!sar.num) sar.num = sar.den = 1; for (plane = 0; plane < 4 && in->data[plane] && in->linesize[plane]; plane++) { int hsub = plane == 1 || plane == 2 ? hsub0 : 0; int vsub = plane == 1 || plane == 2 ? vsub0 : 0; apply_delogo(out->data[plane], out->linesize[plane], in ->data[plane], in ->linesize[plane], FF_CEIL_RSHIFT(inlink->w, hsub), FF_CEIL_RSHIFT(inlink->h, vsub), sar, s->x>>hsub, s->y>>vsub, /* Up and left borders were rounded down, inject lost bits * into width and height to avoid error accumulation */ FF_CEIL_RSHIFT(s->w + (s->x & ((1<<hsub)-1)), hsub), FF_CEIL_RSHIFT(s->h + (s->y & ((1<<vsub)-1)), vsub), s->band>>FFMIN(hsub, vsub), s->show, direct); } if (!direct) av_frame_free(&in); return ff_filter_frame(outlink, out); }
165,998
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 readSeparateStripsIntoBuffer (TIFF *in, uint8 *obuf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { int i, j, bytes_per_sample, bytes_per_pixel, shift_width, result = 1; int32 bytes_read = 0; uint16 bps, nstrips, planar, strips_per_sample; uint32 src_rowsize, dst_rowsize, rows_processed, rps; uint32 rows_this_strip = 0; tsample_t s; tstrip_t strip; tsize_t scanlinesize = TIFFScanlineSize(in); tsize_t stripsize = TIFFStripSize(in); unsigned char *srcbuffs[MAX_SAMPLES]; unsigned char *buff = NULL; unsigned char *dst = NULL; if (obuf == NULL) { TIFFError("readSeparateStripsIntoBuffer","Invalid buffer argument"); return (0); } memset (srcbuffs, '\0', sizeof(srcbuffs)); TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); if (rps > length) rps = length; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; src_rowsize = ((bps * width) + 7) / 8; dst_rowsize = ((bps * width * spp) + 7) / 8; dst = obuf; if ((dump->infile != NULL) && (dump->level == 3)) { dump_info (dump->infile, dump->format, "", "Image width %d, length %d, Scanline size, %4d bytes", width, length, scanlinesize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d, Shift width %d", bps, spp, shift_width); } /* Libtiff seems to assume/require that data for separate planes are * written one complete plane after another and not interleaved in any way. * Multiple scanlines and possibly strips of the same plane must be * written before data for any other plane. */ nstrips = TIFFNumberOfStrips(in); strips_per_sample = nstrips /spp; for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { srcbuffs[s] = NULL; buff = _TIFFmalloc(stripsize); if (!buff) { TIFFError ("readSeparateStripsIntoBuffer", "Unable to allocate strip read buffer for sample %d", s); for (i = 0; i < s; i++) _TIFFfree (srcbuffs[i]); return 0; } srcbuffs[s] = buff; } rows_processed = 0; for (j = 0; (j < strips_per_sample) && (result == 1); j++) { for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; strip = (s * strips_per_sample) + j; bytes_read = TIFFReadEncodedStrip (in, strip, buff, stripsize); rows_this_strip = bytes_read / src_rowsize; if (bytes_read < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu for sample %d", (unsigned long) strip, s + 1); result = 0; break; } #ifdef DEVELMODE TIFFError("", "Strip %2d, read %5d bytes for %4d scanlines, shift width %d", strip, bytes_read, rows_this_strip, shift_width); #endif } if (rps > rows_this_strip) rps = rows_this_strip; dst = obuf + (dst_rowsize * rows_processed); if ((bps % 8) == 0) { if (combineSeparateSamplesBytes (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } } else { switch (shift_width) { case 1: if (combineSeparateSamples8bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 2: if (combineSeparateSamples16bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 3: if (combineSeparateSamples24bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 4: case 5: case 6: case 7: case 8: if (combineSeparateSamples32bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; default: TIFFError ("readSeparateStripsIntoBuffer", "Unsupported bit depth: %d", bps); result = 0; break; } } if ((rows_processed + rps) > length) { rows_processed = length; rps = length - rows_processed; } else rows_processed += rps; } /* free any buffers allocated for each plane or scanline and * any temporary buffers */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; if (buff != NULL) _TIFFfree(buff); } return (result); } /* end readSeparateStripsIntoBuffer */ Commit Message: * tools/tiffcp.c: fix read of undefined variable in case of missing required tags. Found on test case of MSVR 35100. * tools/tiffcrop.c: fix read of undefined buffer in readContigStripsIntoBuffer() due to uint16 overflow. Probably not a security issue but I can be wrong. Reported as MSVR 35100 by Axel Souchet from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-190
static int readSeparateStripsIntoBuffer (TIFF *in, uint8 *obuf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { int i, bytes_per_sample, bytes_per_pixel, shift_width, result = 1; uint32 j; int32 bytes_read = 0; uint16 bps, planar; uint32 nstrips; uint32 strips_per_sample; uint32 src_rowsize, dst_rowsize, rows_processed, rps; uint32 rows_this_strip = 0; tsample_t s; tstrip_t strip; tsize_t scanlinesize = TIFFScanlineSize(in); tsize_t stripsize = TIFFStripSize(in); unsigned char *srcbuffs[MAX_SAMPLES]; unsigned char *buff = NULL; unsigned char *dst = NULL; if (obuf == NULL) { TIFFError("readSeparateStripsIntoBuffer","Invalid buffer argument"); return (0); } memset (srcbuffs, '\0', sizeof(srcbuffs)); TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); if (rps > length) rps = length; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; src_rowsize = ((bps * width) + 7) / 8; dst_rowsize = ((bps * width * spp) + 7) / 8; dst = obuf; if ((dump->infile != NULL) && (dump->level == 3)) { dump_info (dump->infile, dump->format, "", "Image width %d, length %d, Scanline size, %4d bytes", width, length, scanlinesize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d, Shift width %d", bps, spp, shift_width); } /* Libtiff seems to assume/require that data for separate planes are * written one complete plane after another and not interleaved in any way. * Multiple scanlines and possibly strips of the same plane must be * written before data for any other plane. */ nstrips = TIFFNumberOfStrips(in); strips_per_sample = nstrips /spp; for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { srcbuffs[s] = NULL; buff = _TIFFmalloc(stripsize); if (!buff) { TIFFError ("readSeparateStripsIntoBuffer", "Unable to allocate strip read buffer for sample %d", s); for (i = 0; i < s; i++) _TIFFfree (srcbuffs[i]); return 0; } srcbuffs[s] = buff; } rows_processed = 0; for (j = 0; (j < strips_per_sample) && (result == 1); j++) { for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; strip = (s * strips_per_sample) + j; bytes_read = TIFFReadEncodedStrip (in, strip, buff, stripsize); rows_this_strip = bytes_read / src_rowsize; if (bytes_read < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu for sample %d", (unsigned long) strip, s + 1); result = 0; break; } #ifdef DEVELMODE TIFFError("", "Strip %2d, read %5d bytes for %4d scanlines, shift width %d", strip, bytes_read, rows_this_strip, shift_width); #endif } if (rps > rows_this_strip) rps = rows_this_strip; dst = obuf + (dst_rowsize * rows_processed); if ((bps % 8) == 0) { if (combineSeparateSamplesBytes (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } } else { switch (shift_width) { case 1: if (combineSeparateSamples8bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 2: if (combineSeparateSamples16bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 3: if (combineSeparateSamples24bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 4: case 5: case 6: case 7: case 8: if (combineSeparateSamples32bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; default: TIFFError ("readSeparateStripsIntoBuffer", "Unsupported bit depth: %d", bps); result = 0; break; } } if ((rows_processed + rps) > length) { rows_processed = length; rps = length - rows_processed; } else rows_processed += rps; } /* free any buffers allocated for each plane or scanline and * any temporary buffers */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; if (buff != NULL) _TIFFfree(buff); } return (result); } /* end readSeparateStripsIntoBuffer */
166,867
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long Chapters::Atom::GetStartTimecode() const { return m_start_timecode; } 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 Chapters::Atom::GetStartTimecode() const
174,356
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 validate_camera_metadata_structure(const camera_metadata_t *metadata, const size_t *expected_size) { if (metadata == NULL) { ALOGE("%s: metadata is null!", __FUNCTION__); return ERROR; } { static const struct { const char *name; size_t alignment; } alignments[] = { { .name = "camera_metadata", .alignment = METADATA_ALIGNMENT }, { .name = "camera_metadata_buffer_entry", .alignment = ENTRY_ALIGNMENT }, { .name = "camera_metadata_data", .alignment = DATA_ALIGNMENT }, }; for (size_t i = 0; i < sizeof(alignments)/sizeof(alignments[0]); ++i) { uintptr_t aligned_ptr = ALIGN_TO(metadata, alignments[i].alignment); if ((uintptr_t)metadata != aligned_ptr) { ALOGE("%s: Metadata pointer is not aligned (actual %p, " "expected %p) to type %s", __FUNCTION__, metadata, (void*)aligned_ptr, alignments[i].name); return ERROR; } } } /** * Check that the metadata contents are correct */ if (expected_size != NULL && metadata->size > *expected_size) { ALOGE("%s: Metadata size (%" PRIu32 ") should be <= expected size (%zu)", __FUNCTION__, metadata->size, *expected_size); return ERROR; } if (metadata->entry_count > metadata->entry_capacity) { ALOGE("%s: Entry count (%" PRIu32 ") should be <= entry capacity " "(%" PRIu32 ")", __FUNCTION__, metadata->entry_count, metadata->entry_capacity); return ERROR; } const metadata_uptrdiff_t entries_end = metadata->entries_start + metadata->entry_capacity; if (entries_end < metadata->entries_start || // overflow check entries_end > metadata->data_start) { ALOGE("%s: Entry start + capacity (%" PRIu32 ") should be <= data start " "(%" PRIu32 ")", __FUNCTION__, (metadata->entries_start + metadata->entry_capacity), metadata->data_start); return ERROR; } const metadata_uptrdiff_t data_end = metadata->data_start + metadata->data_capacity; if (data_end < metadata->data_start || // overflow check data_end > metadata->size) { ALOGE("%s: Data start + capacity (%" PRIu32 ") should be <= total size " "(%" PRIu32 ")", __FUNCTION__, (metadata->data_start + metadata->data_capacity), metadata->size); return ERROR; } const metadata_size_t entry_count = metadata->entry_count; camera_metadata_buffer_entry_t *entries = get_entries(metadata); for (size_t i = 0; i < entry_count; ++i) { if ((uintptr_t)&entries[i] != ALIGN_TO(&entries[i], ENTRY_ALIGNMENT)) { ALOGE("%s: Entry index %zu had bad alignment (address %p)," " expected alignment %zu", __FUNCTION__, i, &entries[i], ENTRY_ALIGNMENT); return ERROR; } camera_metadata_buffer_entry_t entry = entries[i]; if (entry.type >= NUM_TYPES) { ALOGE("%s: Entry index %zu had a bad type %d", __FUNCTION__, i, entry.type); return ERROR; } uint32_t tag_section = entry.tag >> 16; int tag_type = get_camera_metadata_tag_type(entry.tag); if (tag_type != (int)entry.type && tag_section < VENDOR_SECTION) { ALOGE("%s: Entry index %zu had tag type %d, but the type was %d", __FUNCTION__, i, tag_type, entry.type); return ERROR; } size_t data_size; if (validate_and_calculate_camera_metadata_entry_data_size(&data_size, entry.type, entry.count) != OK) { ALOGE("%s: Entry data size is invalid. type: %u count: %u", __FUNCTION__, entry.type, entry.count); return ERROR; } if (data_size != 0) { camera_metadata_data_t *data = (camera_metadata_data_t*) (get_data(metadata) + entry.data.offset); if ((uintptr_t)data != ALIGN_TO(data, DATA_ALIGNMENT)) { ALOGE("%s: Entry index %zu had bad data alignment (address %p)," " expected align %zu, (tag name %s, data size %zu)", __FUNCTION__, i, data, DATA_ALIGNMENT, get_camera_metadata_tag_name(entry.tag) ?: "unknown", data_size); return ERROR; } size_t data_entry_end = entry.data.offset + data_size; if (data_entry_end < entry.data.offset || // overflow check data_entry_end > metadata->data_capacity) { ALOGE("%s: Entry index %zu data ends (%zu) beyond the capacity " "%" PRIu32, __FUNCTION__, i, data_entry_end, metadata->data_capacity); return ERROR; } } else if (entry.count == 0) { if (entry.data.offset != 0) { ALOGE("%s: Entry index %zu had 0 items, but offset was non-0 " "(%" PRIu32 "), tag name: %s", __FUNCTION__, i, entry.data.offset, get_camera_metadata_tag_name(entry.tag) ?: "unknown"); return ERROR; } } // else data stored inline, so we look at value which can be anything. } return OK; } Commit Message: Camera metadata: Check for inconsistent data count Resolve merge conflict for nyc-release Also check for overflow of data/entry count on append. Bug: 30591838 Change-Id: Ibf4c3c6e236cdb28234f3125055d95ef0a2416a2 CWE ID: CWE-264
int validate_camera_metadata_structure(const camera_metadata_t *metadata, const size_t *expected_size) { if (metadata == NULL) { ALOGE("%s: metadata is null!", __FUNCTION__); return ERROR; } { static const struct { const char *name; size_t alignment; } alignments[] = { { .name = "camera_metadata", .alignment = METADATA_ALIGNMENT }, { .name = "camera_metadata_buffer_entry", .alignment = ENTRY_ALIGNMENT }, { .name = "camera_metadata_data", .alignment = DATA_ALIGNMENT }, }; for (size_t i = 0; i < sizeof(alignments)/sizeof(alignments[0]); ++i) { uintptr_t aligned_ptr = ALIGN_TO(metadata, alignments[i].alignment); if ((uintptr_t)metadata != aligned_ptr) { ALOGE("%s: Metadata pointer is not aligned (actual %p, " "expected %p) to type %s", __FUNCTION__, metadata, (void*)aligned_ptr, alignments[i].name); return ERROR; } } } /** * Check that the metadata contents are correct */ if (expected_size != NULL && metadata->size > *expected_size) { ALOGE("%s: Metadata size (%" PRIu32 ") should be <= expected size (%zu)", __FUNCTION__, metadata->size, *expected_size); return ERROR; } if (metadata->entry_count > metadata->entry_capacity) { ALOGE("%s: Entry count (%" PRIu32 ") should be <= entry capacity " "(%" PRIu32 ")", __FUNCTION__, metadata->entry_count, metadata->entry_capacity); return ERROR; } if (metadata->data_count > metadata->data_capacity) { ALOGE("%s: Data count (%" PRIu32 ") should be <= data capacity " "(%" PRIu32 ")", __FUNCTION__, metadata->data_count, metadata->data_capacity); android_errorWriteLog(SN_EVENT_LOG_ID, "30591838"); return ERROR; } const metadata_uptrdiff_t entries_end = metadata->entries_start + metadata->entry_capacity; if (entries_end < metadata->entries_start || // overflow check entries_end > metadata->data_start) { ALOGE("%s: Entry start + capacity (%" PRIu32 ") should be <= data start " "(%" PRIu32 ")", __FUNCTION__, (metadata->entries_start + metadata->entry_capacity), metadata->data_start); return ERROR; } const metadata_uptrdiff_t data_end = metadata->data_start + metadata->data_capacity; if (data_end < metadata->data_start || // overflow check data_end > metadata->size) { ALOGE("%s: Data start + capacity (%" PRIu32 ") should be <= total size " "(%" PRIu32 ")", __FUNCTION__, (metadata->data_start + metadata->data_capacity), metadata->size); return ERROR; } const metadata_size_t entry_count = metadata->entry_count; camera_metadata_buffer_entry_t *entries = get_entries(metadata); for (size_t i = 0; i < entry_count; ++i) { if ((uintptr_t)&entries[i] != ALIGN_TO(&entries[i], ENTRY_ALIGNMENT)) { ALOGE("%s: Entry index %zu had bad alignment (address %p)," " expected alignment %zu", __FUNCTION__, i, &entries[i], ENTRY_ALIGNMENT); return ERROR; } camera_metadata_buffer_entry_t entry = entries[i]; if (entry.type >= NUM_TYPES) { ALOGE("%s: Entry index %zu had a bad type %d", __FUNCTION__, i, entry.type); return ERROR; } uint32_t tag_section = entry.tag >> 16; int tag_type = get_camera_metadata_tag_type(entry.tag); if (tag_type != (int)entry.type && tag_section < VENDOR_SECTION) { ALOGE("%s: Entry index %zu had tag type %d, but the type was %d", __FUNCTION__, i, tag_type, entry.type); return ERROR; } size_t data_size; if (validate_and_calculate_camera_metadata_entry_data_size(&data_size, entry.type, entry.count) != OK) { ALOGE("%s: Entry data size is invalid. type: %u count: %u", __FUNCTION__, entry.type, entry.count); return ERROR; } if (data_size != 0) { camera_metadata_data_t *data = (camera_metadata_data_t*) (get_data(metadata) + entry.data.offset); if ((uintptr_t)data != ALIGN_TO(data, DATA_ALIGNMENT)) { ALOGE("%s: Entry index %zu had bad data alignment (address %p)," " expected align %zu, (tag name %s, data size %zu)", __FUNCTION__, i, data, DATA_ALIGNMENT, get_camera_metadata_tag_name(entry.tag) ?: "unknown", data_size); return ERROR; } size_t data_entry_end = entry.data.offset + data_size; if (data_entry_end < entry.data.offset || // overflow check data_entry_end > metadata->data_capacity) { ALOGE("%s: Entry index %zu data ends (%zu) beyond the capacity " "%" PRIu32, __FUNCTION__, i, data_entry_end, metadata->data_capacity); return ERROR; } } else if (entry.count == 0) { if (entry.data.offset != 0) { ALOGE("%s: Entry index %zu had 0 items, but offset was non-0 " "(%" PRIu32 "), tag name: %s", __FUNCTION__, i, entry.data.offset, get_camera_metadata_tag_name(entry.tag) ?: "unknown"); return ERROR; } } // else data stored inline, so we look at value which can be anything. } return OK; }
173,397
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 __u8 *lg_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { struct lg_drv_data *drv_data = hid_get_drvdata(hdev); struct usb_device_descriptor *udesc; __u16 bcdDevice, rev_maj, rev_min; if ((drv_data->quirks & LG_RDESC) && *rsize >= 90 && rdesc[83] == 0x26 && rdesc[84] == 0x8c && rdesc[85] == 0x02) { hid_info(hdev, "fixing up Logitech keyboard report descriptor\n"); rdesc[84] = rdesc[89] = 0x4d; rdesc[85] = rdesc[90] = 0x10; } if ((drv_data->quirks & LG_RDESC_REL_ABS) && *rsize >= 50 && rdesc[32] == 0x81 && rdesc[33] == 0x06 && rdesc[49] == 0x81 && rdesc[50] == 0x06) { hid_info(hdev, "fixing up rel/abs in Logitech report descriptor\n"); rdesc[33] = rdesc[50] = 0x02; } switch (hdev->product) { /* Several wheels report as this id when operating in emulation mode. */ case USB_DEVICE_ID_LOGITECH_WHEEL: udesc = &(hid_to_usb_dev(hdev)->descriptor); if (!udesc) { hid_err(hdev, "NULL USB device descriptor\n"); break; } bcdDevice = le16_to_cpu(udesc->bcdDevice); rev_maj = bcdDevice >> 8; rev_min = bcdDevice & 0xff; /* Update the report descriptor for only the Driving Force wheel */ if (rev_maj == 1 && rev_min == 2 && *rsize == DF_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Driving Force report descriptor\n"); rdesc = df_rdesc_fixed; *rsize = sizeof(df_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_MOMO_WHEEL: if (*rsize == MOMO_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Momo Force (Red) report descriptor\n"); rdesc = momo_rdesc_fixed; *rsize = sizeof(momo_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_MOMO_WHEEL2: if (*rsize == MOMO2_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Momo Racing Force (Black) report descriptor\n"); rdesc = momo2_rdesc_fixed; *rsize = sizeof(momo2_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_VIBRATION_WHEEL: if (*rsize == FV_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Formula Vibration report descriptor\n"); rdesc = fv_rdesc_fixed; *rsize = sizeof(fv_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_DFP_WHEEL: if (*rsize == DFP_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Driving Force Pro report descriptor\n"); rdesc = dfp_rdesc_fixed; *rsize = sizeof(dfp_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_WII_WHEEL: if (*rsize >= 101 && rdesc[41] == 0x95 && rdesc[42] == 0x0B && rdesc[47] == 0x05 && rdesc[48] == 0x09) { hid_info(hdev, "fixing up Logitech Speed Force Wireless report descriptor\n"); rdesc[41] = 0x05; rdesc[42] = 0x09; rdesc[47] = 0x95; rdesc[48] = 0x0B; } break; } return rdesc; } Commit Message: HID: fix a couple of off-by-ones There are a few very theoretical off-by-one bugs in report descriptor size checking when performing a pre-parsing fixup. Fix those. Cc: [email protected] Reported-by: Ben Hawkes <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119
static __u8 *lg_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { struct lg_drv_data *drv_data = hid_get_drvdata(hdev); struct usb_device_descriptor *udesc; __u16 bcdDevice, rev_maj, rev_min; if ((drv_data->quirks & LG_RDESC) && *rsize >= 91 && rdesc[83] == 0x26 && rdesc[84] == 0x8c && rdesc[85] == 0x02) { hid_info(hdev, "fixing up Logitech keyboard report descriptor\n"); rdesc[84] = rdesc[89] = 0x4d; rdesc[85] = rdesc[90] = 0x10; } if ((drv_data->quirks & LG_RDESC_REL_ABS) && *rsize >= 51 && rdesc[32] == 0x81 && rdesc[33] == 0x06 && rdesc[49] == 0x81 && rdesc[50] == 0x06) { hid_info(hdev, "fixing up rel/abs in Logitech report descriptor\n"); rdesc[33] = rdesc[50] = 0x02; } switch (hdev->product) { /* Several wheels report as this id when operating in emulation mode. */ case USB_DEVICE_ID_LOGITECH_WHEEL: udesc = &(hid_to_usb_dev(hdev)->descriptor); if (!udesc) { hid_err(hdev, "NULL USB device descriptor\n"); break; } bcdDevice = le16_to_cpu(udesc->bcdDevice); rev_maj = bcdDevice >> 8; rev_min = bcdDevice & 0xff; /* Update the report descriptor for only the Driving Force wheel */ if (rev_maj == 1 && rev_min == 2 && *rsize == DF_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Driving Force report descriptor\n"); rdesc = df_rdesc_fixed; *rsize = sizeof(df_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_MOMO_WHEEL: if (*rsize == MOMO_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Momo Force (Red) report descriptor\n"); rdesc = momo_rdesc_fixed; *rsize = sizeof(momo_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_MOMO_WHEEL2: if (*rsize == MOMO2_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Momo Racing Force (Black) report descriptor\n"); rdesc = momo2_rdesc_fixed; *rsize = sizeof(momo2_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_VIBRATION_WHEEL: if (*rsize == FV_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Formula Vibration report descriptor\n"); rdesc = fv_rdesc_fixed; *rsize = sizeof(fv_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_DFP_WHEEL: if (*rsize == DFP_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Driving Force Pro report descriptor\n"); rdesc = dfp_rdesc_fixed; *rsize = sizeof(dfp_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_WII_WHEEL: if (*rsize >= 101 && rdesc[41] == 0x95 && rdesc[42] == 0x0B && rdesc[47] == 0x05 && rdesc[48] == 0x09) { hid_info(hdev, "fixing up Logitech Speed Force Wireless report descriptor\n"); rdesc[41] = 0x05; rdesc[42] = 0x09; rdesc[47] = 0x95; rdesc[48] = 0x0B; } break; } return rdesc; }
166,372
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Cues::Find(long long time_ns, const Track* pTrack, const CuePoint*& pCP, const CuePoint::TrackPosition*& pTP) const { assert(time_ns >= 0); assert(pTrack); #if 0 LoadCuePoint(); //establish invariant assert(m_cue_points); assert(m_count > 0); CuePoint** const ii = m_cue_points; CuePoint** i = ii; CuePoint** const jj = ii + m_count + m_preload_count; CuePoint** j = jj; pCP = *i; assert(pCP); if (time_ns <= pCP->GetTime(m_pSegment)) { pTP = pCP->Find(pTrack); return (pTP != NULL); } IMkvReader* const pReader = m_pSegment->m_pReader; while (i < j) { CuePoint** const k = i + (j - i) / 2; assert(k < jj); CuePoint* const pCP = *k; assert(pCP); pCP->Load(pReader); const long long t = pCP->GetTime(m_pSegment); if (t <= time_ns) i = k + 1; else j = k; assert(i <= j); } assert(i == j); assert(i <= jj); assert(i > ii); pCP = *--i; assert(pCP); assert(pCP->GetTime(m_pSegment) <= time_ns); #else if (m_cue_points == NULL) return false; if (m_count == 0) return false; CuePoint** const ii = m_cue_points; CuePoint** i = ii; CuePoint** const jj = ii + m_count; CuePoint** j = jj; pCP = *i; assert(pCP); if (time_ns <= pCP->GetTime(m_pSegment)) { pTP = pCP->Find(pTrack); return (pTP != NULL); } while (i < j) { CuePoint** const k = i + (j - i) / 2; assert(k < jj); CuePoint* const pCP = *k; assert(pCP); const long long t = pCP->GetTime(m_pSegment); if (t <= time_ns) i = k + 1; else j = k; assert(i <= j); } assert(i == j); assert(i <= jj); assert(i > ii); pCP = *--i; assert(pCP); assert(pCP->GetTime(m_pSegment) <= time_ns); #endif pTP = pCP->Find(pTrack); return (pTP != NULL); } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
bool Cues::Find(long long time_ns, const Track* pTrack, const CuePoint*& pCP, const CuePoint::TrackPosition*& pTP) const { if (time_ns < 0 || pTrack == NULL || m_cue_points == NULL || m_count == 0) return false; CuePoint** const ii = m_cue_points; CuePoint** i = ii; CuePoint** const jj = ii + m_count; CuePoint** j = jj; pCP = *i; if (pCP == NULL) return false; if (time_ns <= pCP->GetTime(m_pSegment)) { pTP = pCP->Find(pTrack); return (pTP != NULL); } while (i < j) { CuePoint** const k = i + (j - i) / 2; if (k >= jj) return false; CuePoint* const pCP = *k; if (pCP == NULL) return false; const long long t = pCP->GetTime(m_pSegment); if (t <= time_ns) i = k + 1; else j = k; if (i > j) return false; } if (i != j || i > jj || i <= ii) return false; pCP = *--i; if (pCP == NULL || pCP->GetTime(m_pSegment) > time_ns) return false; pTP = pCP->Find(pTrack); return (pTP != NULL); }
173,811
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 getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) { return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; } Commit Message: Reject fonts with invalid ranges in cmap A corrupt or malicious font may have a negative size in its cmap range, which in turn could lead to memory corruption. This patch detects the case and rejects the font, and also includes an assertion in the sparse bit set implementation if we missed any such case. External issue: https://code.google.com/p/android/issues/detail?id=192618 Bug: 26413177 Change-Id: Icc0c80e4ef389abba0964495b89aa0fae3e9f4b2 CWE ID: CWE-20
static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) { return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); if (end < start) { // invalid group range: size must be positive return false; } addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; }
174,234
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: jas_matrix_t *jas_seq2d_input(FILE *in) { jas_matrix_t *matrix; int i; int j; long x; int numrows; int numcols; int xoff; int yoff; if (fscanf(in, "%d %d", &xoff, &yoff) != 2) return 0; if (fscanf(in, "%d %d", &numcols, &numrows) != 2) return 0; if (!(matrix = jas_seq2d_create(xoff, yoff, xoff + numcols, yoff + numrows))) return 0; if (jas_matrix_numrows(matrix) != numrows || jas_matrix_numcols(matrix) != numcols) { abort(); } /* Get matrix data. */ for (i = 0; i < jas_matrix_numrows(matrix); i++) { for (j = 0; j < jas_matrix_numcols(matrix); j++) { if (fscanf(in, "%ld", &x) != 1) { jas_matrix_destroy(matrix); return 0; } jas_matrix_set(matrix, i, j, JAS_CAST(jas_seqent_t, x)); } } return matrix; } 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
jas_matrix_t *jas_seq2d_input(FILE *in) { jas_matrix_t *matrix; jas_matind_t i; jas_matind_t j; long x; jas_matind_t numrows; jas_matind_t numcols; jas_matind_t xoff; jas_matind_t yoff; long tmp_xoff; long tmp_yoff; long tmp_numrows; long tmp_numcols; if (fscanf(in, "%ld %ld", &tmp_xoff, &tmp_yoff) != 2) { return 0; } xoff = tmp_xoff; yoff = tmp_yoff; if (fscanf(in, "%ld %ld", &tmp_numcols, &tmp_numrows) != 2) { return 0; } numrows = tmp_numrows; numcols = tmp_numcols; if (!(matrix = jas_seq2d_create(xoff, yoff, xoff + numcols, yoff + numrows))) { return 0; } if (jas_matrix_numrows(matrix) != numrows || jas_matrix_numcols(matrix) != numcols) { abort(); } /* Get matrix data. */ for (i = 0; i < jas_matrix_numrows(matrix); i++) { for (j = 0; j < jas_matrix_numcols(matrix); j++) { if (fscanf(in, "%ld", &x) != 1) { jas_matrix_destroy(matrix); return 0; } jas_matrix_set(matrix, i, j, JAS_CAST(jas_seqent_t, x)); } } return matrix; }
168,710
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: PHP_FUNCTION(mcrypt_enc_get_supported_key_sizes) { int i, count = 0; int *key_sizes; MCRYPT_GET_TD_ARG array_init(return_value); key_sizes = mcrypt_enc_get_supported_key_sizes(pm->td, &count); for (i = 0; i < count; i++) { add_index_long(return_value, i, key_sizes[i]); } mcrypt_free(key_sizes); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_enc_get_supported_key_sizes) { int i, count = 0; int *key_sizes; MCRYPT_GET_TD_ARG array_init(return_value); key_sizes = mcrypt_enc_get_supported_key_sizes(pm->td, &count); for (i = 0; i < count; i++) { add_index_long(return_value, i, key_sizes[i]); } mcrypt_free(key_sizes); }
167,093
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 SoundPool::load(const char* path, int priority __unused) { ALOGV("load: path=%s, priority=%d", path, priority); Mutex::Autolock lock(&mLock); sp<Sample> sample = new Sample(++mNextSampleID, path); mSamples.add(sample->sampleID(), sample); doLoad(sample); return sample->sampleID(); } Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread Sample decoding still occurs in SoundPoolThread without holding the SoundPool lock. Bug: 25781119 Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8 CWE ID: CWE-264
int SoundPool::load(const char* path, int priority __unused) { ALOGV("load: path=%s, priority=%d", path, priority); int sampleID; { Mutex::Autolock lock(&mLock); sampleID = ++mNextSampleID; sp<Sample> sample = new Sample(sampleID, path); mSamples.add(sampleID, sample); sample->startLoad(); } // mDecodeThread->loadSample() must be called outside of mLock. // mDecodeThread->loadSample() may block on mDecodeThread message queue space; // the message queue emptying may block on SoundPool::findSample(). // // It theoretically possible that sample loads might decode out-of-order. mDecodeThread->loadSample(sampleID); return sampleID; }
173,961
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 AppLauncherHandler::FillAppDictionary(base::DictionaryValue* dictionary) { base::AutoReset<bool> auto_reset(&ignore_changes_, true); base::ListValue* list = new base::ListValue(); Profile* profile = Profile::FromWebUI(web_ui()); PrefService* prefs = profile->GetPrefs(); for (std::set<std::string>::iterator it = visible_apps_.begin(); it != visible_apps_.end(); ++it) { const Extension* extension = extension_service_->GetInstalledExtension(*it); if (extension && extensions::ui_util::ShouldDisplayInNewTabPage( extension, profile)) { base::DictionaryValue* app_info = GetAppInfo(extension); list->Append(app_info); } } dictionary->Set("apps", list); #if defined(OS_MACOSX) dictionary->SetBoolean("disableAppWindowLaunch", true); dictionary->SetBoolean("disableCreateAppShortcut", true); #endif #if defined(OS_CHROMEOS) dictionary->SetBoolean("disableCreateAppShortcut", true); #endif const base::ListValue* app_page_names = prefs->GetList(prefs::kNtpAppPageNames); if (!app_page_names || !app_page_names->GetSize()) { ListPrefUpdate update(prefs, prefs::kNtpAppPageNames); base::ListValue* list = update.Get(); list->Set(0, new base::StringValue( l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME))); dictionary->Set("appPageNames", static_cast<base::ListValue*>(list->DeepCopy())); } else { dictionary->Set("appPageNames", static_cast<base::ListValue*>(app_page_names->DeepCopy())); } } Commit Message: Remove --disable-app-shims. App shims have been enabled by default for 3 milestones (since r242711). BUG=350161 Review URL: https://codereview.chromium.org/298953002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void AppLauncherHandler::FillAppDictionary(base::DictionaryValue* dictionary) { base::AutoReset<bool> auto_reset(&ignore_changes_, true); base::ListValue* list = new base::ListValue(); Profile* profile = Profile::FromWebUI(web_ui()); PrefService* prefs = profile->GetPrefs(); for (std::set<std::string>::iterator it = visible_apps_.begin(); it != visible_apps_.end(); ++it) { const Extension* extension = extension_service_->GetInstalledExtension(*it); if (extension && extensions::ui_util::ShouldDisplayInNewTabPage( extension, profile)) { base::DictionaryValue* app_info = GetAppInfo(extension); list->Append(app_info); } } dictionary->Set("apps", list); const base::ListValue* app_page_names = prefs->GetList(prefs::kNtpAppPageNames); if (!app_page_names || !app_page_names->GetSize()) { ListPrefUpdate update(prefs, prefs::kNtpAppPageNames); base::ListValue* list = update.Get(); list->Set(0, new base::StringValue( l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME))); dictionary->Set("appPageNames", static_cast<base::ListValue*>(list->DeepCopy())); } else { dictionary->Set("appPageNames", static_cast<base::ListValue*>(app_page_names->DeepCopy())); } }
171,147
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 StopInputMethodProcess() { if (!IBusConnectionsAreAlive()) { LOG(ERROR) << "StopInputMethodProcess: IBus connection is not alive"; return false; } ibus_bus_exit_async(ibus_, FALSE /* do not restart */, -1 /* timeout */, NULL /* cancellable */, NULL /* callback */, NULL /* user_data */); if (ibus_config_) { g_object_unref(ibus_config_); ibus_config_ = NULL; } return true; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool StopInputMethodProcess() { // IBusController override. virtual bool StopInputMethodProcess() { if (!IBusConnectionsAreAlive()) { LOG(ERROR) << "StopInputMethodProcess: IBus connection is not alive"; return false; } ibus_bus_exit_async(ibus_, FALSE /* do not restart */, -1 /* timeout */, NULL /* cancellable */, NULL /* callback */, NULL /* user_data */); if (ibus_config_) { g_object_unref(ibus_config_); ibus_config_ = NULL; } return true; }
170,549
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: GahpServer::Reaper(Service *,int pid,int status) { /* This should be much better.... for now, if our Gahp Server goes away for any reason, we EXCEPT. */ GahpServer *dead_server = NULL; GahpServer *next_server = NULL; GahpServersById.startIterations(); while ( GahpServersById.iterate( next_server ) != 0 ) { if ( pid == next_server->m_gahp_pid ) { dead_server = next_server; break; } } std::string buf; sprintf( buf, "Gahp Server (pid=%d) ", pid ); if( WIFSIGNALED(status) ) { sprintf_cat( buf, "died due to %s", daemonCore->GetExceptionString(status) ); } else { sprintf_cat( buf, "exited with status %d", WEXITSTATUS(status) ); } if ( dead_server ) { sprintf_cat( buf, " unexpectedly" ); EXCEPT( buf.c_str() ); } else { sprintf_cat( buf, "\n" ); dprintf( D_ALWAYS, buf.c_str() ); } } Commit Message: CWE ID: CWE-134
GahpServer::Reaper(Service *,int pid,int status) { /* This should be much better.... for now, if our Gahp Server goes away for any reason, we EXCEPT. */ GahpServer *dead_server = NULL; GahpServer *next_server = NULL; GahpServersById.startIterations(); while ( GahpServersById.iterate( next_server ) != 0 ) { if ( pid == next_server->m_gahp_pid ) { dead_server = next_server; break; } } std::string buf; sprintf( buf, "Gahp Server (pid=%d) ", pid ); if( WIFSIGNALED(status) ) { sprintf_cat( buf, "died due to %s", daemonCore->GetExceptionString(status) ); } else { sprintf_cat( buf, "exited with status %d", WEXITSTATUS(status) ); } if ( dead_server ) { sprintf_cat( buf, " unexpectedly" ); EXCEPT( "%s", buf.c_str() ); } else { sprintf_cat( buf, "\n" ); dprintf( D_ALWAYS, "%s", buf.c_str() ); } }
165,373
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void svc_rdma_xdr_encode_reply_array(struct rpcrdma_write_array *ary, int chunks) { ary->wc_discrim = xdr_one; ary->wc_nchunks = cpu_to_be32(chunks); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
void svc_rdma_xdr_encode_reply_array(struct rpcrdma_write_array *ary,
168,161
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 kvm_guest_time_update(struct kvm_vcpu *v) { unsigned long flags, this_tsc_khz; struct kvm_vcpu_arch *vcpu = &v->arch; struct kvm_arch *ka = &v->kvm->arch; void *shared_kaddr; s64 kernel_ns, max_kernel_ns; u64 tsc_timestamp, host_tsc; struct pvclock_vcpu_time_info *guest_hv_clock; u8 pvclock_flags; bool use_master_clock; kernel_ns = 0; host_tsc = 0; /* * If the host uses TSC clock, then passthrough TSC as stable * to the guest. */ spin_lock(&ka->pvclock_gtod_sync_lock); use_master_clock = ka->use_master_clock; if (use_master_clock) { host_tsc = ka->master_cycle_now; kernel_ns = ka->master_kernel_ns; } spin_unlock(&ka->pvclock_gtod_sync_lock); /* Keep irq disabled to prevent changes to the clock */ local_irq_save(flags); this_tsc_khz = __get_cpu_var(cpu_tsc_khz); if (unlikely(this_tsc_khz == 0)) { local_irq_restore(flags); kvm_make_request(KVM_REQ_CLOCK_UPDATE, v); return 1; } if (!use_master_clock) { host_tsc = native_read_tsc(); kernel_ns = get_kernel_ns(); } tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc); /* * We may have to catch up the TSC to match elapsed wall clock * time for two reasons, even if kvmclock is used. * 1) CPU could have been running below the maximum TSC rate * 2) Broken TSC compensation resets the base at each VCPU * entry to avoid unknown leaps of TSC even when running * again on the same CPU. This may cause apparent elapsed * time to disappear, and the guest to stand still or run * very slowly. */ if (vcpu->tsc_catchup) { u64 tsc = compute_guest_tsc(v, kernel_ns); if (tsc > tsc_timestamp) { adjust_tsc_offset_guest(v, tsc - tsc_timestamp); tsc_timestamp = tsc; } } local_irq_restore(flags); if (!vcpu->time_page) return 0; /* * Time as measured by the TSC may go backwards when resetting the base * tsc_timestamp. The reason for this is that the TSC resolution is * higher than the resolution of the other clock scales. Thus, many * possible measurments of the TSC correspond to one measurement of any * other clock, and so a spread of values is possible. This is not a * problem for the computation of the nanosecond clock; with TSC rates * around 1GHZ, there can only be a few cycles which correspond to one * nanosecond value, and any path through this code will inevitably * take longer than that. However, with the kernel_ns value itself, * the precision may be much lower, down to HZ granularity. If the * first sampling of TSC against kernel_ns ends in the low part of the * range, and the second in the high end of the range, we can get: * * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new * * As the sampling errors potentially range in the thousands of cycles, * it is possible such a time value has already been observed by the * guest. To protect against this, we must compute the system time as * observed by the guest and ensure the new system time is greater. */ max_kernel_ns = 0; if (vcpu->hv_clock.tsc_timestamp) { max_kernel_ns = vcpu->last_guest_tsc - vcpu->hv_clock.tsc_timestamp; max_kernel_ns = pvclock_scale_delta(max_kernel_ns, vcpu->hv_clock.tsc_to_system_mul, vcpu->hv_clock.tsc_shift); max_kernel_ns += vcpu->last_kernel_ns; } if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) { kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz, &vcpu->hv_clock.tsc_shift, &vcpu->hv_clock.tsc_to_system_mul); vcpu->hw_tsc_khz = this_tsc_khz; } /* with a master <monotonic time, tsc value> tuple, * pvclock clock reads always increase at the (scaled) rate * of guest TSC - no need to deal with sampling errors. */ if (!use_master_clock) { if (max_kernel_ns > kernel_ns) kernel_ns = max_kernel_ns; } /* With all the info we got, fill in the values */ vcpu->hv_clock.tsc_timestamp = tsc_timestamp; vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset; vcpu->last_kernel_ns = kernel_ns; vcpu->last_guest_tsc = tsc_timestamp; /* * The interface expects us to write an even number signaling that the * update is finished. Since the guest won't see the intermediate * state, we just increase by 2 at the end. */ vcpu->hv_clock.version += 2; shared_kaddr = kmap_atomic(vcpu->time_page); guest_hv_clock = shared_kaddr + vcpu->time_offset; /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */ pvclock_flags = (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED); if (vcpu->pvclock_set_guest_stopped_request) { pvclock_flags |= PVCLOCK_GUEST_STOPPED; vcpu->pvclock_set_guest_stopped_request = false; } /* If the host uses TSC clocksource, then it is stable */ if (use_master_clock) pvclock_flags |= PVCLOCK_TSC_STABLE_BIT; vcpu->hv_clock.flags = pvclock_flags; memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock, sizeof(vcpu->hv_clock)); kunmap_atomic(shared_kaddr); mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT); return 0; } Commit Message: KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797) There is a potential use after free issue with the handling of MSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable memory such as frame buffers then KVM might continue to write to that address even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins the page in memory so it's unlikely to cause an issue, but if the user space component re-purposes the memory previously used for the guest, then the guest will be able to corrupt that memory. Tested: Tested against kvmclock unit test Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> CWE ID: CWE-399
static int kvm_guest_time_update(struct kvm_vcpu *v) { unsigned long flags, this_tsc_khz; struct kvm_vcpu_arch *vcpu = &v->arch; struct kvm_arch *ka = &v->kvm->arch; s64 kernel_ns, max_kernel_ns; u64 tsc_timestamp, host_tsc; struct pvclock_vcpu_time_info guest_hv_clock; u8 pvclock_flags; bool use_master_clock; kernel_ns = 0; host_tsc = 0; /* * If the host uses TSC clock, then passthrough TSC as stable * to the guest. */ spin_lock(&ka->pvclock_gtod_sync_lock); use_master_clock = ka->use_master_clock; if (use_master_clock) { host_tsc = ka->master_cycle_now; kernel_ns = ka->master_kernel_ns; } spin_unlock(&ka->pvclock_gtod_sync_lock); /* Keep irq disabled to prevent changes to the clock */ local_irq_save(flags); this_tsc_khz = __get_cpu_var(cpu_tsc_khz); if (unlikely(this_tsc_khz == 0)) { local_irq_restore(flags); kvm_make_request(KVM_REQ_CLOCK_UPDATE, v); return 1; } if (!use_master_clock) { host_tsc = native_read_tsc(); kernel_ns = get_kernel_ns(); } tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc); /* * We may have to catch up the TSC to match elapsed wall clock * time for two reasons, even if kvmclock is used. * 1) CPU could have been running below the maximum TSC rate * 2) Broken TSC compensation resets the base at each VCPU * entry to avoid unknown leaps of TSC even when running * again on the same CPU. This may cause apparent elapsed * time to disappear, and the guest to stand still or run * very slowly. */ if (vcpu->tsc_catchup) { u64 tsc = compute_guest_tsc(v, kernel_ns); if (tsc > tsc_timestamp) { adjust_tsc_offset_guest(v, tsc - tsc_timestamp); tsc_timestamp = tsc; } } local_irq_restore(flags); if (!vcpu->pv_time_enabled) return 0; /* * Time as measured by the TSC may go backwards when resetting the base * tsc_timestamp. The reason for this is that the TSC resolution is * higher than the resolution of the other clock scales. Thus, many * possible measurments of the TSC correspond to one measurement of any * other clock, and so a spread of values is possible. This is not a * problem for the computation of the nanosecond clock; with TSC rates * around 1GHZ, there can only be a few cycles which correspond to one * nanosecond value, and any path through this code will inevitably * take longer than that. However, with the kernel_ns value itself, * the precision may be much lower, down to HZ granularity. If the * first sampling of TSC against kernel_ns ends in the low part of the * range, and the second in the high end of the range, we can get: * * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new * * As the sampling errors potentially range in the thousands of cycles, * it is possible such a time value has already been observed by the * guest. To protect against this, we must compute the system time as * observed by the guest and ensure the new system time is greater. */ max_kernel_ns = 0; if (vcpu->hv_clock.tsc_timestamp) { max_kernel_ns = vcpu->last_guest_tsc - vcpu->hv_clock.tsc_timestamp; max_kernel_ns = pvclock_scale_delta(max_kernel_ns, vcpu->hv_clock.tsc_to_system_mul, vcpu->hv_clock.tsc_shift); max_kernel_ns += vcpu->last_kernel_ns; } if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) { kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz, &vcpu->hv_clock.tsc_shift, &vcpu->hv_clock.tsc_to_system_mul); vcpu->hw_tsc_khz = this_tsc_khz; } /* with a master <monotonic time, tsc value> tuple, * pvclock clock reads always increase at the (scaled) rate * of guest TSC - no need to deal with sampling errors. */ if (!use_master_clock) { if (max_kernel_ns > kernel_ns) kernel_ns = max_kernel_ns; } /* With all the info we got, fill in the values */ vcpu->hv_clock.tsc_timestamp = tsc_timestamp; vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset; vcpu->last_kernel_ns = kernel_ns; vcpu->last_guest_tsc = tsc_timestamp; /* * The interface expects us to write an even number signaling that the * update is finished. Since the guest won't see the intermediate * state, we just increase by 2 at the end. */ vcpu->hv_clock.version += 2; if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time, &guest_hv_clock, sizeof(guest_hv_clock)))) return 0; /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */ pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED); if (vcpu->pvclock_set_guest_stopped_request) { pvclock_flags |= PVCLOCK_GUEST_STOPPED; vcpu->pvclock_set_guest_stopped_request = false; } /* If the host uses TSC clocksource, then it is stable */ if (use_master_clock) pvclock_flags |= PVCLOCK_TSC_STABLE_BIT; vcpu->hv_clock.flags = pvclock_flags; kvm_write_guest_cached(v->kvm, &vcpu->pv_time, &vcpu->hv_clock, sizeof(vcpu->hv_clock)); return 0; }
166,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: Load_SBit_Png( FT_GlyphSlot slot, FT_Int x_offset, FT_Int y_offset, FT_Int pix_bits, TT_SBit_Metrics metrics, FT_Memory memory, FT_Byte* data, FT_UInt png_len, FT_Bool populate_map_and_metrics ) { FT_Bitmap *map = &slot->bitmap; FT_Error error = FT_Err_Ok; FT_StreamRec stream; png_structp png; png_infop info; png_uint_32 imgWidth, imgHeight; int bitdepth, color_type, interlace; FT_Int i; png_byte* *rows = NULL; /* pacify compiler */ if ( x_offset < 0 || y_offset < 0 ) { error = FT_THROW( Invalid_Argument ); goto Exit; } if ( !populate_map_and_metrics && ( x_offset + metrics->width > map->width || y_offset + metrics->height > map->rows || pix_bits != 32 || map->pixel_mode != FT_PIXEL_MODE_BGRA ) ) { error = FT_THROW( Invalid_Argument ); goto Exit; } FT_Stream_OpenMemory( &stream, data, png_len ); png = png_create_read_struct( PNG_LIBPNG_VER_STRING, &error, error_callback, warning_callback ); if ( !png ) { error = FT_THROW( Out_Of_Memory ); goto Exit; } info = png_create_info_struct( png ); if ( !info ) { error = FT_THROW( Out_Of_Memory ); png_destroy_read_struct( &png, NULL, NULL ); goto Exit; } if ( ft_setjmp( png_jmpbuf( png ) ) ) { error = FT_THROW( Invalid_File_Format ); goto DestroyExit; } png_set_read_fn( png, &stream, read_data_from_FT_Stream ); png_read_info( png, info ); png_get_IHDR( png, info, &imgWidth, &imgHeight, &bitdepth, &color_type, &interlace, NULL, NULL ); if ( error || ( !populate_map_and_metrics && ( (FT_Int)imgWidth != metrics->width || (FT_Int)imgHeight != metrics->height ) ) ) goto DestroyExit; if ( populate_map_and_metrics ) { FT_Long size; metrics->width = (FT_Int)imgWidth; metrics->height = (FT_Int)imgHeight; map->width = metrics->width; map->rows = metrics->height; map->pixel_mode = FT_PIXEL_MODE_BGRA; map->pitch = map->width * 4; map->num_grays = 256; /* reject too large bitmaps similarly to the rasterizer */ if ( map->rows > 0x7FFF || map->width > 0x7FFF ) { error = FT_THROW( Array_Too_Large ); goto DestroyExit; } size = map->rows * map->pitch; error = ft_glyphslot_alloc_bitmap( slot, size ); if ( error ) goto DestroyExit; } /* convert palette/gray image to rgb */ if ( color_type == PNG_COLOR_TYPE_PALETTE ) png_set_palette_to_rgb( png ); /* expand gray bit depth if needed */ if ( color_type == PNG_COLOR_TYPE_GRAY ) { #if PNG_LIBPNG_VER >= 10209 png_set_expand_gray_1_2_4_to_8( png ); #else png_set_gray_1_2_4_to_8( png ); #endif } /* transform transparency to alpha */ if ( png_get_valid(png, info, PNG_INFO_tRNS ) ) png_set_tRNS_to_alpha( png ); if ( bitdepth == 16 ) png_set_strip_16( png ); if ( bitdepth < 8 ) png_set_packing( png ); /* convert grayscale to RGB */ if ( color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA ) png_set_gray_to_rgb( png ); if ( interlace != PNG_INTERLACE_NONE ) png_set_interlace_handling( png ); png_set_filler( png, 0xFF, PNG_FILLER_AFTER ); /* recheck header after setting EXPAND options */ png_read_update_info(png, info ); png_get_IHDR( png, info, &imgWidth, &imgHeight, &bitdepth, &color_type, &interlace, NULL, NULL ); if ( bitdepth != 8 || !( color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA ) ) { error = FT_THROW( Invalid_File_Format ); goto DestroyExit; } switch ( color_type ) { default: /* Shouldn't happen, but fall through. */ case PNG_COLOR_TYPE_RGB_ALPHA: png_set_read_user_transform_fn( png, premultiply_data ); break; case PNG_COLOR_TYPE_RGB: /* Humm, this smells. Carry on though. */ png_set_read_user_transform_fn( png, convert_bytes_to_data ); break; } if ( FT_NEW_ARRAY( rows, imgHeight ) ) { error = FT_THROW( Out_Of_Memory ); goto DestroyExit; } for ( i = 0; i < (FT_Int)imgHeight; i++ ) rows[i] = map->buffer + ( y_offset + i ) * map->pitch + x_offset * 4; png_read_image( png, rows ); FT_FREE( rows ); png_read_end( png, info ); DestroyExit: png_destroy_read_struct( &png, &info, NULL ); FT_Stream_Close( &stream ); Exit: return error; } Commit Message: CWE ID: CWE-119
Load_SBit_Png( FT_GlyphSlot slot, FT_Int x_offset, FT_Int y_offset, FT_Int pix_bits, TT_SBit_Metrics metrics, FT_Memory memory, FT_Byte* data, FT_UInt png_len, FT_Bool populate_map_and_metrics ) { FT_Bitmap *map = &slot->bitmap; FT_Error error = FT_Err_Ok; FT_StreamRec stream; png_structp png; png_infop info; png_uint_32 imgWidth, imgHeight; int bitdepth, color_type, interlace; FT_Int i; png_byte* *rows = NULL; /* pacify compiler */ if ( x_offset < 0 || y_offset < 0 ) { error = FT_THROW( Invalid_Argument ); goto Exit; } if ( !populate_map_and_metrics && ( (FT_UInt)x_offset + metrics->width > map->width || (FT_UInt)y_offset + metrics->height > map->rows || pix_bits != 32 || map->pixel_mode != FT_PIXEL_MODE_BGRA ) ) { error = FT_THROW( Invalid_Argument ); goto Exit; } FT_Stream_OpenMemory( &stream, data, png_len ); png = png_create_read_struct( PNG_LIBPNG_VER_STRING, &error, error_callback, warning_callback ); if ( !png ) { error = FT_THROW( Out_Of_Memory ); goto Exit; } info = png_create_info_struct( png ); if ( !info ) { error = FT_THROW( Out_Of_Memory ); png_destroy_read_struct( &png, NULL, NULL ); goto Exit; } if ( ft_setjmp( png_jmpbuf( png ) ) ) { error = FT_THROW( Invalid_File_Format ); goto DestroyExit; } png_set_read_fn( png, &stream, read_data_from_FT_Stream ); png_read_info( png, info ); png_get_IHDR( png, info, &imgWidth, &imgHeight, &bitdepth, &color_type, &interlace, NULL, NULL ); if ( error || ( !populate_map_and_metrics && ( (FT_Int)imgWidth != metrics->width || (FT_Int)imgHeight != metrics->height ) ) ) goto DestroyExit; if ( populate_map_and_metrics ) { FT_Long size; metrics->width = (FT_Int)imgWidth; metrics->height = (FT_Int)imgHeight; map->width = metrics->width; map->rows = metrics->height; map->pixel_mode = FT_PIXEL_MODE_BGRA; map->pitch = map->width * 4; map->num_grays = 256; /* reject too large bitmaps similarly to the rasterizer */ if ( map->rows > 0x7FFF || map->width > 0x7FFF ) { error = FT_THROW( Array_Too_Large ); goto DestroyExit; } size = map->rows * map->pitch; error = ft_glyphslot_alloc_bitmap( slot, size ); if ( error ) goto DestroyExit; } /* convert palette/gray image to rgb */ if ( color_type == PNG_COLOR_TYPE_PALETTE ) png_set_palette_to_rgb( png ); /* expand gray bit depth if needed */ if ( color_type == PNG_COLOR_TYPE_GRAY ) { #if PNG_LIBPNG_VER >= 10209 png_set_expand_gray_1_2_4_to_8( png ); #else png_set_gray_1_2_4_to_8( png ); #endif } /* transform transparency to alpha */ if ( png_get_valid(png, info, PNG_INFO_tRNS ) ) png_set_tRNS_to_alpha( png ); if ( bitdepth == 16 ) png_set_strip_16( png ); if ( bitdepth < 8 ) png_set_packing( png ); /* convert grayscale to RGB */ if ( color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA ) png_set_gray_to_rgb( png ); if ( interlace != PNG_INTERLACE_NONE ) png_set_interlace_handling( png ); png_set_filler( png, 0xFF, PNG_FILLER_AFTER ); /* recheck header after setting EXPAND options */ png_read_update_info(png, info ); png_get_IHDR( png, info, &imgWidth, &imgHeight, &bitdepth, &color_type, &interlace, NULL, NULL ); if ( bitdepth != 8 || !( color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA ) ) { error = FT_THROW( Invalid_File_Format ); goto DestroyExit; } switch ( color_type ) { default: /* Shouldn't happen, but fall through. */ case PNG_COLOR_TYPE_RGB_ALPHA: png_set_read_user_transform_fn( png, premultiply_data ); break; case PNG_COLOR_TYPE_RGB: /* Humm, this smells. Carry on though. */ png_set_read_user_transform_fn( png, convert_bytes_to_data ); break; } if ( FT_NEW_ARRAY( rows, imgHeight ) ) { error = FT_THROW( Out_Of_Memory ); goto DestroyExit; } for ( i = 0; i < (FT_Int)imgHeight; i++ ) rows[i] = map->buffer + ( y_offset + i ) * map->pitch + x_offset * 4; png_read_image( png, rows ); FT_FREE( rows ); png_read_end( png, info ); DestroyExit: png_destroy_read_struct( &png, &info, NULL ); FT_Stream_Close( &stream ); Exit: return error; }
164,854
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: ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } Commit Message: CVE-2017-13039/IKEv1: Do more bounds checking. Have ikev1_attrmap_print() and ikev1_attr_print() do full bounds checking, and return null on a bounds overflow. Have their callers check for a null return. 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
ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; }
167,843
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ssize_t nbd_wr_syncv(QIOChannel *ioc, struct iovec *iov, size_t niov, size_t length, bool do_read) { ssize_t done = 0; Error *local_err = NULL; struct iovec *local_iov = g_new(struct iovec, niov); struct iovec *local_iov_head = local_iov; unsigned int nlocal_iov = niov; nlocal_iov = iov_copy(local_iov, nlocal_iov, iov, niov, 0, length); while (nlocal_iov > 0) { ssize_t len; if (do_read) { len = qio_channel_readv(ioc, local_iov, nlocal_iov, &local_err); } else { len = qio_channel_writev(ioc, local_iov, nlocal_iov, &local_err); } if (len == QIO_CHANNEL_ERR_BLOCK) { if (qemu_in_coroutine()) { /* XXX figure out if we can create a variant on * qio_channel_yield() that works with AIO contexts * and consider using that in this branch */ qemu_coroutine_yield(); } else if (done) { /* XXX this is needed by nbd_reply_ready. */ qio_channel_wait(ioc, do_read ? G_IO_IN : G_IO_OUT); } else { return -EAGAIN; } } else if (done) { /* XXX this is needed by nbd_reply_ready. */ qio_channel_wait(ioc, do_read ? G_IO_IN : G_IO_OUT); } else { return -EAGAIN; } continue; } if (len < 0) { TRACE("I/O error: %s", error_get_pretty(local_err)); error_free(local_err); /* XXX handle Error objects */ done = -EIO; goto cleanup; } if (do_read && len == 0) { break; } iov_discard_front(&local_iov, &nlocal_iov, len); done += len; } Commit Message: CWE ID: CWE-20
ssize_t nbd_wr_syncv(QIOChannel *ioc, struct iovec *iov, size_t niov, size_t length, bool do_read) { ssize_t done = 0; Error *local_err = NULL; struct iovec *local_iov = g_new(struct iovec, niov); struct iovec *local_iov_head = local_iov; unsigned int nlocal_iov = niov; nlocal_iov = iov_copy(local_iov, nlocal_iov, iov, niov, 0, length); while (nlocal_iov > 0) { ssize_t len; if (do_read) { len = qio_channel_readv(ioc, local_iov, nlocal_iov, &local_err); } else { len = qio_channel_writev(ioc, local_iov, nlocal_iov, &local_err); } if (len == QIO_CHANNEL_ERR_BLOCK) { if (qemu_in_coroutine()) { qio_channel_yield(ioc, do_read ? G_IO_IN : G_IO_OUT); } else { return -EAGAIN; } } else if (done) { /* XXX this is needed by nbd_reply_ready. */ qio_channel_wait(ioc, do_read ? G_IO_IN : G_IO_OUT); } else { return -EAGAIN; } continue; } if (len < 0) { TRACE("I/O error: %s", error_get_pretty(local_err)); error_free(local_err); /* XXX handle Error objects */ done = -EIO; goto cleanup; } if (do_read && len == 0) { break; } iov_discard_front(&local_iov, &nlocal_iov, len); done += len; }
165,451
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: ospf6_print_lshdr(netdissect_options *ndo, register const struct lsa6_hdr *lshp, const u_char *dataend) { if ((const u_char *)(lshp + 1) > dataend) goto trunc; ND_TCHECK(lshp->ls_type); ND_TCHECK(lshp->ls_seq); ND_PRINT((ndo, "\n\t Advertising Router %s, seq 0x%08x, age %us, length %u", ipaddr_string(ndo, &lshp->ls_router), EXTRACT_32BITS(&lshp->ls_seq), EXTRACT_16BITS(&lshp->ls_age), EXTRACT_16BITS(&lshp->ls_length)-(u_int)sizeof(struct lsa6_hdr))); ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lshp->ls_type), &lshp->ls_stateid); return (0); trunc: return (1); } Commit Message: (for 4.9.3) CVE-2018-14880/OSPFv3: Fix a bounds check Need to test bounds check for the last field of the structure lsa6_hdr. No need to test other fields. Include Security working under the Mozilla SOS program had independently identified this vulnerability in 2018 by means of code audit. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test. CWE ID: CWE-125
ospf6_print_lshdr(netdissect_options *ndo, register const struct lsa6_hdr *lshp, const u_char *dataend) { if ((const u_char *)(lshp + 1) > dataend) goto trunc; ND_TCHECK(lshp->ls_length); /* last field of struct lsa6_hdr */ ND_PRINT((ndo, "\n\t Advertising Router %s, seq 0x%08x, age %us, length %u", ipaddr_string(ndo, &lshp->ls_router), EXTRACT_32BITS(&lshp->ls_seq), EXTRACT_16BITS(&lshp->ls_age), EXTRACT_16BITS(&lshp->ls_length)-(u_int)sizeof(struct lsa6_hdr))); ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lshp->ls_type), &lshp->ls_stateid); return (0); trunc: return (1); }
169,834
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: userauth_hostbased(struct ssh *ssh) { Authctxt *authctxt = ssh->authctxt; struct sshbuf *b; struct sshkey *key = NULL; char *pkalg, *cuser, *chost; u_char *pkblob, *sig; size_t alen, blen, slen; int r, pktype, authenticated = 0; if (!authctxt->valid) { debug2("%s: disabled because of invalid user", __func__); return 0; } /* XXX use sshkey_froms() */ if ((r = sshpkt_get_cstring(ssh, &pkalg, &alen)) != 0 || (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 || (r = sshpkt_get_cstring(ssh, &chost, NULL)) != 0 || (r = sshpkt_get_cstring(ssh, &cuser, NULL)) != 0 || (r = sshpkt_get_string(ssh, &sig, &slen)) != 0) fatal("%s: packet parsing: %s", __func__, ssh_err(r)); debug("%s: cuser %s chost %s pkalg %s slen %zu", __func__, cuser, chost, pkalg, slen); #ifdef DEBUG_PK debug("signature:"); sshbuf_dump_data(sig, siglen, stderr); #endif pktype = sshkey_type_from_name(pkalg); if (pktype == KEY_UNSPEC) { /* this is perfectly legal */ logit("%s: unsupported public key algorithm: %s", __func__, pkalg); goto done; } if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) { error("%s: key_from_blob: %s", __func__, ssh_err(r)); goto done; } if (key == NULL) { error("%s: cannot decode key: %s", __func__, pkalg); goto done; } if (key->type != pktype) { error("%s: type mismatch for decoded key " "(received %d, expected %d)", __func__, key->type, pktype); goto done; } if (sshkey_type_plain(key->type) == KEY_RSA && (ssh->compat & SSH_BUG_RSASIGMD5) != 0) { error("Refusing RSA key because peer uses unsafe " "signature format"); goto done; } if (match_pattern_list(pkalg, options.hostbased_key_types, 0) != 1) { logit("%s: key type %s not in HostbasedAcceptedKeyTypes", __func__, sshkey_type(key)); goto done; } if ((b = sshbuf_new()) == NULL) fatal("%s: sshbuf_new failed", __func__); /* reconstruct packet */ if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 || (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 || (r = sshbuf_put_cstring(b, authctxt->user)) != 0 || (r = sshbuf_put_cstring(b, authctxt->service)) != 0 || (r = sshbuf_put_cstring(b, "hostbased")) != 0 || (r = sshbuf_put_string(b, pkalg, alen)) != 0 || (r = sshbuf_put_string(b, pkblob, blen)) != 0 || (r = sshbuf_put_cstring(b, chost)) != 0 || (r = sshbuf_put_cstring(b, cuser)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); #ifdef DEBUG_PK sshbuf_dump(b, stderr); #endif auth2_record_info(authctxt, "client user \"%.100s\", client host \"%.100s\"", cuser, chost); /* test for allowed key and correct signature */ authenticated = 0; if (PRIVSEP(hostbased_key_allowed(authctxt->pw, cuser, chost, key)) && PRIVSEP(sshkey_verify(key, sig, slen, sshbuf_ptr(b), sshbuf_len(b), pkalg, ssh->compat)) == 0) authenticated = 1; auth2_record_key(authctxt, authenticated, key); sshbuf_free(b); done: debug2("%s: authenticated %d", __func__, authenticated); sshkey_free(key); free(pkalg); free(pkblob); free(cuser); free(chost); free(sig); return authenticated; } Commit Message: delay bailout for invalid authenticating user until after the packet containing the request has been fully parsed. Reported by Dariusz Tytko and Michał Sajdak; ok deraadt CWE ID: CWE-200
userauth_hostbased(struct ssh *ssh) { Authctxt *authctxt = ssh->authctxt; struct sshbuf *b; struct sshkey *key = NULL; char *pkalg, *cuser, *chost; u_char *pkblob, *sig; size_t alen, blen, slen; int r, pktype, authenticated = 0; /* XXX use sshkey_froms() */ if ((r = sshpkt_get_cstring(ssh, &pkalg, &alen)) != 0 || (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 || (r = sshpkt_get_cstring(ssh, &chost, NULL)) != 0 || (r = sshpkt_get_cstring(ssh, &cuser, NULL)) != 0 || (r = sshpkt_get_string(ssh, &sig, &slen)) != 0) fatal("%s: packet parsing: %s", __func__, ssh_err(r)); debug("%s: cuser %s chost %s pkalg %s slen %zu", __func__, cuser, chost, pkalg, slen); #ifdef DEBUG_PK debug("signature:"); sshbuf_dump_data(sig, siglen, stderr); #endif pktype = sshkey_type_from_name(pkalg); if (pktype == KEY_UNSPEC) { /* this is perfectly legal */ logit("%s: unsupported public key algorithm: %s", __func__, pkalg); goto done; } if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) { error("%s: key_from_blob: %s", __func__, ssh_err(r)); goto done; } if (key == NULL) { error("%s: cannot decode key: %s", __func__, pkalg); goto done; } if (key->type != pktype) { error("%s: type mismatch for decoded key " "(received %d, expected %d)", __func__, key->type, pktype); goto done; } if (sshkey_type_plain(key->type) == KEY_RSA && (ssh->compat & SSH_BUG_RSASIGMD5) != 0) { error("Refusing RSA key because peer uses unsafe " "signature format"); goto done; } if (match_pattern_list(pkalg, options.hostbased_key_types, 0) != 1) { logit("%s: key type %s not in HostbasedAcceptedKeyTypes", __func__, sshkey_type(key)); goto done; } if (!authctxt->valid || authctxt->user == NULL) { debug2("%s: disabled because of invalid user", __func__); goto done; } if ((b = sshbuf_new()) == NULL) fatal("%s: sshbuf_new failed", __func__); /* reconstruct packet */ if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 || (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 || (r = sshbuf_put_cstring(b, authctxt->user)) != 0 || (r = sshbuf_put_cstring(b, authctxt->service)) != 0 || (r = sshbuf_put_cstring(b, "hostbased")) != 0 || (r = sshbuf_put_string(b, pkalg, alen)) != 0 || (r = sshbuf_put_string(b, pkblob, blen)) != 0 || (r = sshbuf_put_cstring(b, chost)) != 0 || (r = sshbuf_put_cstring(b, cuser)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); #ifdef DEBUG_PK sshbuf_dump(b, stderr); #endif auth2_record_info(authctxt, "client user \"%.100s\", client host \"%.100s\"", cuser, chost); /* test for allowed key and correct signature */ authenticated = 0; if (PRIVSEP(hostbased_key_allowed(authctxt->pw, cuser, chost, key)) && PRIVSEP(sshkey_verify(key, sig, slen, sshbuf_ptr(b), sshbuf_len(b), pkalg, ssh->compat)) == 0) authenticated = 1; auth2_record_key(authctxt, authenticated, key); sshbuf_free(b); done: debug2("%s: authenticated %d", __func__, authenticated); sshkey_free(key); free(pkalg); free(pkblob); free(cuser); free(chost); free(sig); return authenticated; }
169,105
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: Node::InsertionNotificationRequest HTMLLinkElement::InsertedInto( ContainerNode& insertion_point) { HTMLElement::InsertedInto(insertion_point); LogAddElementIfIsolatedWorldAndInDocument("link", relAttr, hrefAttr); if (!insertion_point.isConnected()) return kInsertionDone; DCHECK(isConnected()); if (!ShouldLoadLink() && IsInShadowTree()) { String message = "HTML element <link> is ignored in shadow tree."; GetDocument().AddConsoleMessage(ConsoleMessage::Create( kJSMessageSource, kWarningMessageLevel, message)); return kInsertionDone; } GetDocument().GetStyleEngine().AddStyleSheetCandidateNode(*this); Process(); if (link_) link_->OwnerInserted(); return kInsertionDone; } Commit Message: Avoid crash when setting rel=stylesheet on <link> in shadow root. Link elements in shadow roots without rel=stylesheet are currently not added as stylesheet candidates upon insertion. This causes a crash if rel=stylesheet is set (and then loaded) later. [email protected] Bug: 886753 Change-Id: Ia0de2c1edf43407950f973982ee1c262a909d220 Reviewed-on: https://chromium-review.googlesource.com/1242463 Commit-Queue: Anders Ruud <[email protected]> Reviewed-by: Rune Lillesveen <[email protected]> Cr-Commit-Position: refs/heads/master@{#593907} CWE ID: CWE-416
Node::InsertionNotificationRequest HTMLLinkElement::InsertedInto( ContainerNode& insertion_point) { HTMLElement::InsertedInto(insertion_point); LogAddElementIfIsolatedWorldAndInDocument("link", relAttr, hrefAttr); if (!insertion_point.isConnected()) return kInsertionDone; DCHECK(isConnected()); GetDocument().GetStyleEngine().AddStyleSheetCandidateNode(*this); if (!ShouldLoadLink() && IsInShadowTree()) { String message = "HTML element <link> is ignored in shadow tree."; GetDocument().AddConsoleMessage(ConsoleMessage::Create( kJSMessageSource, kWarningMessageLevel, message)); return kInsertionDone; } Process(); if (link_) link_->OwnerInserted(); return kInsertionDone; }
172,586
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_image_resize(Jbig2Ctx *ctx, Jbig2Image *image, int width, int height) { if (width == image->width) { /* check for integer multiplication overflow */ int64_t check = ((int64_t) image->stride) * ((int64_t) height); if (check != (int)check) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow during resize stride(%d)*height(%d)", image->stride, height); return NULL; } /* use the same stride, just change the length */ image->data = jbig2_renew(ctx, image->data, uint8_t, (int)check); if (image->data == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not resize image buffer!"); return NULL; } if (height > image->height) { memset(image->data + image->height * image->stride, 0, (height - image->height) * image->stride); } image->height = height; } else { /* we must allocate a new image buffer and copy */ jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "jbig2_image_resize called with a different width (NYI)"); } return NULL; } Commit Message: CWE ID: CWE-119
jbig2_image_resize(Jbig2Ctx *ctx, Jbig2Image *image, int width, int height) jbig2_image_resize(Jbig2Ctx *ctx, Jbig2Image *image, uint32_t width, uint32_t height) { if (width == image->width) { /* check for integer multiplication overflow */ int64_t check = ((int64_t) image->stride) * ((int64_t) height); if (check != (int)check) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow during resize stride(%d)*height(%d)", image->stride, height); return NULL; } /* use the same stride, just change the length */ image->data = jbig2_renew(ctx, image->data, uint8_t, (int)check); if (image->data == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not resize image buffer!"); return NULL; } if (height > image->height) { memset(image->data + image->height * image->stride, 0, (height - image->height) * image->stride); } image->height = height; } else { /* we must allocate a new image buffer and copy */ jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "jbig2_image_resize called with a different width (NYI)"); } return NULL; }
165,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: long Cluster::GetLast(const BlockEntry*& pLast) const { for (;;) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) //error { pLast = NULL; return status; } if (status > 0) //no new block break; } if (m_entries_count <= 0) { pLast = NULL; return 0; } assert(m_entries); const long idx = m_entries_count - 1; pLast = m_entries[idx]; assert(pLast); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Cluster::GetLast(const BlockEntry*& pLast) const if (m_entries_count <= 0) { pLast = NULL; return 0; } assert(m_entries); const long idx = m_entries_count - 1; pLast = m_entries[idx]; assert(pLast); return 0; }
174,338
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 FileBrowserHandlerCustomBindings::GetExternalFileEntry( const v8::FunctionCallbackInfo<v8::Value>& args) { //// TODO(zelidrag): Make this magic work on other platforms when file browser //// matures enough on ChromeOS. #if defined(OS_CHROMEOS) CHECK(args.Length() == 1); CHECK(args[0]->IsObject()); v8::Local<v8::Object> file_def = args[0]->ToObject(); std::string file_system_name( *v8::String::Utf8Value(file_def->Get( v8::String::NewFromUtf8(args.GetIsolate(), "fileSystemName")))); GURL file_system_root( *v8::String::Utf8Value(file_def->Get( v8::String::NewFromUtf8(args.GetIsolate(), "fileSystemRoot")))); std::string file_full_path( *v8::String::Utf8Value(file_def->Get( v8::String::NewFromUtf8(args.GetIsolate(), "fileFullPath")))); bool is_directory = file_def->Get(v8::String::NewFromUtf8( args.GetIsolate(), "fileIsDirectory"))->ToBoolean()->Value(); blink::WebDOMFileSystem::EntryType entry_type = is_directory ? blink::WebDOMFileSystem::EntryTypeDirectory : blink::WebDOMFileSystem::EntryTypeFile; blink::WebLocalFrame* webframe = blink::WebLocalFrame::frameForContext(context()->v8_context()); args.GetReturnValue().Set( blink::WebDOMFileSystem::create( webframe, blink::WebFileSystemTypeExternal, blink::WebString::fromUTF8(file_system_name), file_system_root) .createV8Entry(blink::WebString::fromUTF8(file_full_path), entry_type, args.Holder(), args.GetIsolate())); #endif } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID:
void FileBrowserHandlerCustomBindings::GetExternalFileEntry( const v8::FunctionCallbackInfo<v8::Value>& args, ScriptContext* context) { //// TODO(zelidrag): Make this magic work on other platforms when file browser //// matures enough on ChromeOS. #if defined(OS_CHROMEOS) CHECK(args.Length() == 1); CHECK(args[0]->IsObject()); v8::Local<v8::Object> file_def = args[0]->ToObject(); std::string file_system_name( *v8::String::Utf8Value(file_def->Get( v8::String::NewFromUtf8(args.GetIsolate(), "fileSystemName")))); GURL file_system_root( *v8::String::Utf8Value(file_def->Get( v8::String::NewFromUtf8(args.GetIsolate(), "fileSystemRoot")))); std::string file_full_path( *v8::String::Utf8Value(file_def->Get( v8::String::NewFromUtf8(args.GetIsolate(), "fileFullPath")))); bool is_directory = file_def->Get(v8::String::NewFromUtf8( args.GetIsolate(), "fileIsDirectory"))->ToBoolean()->Value(); blink::WebDOMFileSystem::EntryType entry_type = is_directory ? blink::WebDOMFileSystem::EntryTypeDirectory : blink::WebDOMFileSystem::EntryTypeFile; blink::WebLocalFrame* webframe = blink::WebLocalFrame::frameForContext(context->v8_context()); args.GetReturnValue().Set( blink::WebDOMFileSystem::create( webframe, blink::WebFileSystemTypeExternal, blink::WebString::fromUTF8(file_system_name), file_system_root) .createV8Entry(blink::WebString::fromUTF8(file_full_path), entry_type, args.Holder(), args.GetIsolate())); #endif }
173,273
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 HeapAllocator::backingShrink(void* address, size_t quantizedCurrentSize, size_t quantizedShrunkSize) { if (!address || quantizedShrunkSize == quantizedCurrentSize) return true; ASSERT(quantizedShrunkSize < quantizedCurrentSize); ThreadState* state = ThreadState::current(); if (state->sweepForbidden()) return false; ASSERT(!state->isInGC()); ASSERT(state->isAllocationAllowed()); DCHECK_EQ(&state->heap(), &ThreadState::fromObject(address)->heap()); BasePage* page = pageFromObject(address); if (page->isLargeObjectPage() || page->arena()->getThreadState() != state) return false; HeapObjectHeader* header = HeapObjectHeader::fromPayload(address); ASSERT(header->checkHeader()); NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage(); if (quantizedCurrentSize <= quantizedShrunkSize + sizeof(HeapObjectHeader) + sizeof(void*) * 32 && !arena->isObjectAllocatedAtAllocationPoint(header)) return true; bool succeededAtAllocationPoint = arena->shrinkObject(header, quantizedShrunkSize); if (succeededAtAllocationPoint) state->allocationPointAdjusted(arena->arenaIndex()); return true; } 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
bool HeapAllocator::backingShrink(void* address, size_t quantizedCurrentSize, size_t quantizedShrunkSize) { if (!address || quantizedShrunkSize == quantizedCurrentSize) return true; ASSERT(quantizedShrunkSize < quantizedCurrentSize); ThreadState* state = ThreadState::current(); if (state->sweepForbidden()) return false; ASSERT(!state->isInGC()); ASSERT(state->isAllocationAllowed()); DCHECK_EQ(&state->heap(), &ThreadState::fromObject(address)->heap()); BasePage* page = pageFromObject(address); if (page->isLargeObjectPage() || page->arena()->getThreadState() != state) return false; HeapObjectHeader* header = HeapObjectHeader::fromPayload(address); header->checkHeader(); NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage(); if (quantizedCurrentSize <= quantizedShrunkSize + sizeof(HeapObjectHeader) + sizeof(void*) * 32 && !arena->isObjectAllocatedAtAllocationPoint(header)) return true; bool succeededAtAllocationPoint = arena->shrinkObject(header, quantizedShrunkSize); if (succeededAtAllocationPoint) state->allocationPointAdjusted(arena->arenaIndex()); return true; }
172,707
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 ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *isk = inet_sk(sk); int family = sk->sk_family; struct sockaddr_in *sin; struct sockaddr_in6 *sin6; struct sk_buff *skb; int copied, err; pr_debug("ping_recvmsg(sk=%p,sk->num=%u)\n", isk, isk->inet_num); err = -EOPNOTSUPP; if (flags & MSG_OOB) goto out; if (addr_len) { if (family == AF_INET) *addr_len = sizeof(*sin); else if (family == AF_INET6 && addr_len) *addr_len = sizeof(*sin6); } if (flags & MSG_ERRQUEUE) { if (family == AF_INET) { return ip_recv_error(sk, msg, len); #if IS_ENABLED(CONFIG_IPV6) } else if (family == AF_INET6) { return pingv6_ops.ipv6_recv_error(sk, msg, len); #endif } } skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } /* Don't bother checking the checksum */ err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address and add cmsg data. */ if (family == AF_INET) { sin = (struct sockaddr_in *) msg->msg_name; sin->sin_family = AF_INET; sin->sin_port = 0 /* skb->h.uh->source */; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); if (isk->cmsg_flags) ip_cmsg_recv(msg, skb); #if IS_ENABLED(CONFIG_IPV6) } else if (family == AF_INET6) { struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6hdr *ip6 = ipv6_hdr(skb); sin6 = (struct sockaddr_in6 *) msg->msg_name; sin6->sin6_family = AF_INET6; sin6->sin6_port = 0; sin6->sin6_addr = ip6->saddr; sin6->sin6_flowinfo = 0; if (np->sndflow) sin6->sin6_flowinfo = ip6_flowinfo(ip6); sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr, IP6CB(skb)->iif); if (inet6_sk(sk)->rxopt.all) pingv6_ops.ip6_datagram_recv_ctl(sk, msg, skb); #endif } else { BUG(); } err = copied; done: skb_free_datagram(sk, skb); out: pr_debug("ping_recvmsg -> %d\n", err); return err; } 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 ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *isk = inet_sk(sk); int family = sk->sk_family; struct sk_buff *skb; int copied, err; pr_debug("ping_recvmsg(sk=%p,sk->num=%u)\n", isk, isk->inet_num); err = -EOPNOTSUPP; if (flags & MSG_OOB) goto out; if (flags & MSG_ERRQUEUE) { if (family == AF_INET) { return ip_recv_error(sk, msg, len); #if IS_ENABLED(CONFIG_IPV6) } else if (family == AF_INET6) { return pingv6_ops.ipv6_recv_error(sk, msg, len); #endif } } skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } /* Don't bother checking the checksum */ err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address and add cmsg data. */ if (family == AF_INET) { struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name; sin->sin_family = AF_INET; sin->sin_port = 0 /* skb->h.uh->source */; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); *addr_len = sizeof(*sin); if (isk->cmsg_flags) ip_cmsg_recv(msg, skb); #if IS_ENABLED(CONFIG_IPV6) } else if (family == AF_INET6) { struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6hdr *ip6 = ipv6_hdr(skb); struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)msg->msg_name; sin6->sin6_family = AF_INET6; sin6->sin6_port = 0; sin6->sin6_addr = ip6->saddr; sin6->sin6_flowinfo = 0; if (np->sndflow) sin6->sin6_flowinfo = ip6_flowinfo(ip6); sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr, IP6CB(skb)->iif); *addr_len = sizeof(*sin6); if (inet6_sk(sk)->rxopt.all) pingv6_ops.ip6_datagram_recv_ctl(sk, msg, skb); #endif } else { BUG(); } err = copied; done: skb_free_datagram(sk, skb); out: pr_debug("ping_recvmsg -> %d\n", err); return err; }
166,477
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 BaseAudioContext::WouldTaintOrigin(const KURL& url) const { if (url.ProtocolIsData()) { return false; } Document* document = GetDocument(); if (document && document->GetSecurityOrigin()) { return !document->GetSecurityOrigin()->CanRequest(url); } return true; } 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 BaseAudioContext::WouldTaintOrigin(const KURL& url) const {
172,633
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 StorageHandler::ClearDataForOrigin( const std::string& origin, const std::string& storage_types, std::unique_ptr<ClearDataForOriginCallback> callback) { if (!process_) return callback->sendFailure(Response::InternalError()); StoragePartition* partition = process_->GetStoragePartition(); std::vector<std::string> types = base::SplitString( storage_types, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); std::unordered_set<std::string> set(types.begin(), types.end()); uint32_t remove_mask = 0; if (set.count(Storage::StorageTypeEnum::Appcache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_APPCACHE; if (set.count(Storage::StorageTypeEnum::Cookies)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_COOKIES; if (set.count(Storage::StorageTypeEnum::File_systems)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS; if (set.count(Storage::StorageTypeEnum::Indexeddb)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB; if (set.count(Storage::StorageTypeEnum::Local_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE; if (set.count(Storage::StorageTypeEnum::Shader_cache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE; if (set.count(Storage::StorageTypeEnum::Websql)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_WEBSQL; if (set.count(Storage::StorageTypeEnum::Service_workers)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS; if (set.count(Storage::StorageTypeEnum::Cache_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE; if (set.count(Storage::StorageTypeEnum::All)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_ALL; if (!remove_mask) { return callback->sendFailure( Response::InvalidParams("No valid storage type specified")); } partition->ClearData(remove_mask, StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL, GURL(origin), StoragePartition::OriginMatcherFunction(), base::Time(), base::Time::Max(), base::BindOnce(&ClearDataForOriginCallback::sendSuccess, std::move(callback))); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void StorageHandler::ClearDataForOrigin( const std::string& origin, const std::string& storage_types, std::unique_ptr<ClearDataForOriginCallback> callback) { if (!storage_partition_) return callback->sendFailure(Response::InternalError()); std::vector<std::string> types = base::SplitString( storage_types, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); std::unordered_set<std::string> set(types.begin(), types.end()); uint32_t remove_mask = 0; if (set.count(Storage::StorageTypeEnum::Appcache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_APPCACHE; if (set.count(Storage::StorageTypeEnum::Cookies)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_COOKIES; if (set.count(Storage::StorageTypeEnum::File_systems)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS; if (set.count(Storage::StorageTypeEnum::Indexeddb)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB; if (set.count(Storage::StorageTypeEnum::Local_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE; if (set.count(Storage::StorageTypeEnum::Shader_cache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE; if (set.count(Storage::StorageTypeEnum::Websql)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_WEBSQL; if (set.count(Storage::StorageTypeEnum::Service_workers)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS; if (set.count(Storage::StorageTypeEnum::Cache_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE; if (set.count(Storage::StorageTypeEnum::All)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_ALL; if (!remove_mask) { return callback->sendFailure( Response::InvalidParams("No valid storage type specified")); } storage_partition_->ClearData( remove_mask, StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL, GURL(origin), StoragePartition::OriginMatcherFunction(), base::Time(), base::Time::Max(), base::BindOnce(&ClearDataForOriginCallback::sendSuccess, std::move(callback))); }
172,770