instruction
stringclasses 1
value | input
stringlengths 90
9.3k
| 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: DevToolsClient::DevToolsClient(
RenderFrame* main_render_frame,
const std::string& compatibility_script)
: RenderFrameObserver(main_render_frame),
compatibility_script_(compatibility_script),
web_tools_frontend_(
WebDevToolsFrontend::create(main_render_frame->GetWebFrame(), this)) {
}
Commit Message: [DevTools] Move sanitize url to devtools_ui.cc.
Compatibility script is not reliable enough.
BUG=653134
Review-Url: https://codereview.chromium.org/2403633002
Cr-Commit-Position: refs/heads/master@{#425814}
CWE ID: CWE-200
|
DevToolsClient::DevToolsClient(
RenderFrame* main_render_frame,
const std::string& compatibility_script)
: RenderFrameObserver(main_render_frame),
compatibility_script_(compatibility_script),
web_tools_frontend_(
WebDevToolsFrontend::create(main_render_frame->GetWebFrame(), this)) {
compatibility_script_ += "\n//# sourceURL=devtools_compatibility.js";
}
| 172,511
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BluetoothDeviceChooserController::GetDevice(
blink::mojom::WebBluetoothRequestDeviceOptionsPtr options,
const SuccessCallback& success_callback,
const ErrorCallback& error_callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(success_callback_.is_null());
DCHECK(error_callback_.is_null());
success_callback_ = success_callback;
error_callback_ = error_callback;
options_ = std::move(options);
LogRequestDeviceOptions(options_);
if (options_->filters &&
BluetoothBlocklist::Get().IsExcluded(options_->filters.value())) {
RecordRequestDeviceOutcome(
UMARequestDeviceOutcome::BLOCKLISTED_SERVICE_IN_FILTER);
PostErrorCallback(
blink::mojom::WebBluetoothResult::REQUEST_DEVICE_WITH_BLOCKLISTED_UUID);
return;
}
BluetoothBlocklist::Get().RemoveExcludedUUIDs(options_.get());
const url::Origin requesting_origin =
render_frame_host_->GetLastCommittedOrigin();
const url::Origin embedding_origin =
web_contents_->GetMainFrame()->GetLastCommittedOrigin();
if (!embedding_origin.IsSameOriginWith(requesting_origin)) {
PostErrorCallback(blink::mojom::WebBluetoothResult::
REQUEST_DEVICE_FROM_CROSS_ORIGIN_IFRAME);
return;
}
DCHECK(!requesting_origin.opaque());
if (!adapter_->IsPresent()) {
DVLOG(1) << "Bluetooth Adapter not present. Can't serve requestDevice.";
RecordRequestDeviceOutcome(
UMARequestDeviceOutcome::BLUETOOTH_ADAPTER_NOT_PRESENT);
PostErrorCallback(blink::mojom::WebBluetoothResult::NO_BLUETOOTH_ADAPTER);
return;
}
switch (GetContentClient()->browser()->AllowWebBluetooth(
web_contents_->GetBrowserContext(), requesting_origin,
embedding_origin)) {
case ContentBrowserClient::AllowWebBluetoothResult::BLOCK_POLICY: {
RecordRequestDeviceOutcome(
UMARequestDeviceOutcome::BLUETOOTH_CHOOSER_POLICY_DISABLED);
PostErrorCallback(blink::mojom::WebBluetoothResult::
CHOOSER_NOT_SHOWN_API_LOCALLY_DISABLED);
return;
}
case ContentBrowserClient::AllowWebBluetoothResult::
BLOCK_GLOBALLY_DISABLED: {
web_contents_->GetMainFrame()->AddMessageToConsole(
blink::mojom::ConsoleMessageLevel::kInfo,
"Bluetooth permission has been blocked.");
RecordRequestDeviceOutcome(
UMARequestDeviceOutcome::BLUETOOTH_GLOBALLY_DISABLED);
PostErrorCallback(blink::mojom::WebBluetoothResult::
CHOOSER_NOT_SHOWN_API_GLOBALLY_DISABLED);
return;
}
case ContentBrowserClient::AllowWebBluetoothResult::ALLOW:
break;
}
BluetoothChooser::EventHandler chooser_event_handler =
base::Bind(&BluetoothDeviceChooserController::OnBluetoothChooserEvent,
base::Unretained(this));
if (WebContentsDelegate* delegate = web_contents_->GetDelegate()) {
chooser_ = delegate->RunBluetoothChooser(render_frame_host_,
std::move(chooser_event_handler));
}
if (!chooser_.get()) {
PostErrorCallback(
blink::mojom::WebBluetoothResult::WEB_BLUETOOTH_NOT_SUPPORTED);
return;
}
if (!chooser_->CanAskForScanningPermission()) {
DVLOG(1) << "Closing immediately because Chooser cannot obtain permission.";
OnBluetoothChooserEvent(BluetoothChooser::Event::DENIED_PERMISSION,
"" /* device_address */);
return;
}
device_ids_.clear();
PopulateConnectedDevices();
if (!chooser_.get()) {
return;
}
if (!adapter_->IsPowered()) {
chooser_->SetAdapterPresence(
BluetoothChooser::AdapterPresence::POWERED_OFF);
return;
}
StartDeviceDiscovery();
}
Commit Message: bluetooth: Implement getAvailability()
This change implements the getAvailability() method for
navigator.bluetooth as defined in the specification.
Bug: 707640
Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516
Reviewed-by: Chris Harrelson <chrishtr@chromium.org>
Reviewed-by: Giovanni Ortuño Urquidi <ortuno@chromium.org>
Reviewed-by: Kinuko Yasuda <kinuko@chromium.org>
Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <odejesush@chromium.org>
Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <odejesush@chromium.org>
Cr-Commit-Position: refs/heads/master@{#688987}
CWE ID: CWE-119
|
void BluetoothDeviceChooserController::GetDevice(
blink::mojom::WebBluetoothRequestDeviceOptionsPtr options,
const SuccessCallback& success_callback,
const ErrorCallback& error_callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(success_callback_.is_null());
DCHECK(error_callback_.is_null());
success_callback_ = success_callback;
error_callback_ = error_callback;
options_ = std::move(options);
LogRequestDeviceOptions(options_);
if (options_->filters &&
BluetoothBlocklist::Get().IsExcluded(options_->filters.value())) {
RecordRequestDeviceOutcome(
UMARequestDeviceOutcome::BLOCKLISTED_SERVICE_IN_FILTER);
PostErrorCallback(WebBluetoothResult::REQUEST_DEVICE_WITH_BLOCKLISTED_UUID);
return;
}
BluetoothBlocklist::Get().RemoveExcludedUUIDs(options_.get());
WebBluetoothResult allow_result =
web_bluetooth_service_->GetBluetoothAllowed();
if (allow_result != WebBluetoothResult::SUCCESS) {
switch (allow_result) {
case WebBluetoothResult::CHOOSER_NOT_SHOWN_API_LOCALLY_DISABLED: {
RecordRequestDeviceOutcome(
UMARequestDeviceOutcome::BLUETOOTH_CHOOSER_POLICY_DISABLED);
break;
}
case WebBluetoothResult::CHOOSER_NOT_SHOWN_API_GLOBALLY_DISABLED: {
// Log to the developer console.
web_contents_->GetMainFrame()->AddMessageToConsole(
blink::mojom::ConsoleMessageLevel::kInfo,
"Bluetooth permission has been blocked.");
// Block requests.
RecordRequestDeviceOutcome(
UMARequestDeviceOutcome::BLUETOOTH_GLOBALLY_DISABLED);
break;
}
default:
break;
}
PostErrorCallback(allow_result);
return;
}
if (!adapter_->IsPresent()) {
DVLOG(1) << "Bluetooth Adapter not present. Can't serve requestDevice.";
RecordRequestDeviceOutcome(
UMARequestDeviceOutcome::BLUETOOTH_ADAPTER_NOT_PRESENT);
PostErrorCallback(WebBluetoothResult::NO_BLUETOOTH_ADAPTER);
return;
}
BluetoothChooser::EventHandler chooser_event_handler =
base::Bind(&BluetoothDeviceChooserController::OnBluetoothChooserEvent,
base::Unretained(this));
if (WebContentsDelegate* delegate = web_contents_->GetDelegate()) {
chooser_ = delegate->RunBluetoothChooser(render_frame_host_,
std::move(chooser_event_handler));
}
if (!chooser_.get()) {
PostErrorCallback(WebBluetoothResult::WEB_BLUETOOTH_NOT_SUPPORTED);
return;
}
if (!chooser_->CanAskForScanningPermission()) {
DVLOG(1) << "Closing immediately because Chooser cannot obtain permission.";
OnBluetoothChooserEvent(BluetoothChooser::Event::DENIED_PERMISSION,
"" /* device_address */);
return;
}
device_ids_.clear();
PopulateConnectedDevices();
if (!chooser_.get()) {
return;
}
if (!adapter_->IsPowered()) {
chooser_->SetAdapterPresence(
BluetoothChooser::AdapterPresence::POWERED_OFF);
return;
}
StartDeviceDiscovery();
}
| 172,443
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: EC_KEY *d2i_ECPrivateKey(EC_KEY **a, const unsigned char **in, long len)
{
int ok = 0;
EC_KEY *ret = NULL;
EC_PRIVATEKEY *priv_key = NULL;
if ((priv_key = EC_PRIVATEKEY_new()) == NULL) {
ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE);
return NULL;
}
if ((priv_key = d2i_EC_PRIVATEKEY(&priv_key, in, len)) == NULL) {
ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB);
EC_PRIVATEKEY_free(priv_key);
return NULL;
}
if (a == NULL || *a == NULL) {
if ((ret = EC_KEY_new()) == NULL) {
ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE);
goto err;
}
if (a)
*a = ret;
} else
ret = *a;
ret = *a;
if (priv_key->parameters) {
if (ret->group)
EC_GROUP_clear_free(ret->group);
ret->group = ec_asn1_pkparameters2group(priv_key->parameters);
}
if (ret->group == NULL) {
ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB);
goto err;
}
ret->version = priv_key->version;
if (priv_key->privateKey) {
ret->priv_key = BN_bin2bn(M_ASN1_STRING_data(priv_key->privateKey),
M_ASN1_STRING_length(priv_key->privateKey),
ret->priv_key);
if (ret->priv_key == NULL) {
ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_BN_LIB);
goto err;
}
} else {
ECerr(EC_F_D2I_ECPRIVATEKEY, EC_R_MISSING_PRIVATE_KEY);
goto err;
}
if (priv_key->publicKey) {
const unsigned char *pub_oct;
size_t pub_oct_len;
if (ret->pub_key)
EC_POINT_clear_free(ret->pub_key);
ret->pub_key = EC_POINT_new(ret->group);
if (ret->pub_key == NULL) {
ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB);
goto err;
}
pub_oct = M_ASN1_STRING_data(priv_key->publicKey);
pub_oct_len = M_ASN1_STRING_length(priv_key->publicKey);
/* save the point conversion form */
ret->conv_form = (point_conversion_form_t) (pub_oct[0] & ~0x01);
if (!EC_POINT_oct2point(ret->group, ret->pub_key,
pub_oct, pub_oct_len, NULL)) {
}
}
ok = 1;
err:
if (!ok) {
if (ret)
EC_KEY_free(ret);
ret = NULL;
}
if (priv_key)
EC_PRIVATEKEY_free(priv_key);
return (ret);
}
Commit Message:
CWE ID:
|
EC_KEY *d2i_ECPrivateKey(EC_KEY **a, const unsigned char **in, long len)
{
int ok = 0;
EC_KEY *ret = NULL;
EC_PRIVATEKEY *priv_key = NULL;
if ((priv_key = EC_PRIVATEKEY_new()) == NULL) {
ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE);
return NULL;
}
if ((priv_key = d2i_EC_PRIVATEKEY(&priv_key, in, len)) == NULL) {
ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB);
EC_PRIVATEKEY_free(priv_key);
return NULL;
}
if (a == NULL || *a == NULL) {
if ((ret = EC_KEY_new()) == NULL) {
ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE);
goto err;
}
} else
ret = *a;
ret = *a;
if (priv_key->parameters) {
if (ret->group)
EC_GROUP_clear_free(ret->group);
ret->group = ec_asn1_pkparameters2group(priv_key->parameters);
}
if (ret->group == NULL) {
ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB);
goto err;
}
ret->version = priv_key->version;
if (priv_key->privateKey) {
ret->priv_key = BN_bin2bn(M_ASN1_STRING_data(priv_key->privateKey),
M_ASN1_STRING_length(priv_key->privateKey),
ret->priv_key);
if (ret->priv_key == NULL) {
ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_BN_LIB);
goto err;
}
} else {
ECerr(EC_F_D2I_ECPRIVATEKEY, EC_R_MISSING_PRIVATE_KEY);
goto err;
}
if (priv_key->publicKey) {
const unsigned char *pub_oct;
size_t pub_oct_len;
if (ret->pub_key)
EC_POINT_clear_free(ret->pub_key);
ret->pub_key = EC_POINT_new(ret->group);
if (ret->pub_key == NULL) {
ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB);
goto err;
}
pub_oct = M_ASN1_STRING_data(priv_key->publicKey);
pub_oct_len = M_ASN1_STRING_length(priv_key->publicKey);
/* save the point conversion form */
ret->conv_form = (point_conversion_form_t) (pub_oct[0] & ~0x01);
if (!EC_POINT_oct2point(ret->group, ret->pub_key,
pub_oct, pub_oct_len, NULL)) {
}
}
if (a)
*a = ret;
ok = 1;
err:
if (!ok) {
if (ret && (a == NULL || *a != ret))
EC_KEY_free(ret);
ret = NULL;
}
if (priv_key)
EC_PRIVATEKEY_free(priv_key);
return (ret);
}
| 164,819
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 btif_fetch_local_bdaddr(bt_bdaddr_t *local_addr)
{
char val[PROPERTY_VALUE_MAX] = {0};
uint8_t valid_bda = FALSE;
int val_size = 0;
const uint8_t null_bdaddr[BD_ADDR_LEN] = {0,0,0,0,0,0};
/* Get local bdaddr storage path from property */
if (property_get(PROPERTY_BT_BDADDR_PATH, val, NULL))
{
int addr_fd;
BTIF_TRACE_DEBUG("%s, local bdaddr is stored in %s", __func__, val);
if ((addr_fd = open(val, O_RDONLY)) != -1)
{
memset(val, 0, sizeof(val));
read(addr_fd, val, FACTORY_BT_BDADDR_STORAGE_LEN);
/* If this is not a reserved/special bda, then use it */
if ((string_to_bdaddr(val, local_addr)) &&
(memcmp(local_addr->address, null_bdaddr, BD_ADDR_LEN) != 0))
{
valid_bda = TRUE;
BTIF_TRACE_DEBUG("%s: Got Factory BDA %s", __func__, val);
}
close(addr_fd);
}
}
if(!valid_bda)
{
val_size = sizeof(val);
if(btif_config_get_str("Adapter", "Address", val, &val_size))
{
string_to_bdaddr(val, local_addr);
BTIF_TRACE_DEBUG("local bdaddr from bt_config.xml is %s", val);
return;
}
}
/* No factory BDADDR found. Look for previously generated random BDA */
if (!valid_bda) {
valid_bda = btif_fetch_property(PERSIST_BDADDR_PROPERTY, local_addr);
}
/* No BDADDR found in file. Look for BDA in factory property */
if (!valid_bda) {
valid_bda = btif_fetch_property(FACTORY_BT_ADDR_PROPERTY, local_addr);
}
/* Generate new BDA if necessary */
if (!valid_bda)
{
bdstr_t bdstr;
/* Seed the random number generator */
srand((unsigned int) (time(0)));
/* No autogen BDA. Generate one now. */
local_addr->address[0] = 0x22;
local_addr->address[1] = 0x22;
local_addr->address[2] = (uint8_t) ((rand() >> 8) & 0xFF);
local_addr->address[3] = (uint8_t) ((rand() >> 8) & 0xFF);
local_addr->address[4] = (uint8_t) ((rand() >> 8) & 0xFF);
local_addr->address[5] = (uint8_t) ((rand() >> 8) & 0xFF);
/* Convert to ascii, and store as a persistent property */
bdaddr_to_string(local_addr, bdstr, sizeof(bdstr));
BTIF_TRACE_DEBUG("No preset BDA. Generating BDA: %s for prop %s",
(char*)bdstr, PERSIST_BDADDR_PROPERTY);
if (property_set(PERSIST_BDADDR_PROPERTY, (char*)bdstr) < 0)
BTIF_TRACE_ERROR("Failed to set random BDA in prop %s",PERSIST_BDADDR_PROPERTY);
}
bdstr_t bdstr;
bdaddr_to_string(local_addr, bdstr, sizeof(bdstr));
val_size = sizeof(val);
if (btif_config_get_str("Adapter", "Address", val, &val_size))
{
if (strcmp(bdstr, val) ==0)
{
return;
}
}
btif_config_set_str("Adapter", "Address", bdstr);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
static void btif_fetch_local_bdaddr(bt_bdaddr_t *local_addr)
{
char val[PROPERTY_VALUE_MAX] = {0};
uint8_t valid_bda = FALSE;
int val_size = 0;
const uint8_t null_bdaddr[BD_ADDR_LEN] = {0,0,0,0,0,0};
/* Get local bdaddr storage path from property */
if (property_get(PROPERTY_BT_BDADDR_PATH, val, NULL))
{
int addr_fd;
BTIF_TRACE_DEBUG("%s, local bdaddr is stored in %s", __func__, val);
if ((addr_fd = TEMP_FAILURE_RETRY(open(val, O_RDONLY))) != -1)
{
memset(val, 0, sizeof(val));
TEMP_FAILURE_RETRY(read(addr_fd, val, FACTORY_BT_BDADDR_STORAGE_LEN));
/* If this is not a reserved/special bda, then use it */
if ((string_to_bdaddr(val, local_addr)) &&
(memcmp(local_addr->address, null_bdaddr, BD_ADDR_LEN) != 0))
{
valid_bda = TRUE;
BTIF_TRACE_DEBUG("%s: Got Factory BDA %s", __func__, val);
}
close(addr_fd);
}
}
if(!valid_bda)
{
val_size = sizeof(val);
if(btif_config_get_str("Adapter", "Address", val, &val_size))
{
string_to_bdaddr(val, local_addr);
BTIF_TRACE_DEBUG("local bdaddr from bt_config.xml is %s", val);
return;
}
}
/* No factory BDADDR found. Look for previously generated random BDA */
if (!valid_bda) {
valid_bda = btif_fetch_property(PERSIST_BDADDR_PROPERTY, local_addr);
}
/* No BDADDR found in file. Look for BDA in factory property */
if (!valid_bda) {
valid_bda = btif_fetch_property(FACTORY_BT_ADDR_PROPERTY, local_addr);
}
/* Generate new BDA if necessary */
if (!valid_bda)
{
bdstr_t bdstr;
/* Seed the random number generator */
srand((unsigned int) (time(0)));
/* No autogen BDA. Generate one now. */
local_addr->address[0] = 0x22;
local_addr->address[1] = 0x22;
local_addr->address[2] = (uint8_t) ((rand() >> 8) & 0xFF);
local_addr->address[3] = (uint8_t) ((rand() >> 8) & 0xFF);
local_addr->address[4] = (uint8_t) ((rand() >> 8) & 0xFF);
local_addr->address[5] = (uint8_t) ((rand() >> 8) & 0xFF);
/* Convert to ascii, and store as a persistent property */
bdaddr_to_string(local_addr, bdstr, sizeof(bdstr));
BTIF_TRACE_DEBUG("No preset BDA. Generating BDA: %s for prop %s",
(char*)bdstr, PERSIST_BDADDR_PROPERTY);
if (property_set(PERSIST_BDADDR_PROPERTY, (char*)bdstr) < 0)
BTIF_TRACE_ERROR("Failed to set random BDA in prop %s",PERSIST_BDADDR_PROPERTY);
}
bdstr_t bdstr;
bdaddr_to_string(local_addr, bdstr, sizeof(bdstr));
val_size = sizeof(val);
if (btif_config_get_str("Adapter", "Address", val, &val_size))
{
if (strcmp(bdstr, val) ==0)
{
return;
}
}
btif_config_set_str("Adapter", "Address", bdstr);
}
| 173,435
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 iwl_process_add_sta_resp(struct iwl_priv *priv,
struct iwl_addsta_cmd *addsta,
struct iwl_rx_packet *pkt)
{
u8 sta_id = addsta->sta.sta_id;
unsigned long flags;
int ret = -EIO;
if (pkt->hdr.flags & IWL_CMD_FAILED_MSK) {
IWL_ERR(priv, "Bad return from REPLY_ADD_STA (0x%08X)\n",
pkt->hdr.flags);
return ret;
}
IWL_DEBUG_INFO(priv, "Processing response for adding station %u\n",
sta_id);
spin_lock_irqsave(&priv->shrd->sta_lock, flags);
switch (pkt->u.add_sta.status) {
case ADD_STA_SUCCESS_MSK:
IWL_DEBUG_INFO(priv, "REPLY_ADD_STA PASSED\n");
iwl_sta_ucode_activate(priv, sta_id);
ret = 0;
break;
case ADD_STA_NO_ROOM_IN_TABLE:
IWL_ERR(priv, "Adding station %d failed, no room in table.\n",
sta_id);
break;
case ADD_STA_NO_BLOCK_ACK_RESOURCE:
IWL_ERR(priv, "Adding station %d failed, no block ack "
"resource.\n", sta_id);
break;
case ADD_STA_MODIFY_NON_EXIST_STA:
IWL_ERR(priv, "Attempting to modify non-existing station %d\n",
sta_id);
break;
default:
IWL_DEBUG_ASSOC(priv, "Received REPLY_ADD_STA:(0x%08X)\n",
pkt->u.add_sta.status);
break;
}
IWL_DEBUG_INFO(priv, "%s station id %u addr %pM\n",
priv->stations[sta_id].sta.mode ==
STA_CONTROL_MODIFY_MSK ? "Modified" : "Added",
sta_id, priv->stations[sta_id].sta.sta.addr);
/*
* XXX: The MAC address in the command buffer is often changed from
* the original sent to the device. That is, the MAC address
* written to the command buffer often is not the same MAC address
* read from the command buffer when the command returns. This
* issue has not yet been resolved and this debugging is left to
* observe the problem.
*/
IWL_DEBUG_INFO(priv, "%s station according to cmd buffer %pM\n",
priv->stations[sta_id].sta.mode ==
STA_CONTROL_MODIFY_MSK ? "Modified" : "Added",
addsta->sta.addr);
spin_unlock_irqrestore(&priv->shrd->sta_lock, flags);
return ret;
}
Commit Message: iwlwifi: Sanity check for sta_id
On my testing, I saw some strange behavior
[ 421.739708] iwlwifi 0000:01:00.0: ACTIVATE a non DRIVER active station id 148 addr 00:00:00:00:00:00
[ 421.739719] iwlwifi 0000:01:00.0: iwl_sta_ucode_activate Added STA id 148 addr 00:00:00:00:00:00 to uCode
not sure how it happen, but adding the sanity check to prevent memory
corruption
Signed-off-by: Wey-Yi Guy <wey-yi.w.guy@intel.com>
Signed-off-by: John W. Linville <linville@tuxdriver.com>
CWE ID: CWE-119
|
static int iwl_process_add_sta_resp(struct iwl_priv *priv,
struct iwl_addsta_cmd *addsta,
struct iwl_rx_packet *pkt)
{
u8 sta_id = addsta->sta.sta_id;
unsigned long flags;
int ret = -EIO;
if (pkt->hdr.flags & IWL_CMD_FAILED_MSK) {
IWL_ERR(priv, "Bad return from REPLY_ADD_STA (0x%08X)\n",
pkt->hdr.flags);
return ret;
}
IWL_DEBUG_INFO(priv, "Processing response for adding station %u\n",
sta_id);
spin_lock_irqsave(&priv->shrd->sta_lock, flags);
switch (pkt->u.add_sta.status) {
case ADD_STA_SUCCESS_MSK:
IWL_DEBUG_INFO(priv, "REPLY_ADD_STA PASSED\n");
ret = iwl_sta_ucode_activate(priv, sta_id);
break;
case ADD_STA_NO_ROOM_IN_TABLE:
IWL_ERR(priv, "Adding station %d failed, no room in table.\n",
sta_id);
break;
case ADD_STA_NO_BLOCK_ACK_RESOURCE:
IWL_ERR(priv, "Adding station %d failed, no block ack "
"resource.\n", sta_id);
break;
case ADD_STA_MODIFY_NON_EXIST_STA:
IWL_ERR(priv, "Attempting to modify non-existing station %d\n",
sta_id);
break;
default:
IWL_DEBUG_ASSOC(priv, "Received REPLY_ADD_STA:(0x%08X)\n",
pkt->u.add_sta.status);
break;
}
IWL_DEBUG_INFO(priv, "%s station id %u addr %pM\n",
priv->stations[sta_id].sta.mode ==
STA_CONTROL_MODIFY_MSK ? "Modified" : "Added",
sta_id, priv->stations[sta_id].sta.sta.addr);
/*
* XXX: The MAC address in the command buffer is often changed from
* the original sent to the device. That is, the MAC address
* written to the command buffer often is not the same MAC address
* read from the command buffer when the command returns. This
* issue has not yet been resolved and this debugging is left to
* observe the problem.
*/
IWL_DEBUG_INFO(priv, "%s station according to cmd buffer %pM\n",
priv->stations[sta_id].sta.mode ==
STA_CONTROL_MODIFY_MSK ? "Modified" : "Added",
addsta->sta.addr);
spin_unlock_irqrestore(&priv->shrd->sta_lock, flags);
return ret;
}
| 169,868
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jp2_box_put(jp2_box_t *box, jas_stream_t *out)
{
jas_stream_t *tmpstream;
bool extlen;
bool dataflag;
tmpstream = 0;
dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA));
if (dataflag) {
if (!(tmpstream = jas_stream_memopen(0, 0))) {
goto error;
}
if (box->ops->putdata) {
if ((*box->ops->putdata)(box, tmpstream)) {
goto error;
}
}
box->len = jas_stream_tell(tmpstream) + JP2_BOX_HDRLEN(false);
jas_stream_rewind(tmpstream);
}
extlen = (box->len >= (((uint_fast64_t)1) << 32)) != 0;
if (jp2_putuint32(out, extlen ? 1 : box->len)) {
goto error;
}
if (jp2_putuint32(out, box->type)) {
goto error;
}
if (extlen) {
if (jp2_putuint64(out, box->len)) {
goto error;
}
}
if (dataflag) {
if (jas_stream_copy(out, tmpstream, box->len - JP2_BOX_HDRLEN(false))) {
goto error;
}
jas_stream_close(tmpstream);
}
return 0;
error:
if (tmpstream) {
jas_stream_close(tmpstream);
}
return -1;
}
Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder.
Also, added some comments marking I/O stream interfaces that probably
need to be changed (in the long term) to fix integer overflow problems.
CWE ID: CWE-476
|
int jp2_box_put(jp2_box_t *box, jas_stream_t *out)
{
jas_stream_t *tmpstream;
bool extlen;
bool dataflag;
tmpstream = 0;
dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA));
if (dataflag) {
if (!(tmpstream = jas_stream_memopen(0, 0))) {
goto error;
}
if (box->ops->putdata) {
if ((*box->ops->putdata)(box, tmpstream)) {
goto error;
}
}
box->len = jas_stream_tell(tmpstream) + JP2_BOX_HDRLEN(false);
jas_stream_rewind(tmpstream);
}
extlen = (box->len >= (((uint_fast64_t)1) << 32)) != 0;
if (jp2_putuint32(out, extlen ? 1 : box->len)) {
goto error;
}
if (jp2_putuint32(out, box->type)) {
goto error;
}
if (extlen) {
if (jp2_putuint64(out, box->len)) {
goto error;
}
}
if (dataflag) {
if (jas_stream_copy(out, tmpstream, box->len -
JP2_BOX_HDRLEN(false))) {
jas_eprintf("cannot copy box data\n");
goto error;
}
jas_stream_close(tmpstream);
}
return 0;
error:
if (tmpstream) {
jas_stream_close(tmpstream);
}
return -1;
}
| 168,319
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftVPX::outputBufferSafe(OMX_BUFFERHEADERTYPE *outHeader) {
uint32_t width = outputBufferWidth();
uint32_t height = outputBufferHeight();
uint64_t nFilledLen = width;
nFilledLen *= height;
if (nFilledLen > UINT32_MAX / 3) {
ALOGE("b/29421675, nFilledLen overflow %llu w %u h %u", nFilledLen, width, height);
android_errorWriteLog(0x534e4554, "29421675");
return false;
} else if (outHeader->nAllocLen < outHeader->nFilledLen) {
ALOGE("b/27597103, buffer too small");
android_errorWriteLog(0x534e4554, "27597103");
return false;
}
return true;
}
Commit Message: fix build
Change-Id: I9bb8c659d3fc97a8e748451d82d0f3448faa242b
CWE ID: CWE-119
|
bool SoftVPX::outputBufferSafe(OMX_BUFFERHEADERTYPE *outHeader) {
uint32_t width = outputBufferWidth();
uint32_t height = outputBufferHeight();
uint64_t nFilledLen = width;
nFilledLen *= height;
if (nFilledLen > UINT32_MAX / 3) {
ALOGE("b/29421675, nFilledLen overflow %llu w %u h %u",
(unsigned long long)nFilledLen, width, height);
android_errorWriteLog(0x534e4554, "29421675");
return false;
} else if (outHeader->nAllocLen < outHeader->nFilledLen) {
ALOGE("b/27597103, buffer too small");
android_errorWriteLog(0x534e4554, "27597103");
return false;
}
return true;
}
| 173,414
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void AppControllerImpl::GetArcAndroidId(
mojom::AppController::GetArcAndroidIdCallback callback) {
arc::GetAndroidId(base::BindOnce(
[](mojom::AppController::GetArcAndroidIdCallback callback, bool success,
int64_t android_id) {
std::move(callback).Run(success, base::NumberToString(android_id));
},
std::move(callback)));
}
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <michaelpg@chromium.org>
Commit-Queue: Lucas Tenório <ltenorio@chromium.org>
Cr-Commit-Position: refs/heads/master@{#645122}
CWE ID: CWE-416
|
void AppControllerImpl::GetArcAndroidId(
void AppControllerService::GetArcAndroidId(
mojom::AppController::GetArcAndroidIdCallback callback) {
arc::GetAndroidId(base::BindOnce(
[](mojom::AppController::GetArcAndroidIdCallback callback, bool success,
int64_t android_id) {
std::move(callback).Run(success, base::NumberToString(android_id));
},
std::move(callback)));
}
| 172,083
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_file_summary_info(struct magic_set *ms, const cdf_header_t *h,
const cdf_stream_t *sst, const uint64_t clsid[2])
{
cdf_summary_info_header_t si;
cdf_property_info_t *info;
size_t count;
int m;
if (cdf_unpack_summary_info(sst, h, &si, &info, &count) == -1)
return -1;
if (NOTMIME(ms)) {
const char *str;
if (file_printf(ms, "Composite Document File V2 Document")
== -1)
return -1;
if (file_printf(ms, ", %s Endian",
si.si_byte_order == 0xfffe ? "Little" : "Big") == -1)
return -2;
switch (si.si_os) {
case 2:
if (file_printf(ms, ", Os: Windows, Version %d.%d",
si.si_os_version & 0xff,
(uint32_t)si.si_os_version >> 8) == -1)
return -2;
break;
case 1:
if (file_printf(ms, ", Os: MacOS, Version %d.%d",
(uint32_t)si.si_os_version >> 8,
si.si_os_version & 0xff) == -1)
return -2;
break;
default:
if (file_printf(ms, ", Os %d, Version: %d.%d", si.si_os,
si.si_os_version & 0xff,
(uint32_t)si.si_os_version >> 8) == -1)
return -2;
break;
}
str = cdf_clsid_to_mime(clsid, clsid2desc);
if (str)
if (file_printf(ms, ", %s", str) == -1)
return -2;
}
m = cdf_file_property_info(ms, info, count, clsid);
free(info);
return m == -1 ? -2 : m;
}
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_file_summary_info(struct magic_set *ms, const cdf_header_t *h,
const cdf_stream_t *sst, const cdf_directory_t *root_storage)
{
cdf_summary_info_header_t si;
cdf_property_info_t *info;
size_t count;
int m;
if (cdf_unpack_summary_info(sst, h, &si, &info, &count) == -1)
return -1;
if (NOTMIME(ms)) {
const char *str;
if (file_printf(ms, "Composite Document File V2 Document")
== -1)
return -1;
if (file_printf(ms, ", %s Endian",
si.si_byte_order == 0xfffe ? "Little" : "Big") == -1)
return -2;
switch (si.si_os) {
case 2:
if (file_printf(ms, ", Os: Windows, Version %d.%d",
si.si_os_version & 0xff,
(uint32_t)si.si_os_version >> 8) == -1)
return -2;
break;
case 1:
if (file_printf(ms, ", Os: MacOS, Version %d.%d",
(uint32_t)si.si_os_version >> 8,
si.si_os_version & 0xff) == -1)
return -2;
break;
default:
if (file_printf(ms, ", Os %d, Version: %d.%d", si.si_os,
si.si_os_version & 0xff,
(uint32_t)si.si_os_version >> 8) == -1)
return -2;
break;
}
if (root_storage) {
str = cdf_clsid_to_mime(root_storage->d_storage_uuid, clsid2desc);
if (str)
if (file_printf(ms, ", %s", str) == -1)
return -2;
}
}
m = cdf_file_property_info(ms, info, count, root_storage);
free(info);
return m == -1 ? -2 : m;
}
| 166,446
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jpc_qmfb_join_colgrp(jpc_fix_t *a, int numrows, int stride,
int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE];
jpc_fix_t *buf = joinbuf;
jpc_fix_t *srcptr;
jpc_fix_t *dstptr;
register jpc_fix_t *srcptr2;
register jpc_fix_t *dstptr2;
register int n;
register int i;
int hstartcol;
/* Allocate memory for the join buffer from the heap. */
if (bufsize > QMFB_JOINBUFSIZE) {
if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide. */
abort();
}
}
hstartcol = (numrows + 1 - parity) >> 1;
/* Save the samples from the lowpass channel. */
n = hstartcol;
srcptr = &a[0];
dstptr = buf;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
srcptr += stride;
dstptr += JPC_QMFB_COLGRPSIZE;
}
/* Copy the samples from the highpass channel into place. */
srcptr = &a[hstartcol * stride];
dstptr = &a[(1 - parity) * stride];
n = numrows - hstartcol;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += 2 * stride;
srcptr += stride;
}
/* Copy the samples from the lowpass channel into place. */
srcptr = buf;
dstptr = &a[parity * stride];
n = hstartcol;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += 2 * stride;
srcptr += JPC_QMFB_COLGRPSIZE;
}
/* If the join buffer was allocated on the heap, free this memory. */
if (buf != joinbuf) {
jas_free(buf);
}
}
Commit Message: Fixed a buffer overrun problem in the QMFB code in the JPC codec
that was caused by a buffer being allocated with a size that was too small
in some cases.
Added a new regression test case.
CWE ID: CWE-119
|
void jpc_qmfb_join_colgrp(jpc_fix_t *a, int numrows, int stride,
int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE];
jpc_fix_t *buf = joinbuf;
jpc_fix_t *srcptr;
jpc_fix_t *dstptr;
register jpc_fix_t *srcptr2;
register jpc_fix_t *dstptr2;
register int n;
register int i;
int hstartcol;
/* Allocate memory for the join buffer from the heap. */
if (bufsize > QMFB_JOINBUFSIZE) {
if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE,
sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide. */
abort();
}
}
hstartcol = (numrows + 1 - parity) >> 1;
/* Save the samples from the lowpass channel. */
n = hstartcol;
srcptr = &a[0];
dstptr = buf;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
srcptr += stride;
dstptr += JPC_QMFB_COLGRPSIZE;
}
/* Copy the samples from the highpass channel into place. */
srcptr = &a[hstartcol * stride];
dstptr = &a[(1 - parity) * stride];
n = numrows - hstartcol;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += 2 * stride;
srcptr += stride;
}
/* Copy the samples from the lowpass channel into place. */
srcptr = buf;
dstptr = &a[parity * stride];
n = hstartcol;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += 2 * stride;
srcptr += JPC_QMFB_COLGRPSIZE;
}
/* If the join buffer was allocated on the heap, free this memory. */
if (buf != joinbuf) {
jas_free(buf);
}
}
| 169,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: image_transform_png_set_strip_16_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
if (that->bit_depth == 16)
{
that->sample_depth = that->bit_depth = 8;
if (that->red_sBIT > 8) that->red_sBIT = 8;
if (that->green_sBIT > 8) that->green_sBIT = 8;
if (that->blue_sBIT > 8) that->blue_sBIT = 8;
if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
/* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this
* configuration option is set. From 1.5.4 the flag is never set and the
* 'scale' API (above) must be used.
*/
# ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED
# if PNG_LIBPNG_VER >= 10504
# error PNG_READ_ACCURATE_SCALE should not be set
# endif
/* The strip 16 algorithm drops the low 8 bits rather than calculating
* 1/257, so we need to adjust the permitted errors appropriately:
* Notice that this is only relevant prior to the addition of the
* png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!)
*/
{
PNG_CONST double d = (255-128.5)/65535;
that->rede += d;
that->greene += d;
that->bluee += d;
that->alphae += d;
}
# endif
}
this->next->mod(this->next, that, pp, display);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
image_transform_png_set_strip_16_mod(PNG_CONST image_transform *this,
image_transform_png_set_strip_16_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth == 16)
{
that->sample_depth = that->bit_depth = 8;
if (that->red_sBIT > 8) that->red_sBIT = 8;
if (that->green_sBIT > 8) that->green_sBIT = 8;
if (that->blue_sBIT > 8) that->blue_sBIT = 8;
if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
/* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this
* configuration option is set. From 1.5.4 the flag is never set and the
* 'scale' API (above) must be used.
*/
# ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED
# if PNG_LIBPNG_VER >= 10504
# error PNG_READ_ACCURATE_SCALE should not be set
# endif
/* The strip 16 algorithm drops the low 8 bits rather than calculating
* 1/257, so we need to adjust the permitted errors appropriately:
* Notice that this is only relevant prior to the addition of the
* png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!)
*/
{
const double d = (255-128.5)/65535;
that->rede += d;
that->greene += d;
that->bluee += d;
that->alphae += d;
}
# endif
}
this->next->mod(this->next, that, pp, display);
}
| 173,649
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sum_update(const char *p, int32 len)
{
switch (cursum_type) {
case CSUM_MD5:
md5_update(&md, (uchar *)p, len);
break;
case CSUM_MD4:
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
if (len + sumresidue < CSUM_CHUNK) {
memcpy(md.buffer + sumresidue, p, len);
sumresidue += len;
}
if (sumresidue) {
int32 i = CSUM_CHUNK - sumresidue;
memcpy(md.buffer + sumresidue, p, i);
mdfour_update(&md, (uchar *)md.buffer, CSUM_CHUNK);
len -= i;
p += i;
}
while (len >= CSUM_CHUNK) {
mdfour_update(&md, (uchar *)p, CSUM_CHUNK);
len -= CSUM_CHUNK;
p += CSUM_CHUNK;
}
sumresidue = len;
if (sumresidue)
memcpy(md.buffer, p, sumresidue);
break;
case CSUM_NONE:
break;
}
}
Commit Message:
CWE ID: CWE-354
|
void sum_update(const char *p, int32 len)
{
switch (cursum_type) {
case CSUM_MD5:
md5_update(&md, (uchar *)p, len);
break;
case CSUM_MD4:
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
case CSUM_MD4_ARCHAIC:
if (len + sumresidue < CSUM_CHUNK) {
memcpy(md.buffer + sumresidue, p, len);
sumresidue += len;
}
if (sumresidue) {
int32 i = CSUM_CHUNK - sumresidue;
memcpy(md.buffer + sumresidue, p, i);
mdfour_update(&md, (uchar *)md.buffer, CSUM_CHUNK);
len -= i;
p += i;
}
while (len >= CSUM_CHUNK) {
mdfour_update(&md, (uchar *)p, CSUM_CHUNK);
len -= CSUM_CHUNK;
p += CSUM_CHUNK;
}
sumresidue = len;
if (sumresidue)
memcpy(md.buffer, p, sumresidue);
break;
case CSUM_NONE:
break;
}
}
| 164,640
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
{
struct sockaddr_rc *sa = (struct sockaddr_rc *) addr;
struct sock *sk = sock->sk;
int chan = sa->rc_channel;
int err = 0;
BT_DBG("sk %p %pMR", sk, &sa->rc_bdaddr);
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state != BT_OPEN) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
write_lock(&rfcomm_sk_list.lock);
if (chan && __rfcomm_get_listen_sock_by_addr(chan, &sa->rc_bdaddr)) {
err = -EADDRINUSE;
} else {
/* Save source address */
bacpy(&rfcomm_pi(sk)->src, &sa->rc_bdaddr);
rfcomm_pi(sk)->channel = chan;
sk->sk_state = BT_BOUND;
}
write_unlock(&rfcomm_sk_list.lock);
done:
release_sock(sk);
return err;
}
Commit Message: Bluetooth: Fix potential NULL dereference in RFCOMM bind callback
addr can be NULL and it should not be dereferenced before NULL checking.
Signed-off-by: Jaganath Kanakkassery <jaganath.k@samsung.com>
Signed-off-by: Marcel Holtmann <marcel@holtmann.org>
CWE ID: CWE-476
|
static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
{
struct sockaddr_rc sa;
struct sock *sk = sock->sk;
int len, err = 0;
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
memset(&sa, 0, sizeof(sa));
len = min_t(unsigned int, sizeof(sa), addr_len);
memcpy(&sa, addr, len);
BT_DBG("sk %p %pMR", sk, &sa.rc_bdaddr);
lock_sock(sk);
if (sk->sk_state != BT_OPEN) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
write_lock(&rfcomm_sk_list.lock);
if (sa.rc_channel &&
__rfcomm_get_listen_sock_by_addr(sa.rc_channel, &sa.rc_bdaddr)) {
err = -EADDRINUSE;
} else {
/* Save source address */
bacpy(&rfcomm_pi(sk)->src, &sa.rc_bdaddr);
rfcomm_pi(sk)->channel = sa.rc_channel;
sk->sk_state = BT_BOUND;
}
write_unlock(&rfcomm_sk_list.lock);
done:
release_sock(sk);
return err;
}
| 167,466
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ixheaacd_complex_anal_filt(ia_esbr_hbe_txposer_struct *ptr_hbe_txposer) {
WORD32 idx;
WORD32 anal_size = 2 * ptr_hbe_txposer->synth_size;
WORD32 N = (10 * anal_size);
for (idx = 0; idx < (ptr_hbe_txposer->no_bins >> 1); idx++) {
WORD32 i, j, k, l;
FLOAT32 window_output[640];
FLOAT32 u[128], u_in[256], u_out[256];
FLOAT32 accu_r, accu_i;
const FLOAT32 *inp_signal;
FLOAT32 *anal_buf;
FLOAT32 *analy_cos_sin_tab = ptr_hbe_txposer->analy_cos_sin_tab;
const FLOAT32 *interp_window_coeff = ptr_hbe_txposer->analy_wind_coeff;
FLOAT32 *x = ptr_hbe_txposer->analy_buf;
memset(ptr_hbe_txposer->qmf_in_buf[idx + HBE_OPER_WIN_LEN - 1], 0,
TWICE_QMF_SYNTH_CHANNELS_NUM * sizeof(FLOAT32));
inp_signal = ptr_hbe_txposer->ptr_input_buf +
idx * 2 * ptr_hbe_txposer->synth_size + 1;
anal_buf = &ptr_hbe_txposer->qmf_in_buf[idx + HBE_OPER_WIN_LEN - 1]
[4 * ptr_hbe_txposer->k_start];
for (i = N - 1; i >= anal_size; i--) {
x[i] = x[i - anal_size];
}
for (i = anal_size - 1; i >= 0; i--) {
x[i] = inp_signal[anal_size - 1 - i];
}
for (i = 0; i < N; i++) {
window_output[i] = x[i] * interp_window_coeff[i];
}
for (i = 0; i < 2 * anal_size; i++) {
accu_r = 0.0;
for (j = 0; j < 5; j++) {
accu_r = accu_r + window_output[i + j * 2 * anal_size];
}
u[i] = accu_r;
}
if (anal_size == 40) {
for (i = 1; i < anal_size; i++) {
FLOAT32 temp1 = u[i] + u[2 * anal_size - i];
FLOAT32 temp2 = u[i] - u[2 * anal_size - i];
u[i] = temp1;
u[2 * anal_size - i] = temp2;
}
for (k = 0; k < anal_size; k++) {
accu_r = u[anal_size];
if (k & 1)
accu_i = u[0];
else
accu_i = -u[0];
for (l = 1; l < anal_size; l++) {
accu_r = accu_r + u[0 + l] * analy_cos_sin_tab[2 * l + 0];
accu_i = accu_i + u[2 * anal_size - l] * analy_cos_sin_tab[2 * l + 1];
}
analy_cos_sin_tab += (2 * anal_size);
*anal_buf++ = (FLOAT32)accu_r;
*anal_buf++ = (FLOAT32)accu_i;
}
} else {
FLOAT32 *ptr_u = u_in;
FLOAT32 *ptr_v = u_out;
for (k = 0; k < anal_size * 2; k++) {
*ptr_u++ = ((*analy_cos_sin_tab++) * u[k]);
*ptr_u++ = ((*analy_cos_sin_tab++) * u[k]);
}
if (ixheaacd_cmplx_anal_fft != NULL)
(*ixheaacd_cmplx_anal_fft)(u_in, u_out, anal_size * 2);
else
return -1;
for (k = 0; k < anal_size / 2; k++) {
*(anal_buf + 1) = -*ptr_v++;
*anal_buf = *ptr_v++;
anal_buf += 2;
*(anal_buf + 1) = *ptr_v++;
*anal_buf = -*ptr_v++;
anal_buf += 2;
}
}
}
return 0;
}
Commit Message: Fix for stack corruption in esbr
Bug: 110769924
Test: poc from bug before/after
Change-Id: I99c6e89902064849ea1310c271064bdeccf7f20e
(cherry picked from commit 7e90d745c22695236437297cd8167a9312427a4a)
(cherry picked from commit 5464927f0c1fc721fa03d1c5be77b0b43dfffc50)
CWE ID: CWE-787
|
WORD32 ixheaacd_complex_anal_filt(ia_esbr_hbe_txposer_struct *ptr_hbe_txposer) {
WORD32 idx;
WORD32 anal_size = 2 * ptr_hbe_txposer->synth_size;
WORD32 N = (10 * anal_size);
for (idx = 0; idx < (ptr_hbe_txposer->no_bins >> 1); idx++) {
WORD32 i, j, k, l;
FLOAT32 window_output[640];
FLOAT32 u[128], u_in[256], u_out[256];
FLOAT32 accu_r, accu_i;
const FLOAT32 *inp_signal;
FLOAT32 *anal_buf;
FLOAT32 *analy_cos_sin_tab = ptr_hbe_txposer->analy_cos_sin_tab;
const FLOAT32 *interp_window_coeff = ptr_hbe_txposer->analy_wind_coeff;
FLOAT32 *x = ptr_hbe_txposer->analy_buf;
memset(ptr_hbe_txposer->qmf_in_buf[idx + HBE_OPER_WIN_LEN - 1], 0,
TWICE_QMF_SYNTH_CHANNELS_NUM * sizeof(FLOAT32));
inp_signal = ptr_hbe_txposer->ptr_input_buf +
idx * 2 * ptr_hbe_txposer->synth_size + 1;
anal_buf = &ptr_hbe_txposer->qmf_in_buf[idx + HBE_OPER_WIN_LEN - 1]
[4 * ptr_hbe_txposer->k_start];
for (i = N - 1; i >= anal_size; i--) {
x[i] = x[i - anal_size];
}
for (i = anal_size - 1; i >= 0; i--) {
x[i] = inp_signal[anal_size - 1 - i];
}
for (i = 0; i < N; i++) {
window_output[i] = x[i] * interp_window_coeff[i];
}
for (i = 0; i < 2 * anal_size; i++) {
accu_r = 0.0;
for (j = 0; j < 5; j++) {
accu_r = accu_r + window_output[i + j * 2 * anal_size];
}
u[i] = accu_r;
}
if (anal_size == 40) {
for (i = 1; i < anal_size; i++) {
FLOAT32 temp1 = u[i] + u[2 * anal_size - i];
FLOAT32 temp2 = u[i] - u[2 * anal_size - i];
u[i] = temp1;
u[2 * anal_size - i] = temp2;
}
for (k = 0; k < anal_size; k++) {
accu_r = u[anal_size];
if (k & 1)
accu_i = u[0];
else
accu_i = -u[0];
for (l = 1; l < anal_size; l++) {
accu_r = accu_r + u[0 + l] * analy_cos_sin_tab[2 * l + 0];
accu_i = accu_i + u[2 * anal_size - l] * analy_cos_sin_tab[2 * l + 1];
}
analy_cos_sin_tab += (2 * anal_size);
*anal_buf++ = (FLOAT32)accu_r;
*anal_buf++ = (FLOAT32)accu_i;
}
} else {
FLOAT32 *ptr_u = u_in;
FLOAT32 *ptr_v = u_out;
for (k = 0; k < anal_size * 2; k++) {
*ptr_u++ = ((*analy_cos_sin_tab++) * u[k]);
*ptr_u++ = ((*analy_cos_sin_tab++) * u[k]);
}
if (ptr_hbe_txposer->ixheaacd_cmplx_anal_fft != NULL)
(*(ptr_hbe_txposer->ixheaacd_cmplx_anal_fft))(u_in, u_out,
anal_size * 2);
else
return -1;
for (k = 0; k < anal_size / 2; k++) {
*(anal_buf + 1) = -*ptr_v++;
*anal_buf = *ptr_v++;
anal_buf += 2;
*(anal_buf + 1) = *ptr_v++;
*anal_buf = -*ptr_v++;
anal_buf += 2;
}
}
}
return 0;
}
| 174,090
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sycc422_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b;
const int *y, *cb, *cr;
unsigned int maxw, maxh, max;
int offset, upb;
unsigned int i, j;
upb = (int)img->comps[0].prec;
offset = 1<<(upb - 1); upb = (1<<upb)-1;
maxw = (unsigned int)img->comps[0].w; maxh = (unsigned int)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)malloc(sizeof(int) * (size_t)max);
d1 = g = (int*)malloc(sizeof(int) * (size_t)max);
d2 = b = (int*)malloc(sizeof(int) * (size_t)max);
if(r == NULL || g == NULL || b == NULL) goto fails;
for(i=0U; i < maxh; ++i)
{
for(j=0U; j < (maxw & ~(unsigned int)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
if (j < maxw) {
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
}
free(img->comps[0].data); img->comps[0].data = d0;
free(img->comps[1].data); img->comps[1].data = d1;
free(img->comps[2].data); img->comps[2].data = d2;
#if defined(USE_JPWL) || defined(USE_MJ2)
img->comps[1].w = maxw; img->comps[1].h = maxh;
img->comps[2].w = maxw; img->comps[2].h = maxh;
#else
img->comps[1].w = (OPJ_UINT32)maxw; img->comps[1].h = (OPJ_UINT32)maxh;
img->comps[2].w = (OPJ_UINT32)maxw; img->comps[2].h = (OPJ_UINT32)maxh;
#endif
img->comps[1].dx = img->comps[0].dx;
img->comps[2].dx = img->comps[0].dx;
img->comps[1].dy = img->comps[0].dy;
img->comps[2].dy = img->comps[0].dy;
return;
fails:
if(r) free(r);
if(g) free(g);
if(b) free(b);
}/* sycc422_to_rgb() */
Commit Message: Fix Out-Of-Bounds Read in sycc42x_to_rgb function (#745)
42x Images with an odd x0/y0 lead to subsampled component starting at the
2nd column/line.
That is offset = comp->dx * comp->x0 - image->x0 = 1
Fix #726
CWE ID: CWE-125
|
static void sycc422_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b;
const int *y, *cb, *cr;
size_t maxw, maxh, max, offx, loopmaxw;
int offset, upb;
size_t i;
upb = (int)img->comps[0].prec;
offset = 1<<(upb - 1); upb = (1<<upb)-1;
maxw = (size_t)img->comps[0].w; maxh = (size_t)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)malloc(sizeof(int) * max);
d1 = g = (int*)malloc(sizeof(int) * max);
d2 = b = (int*)malloc(sizeof(int) * max);
if(r == NULL || g == NULL || b == NULL) goto fails;
/* if img->x0 is odd, then first column shall use Cb/Cr = 0 */
offx = img->x0 & 1U;
loopmaxw = maxw - offx;
for(i=0U; i < maxh; ++i)
{
size_t j;
if (offx > 0U) {
sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b);
++y; ++r; ++g; ++b;
}
for(j=0U; j < (loopmaxw & ~(size_t)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
if (j < loopmaxw) {
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
}
free(img->comps[0].data); img->comps[0].data = d0;
free(img->comps[1].data); img->comps[1].data = d1;
free(img->comps[2].data); img->comps[2].data = d2;
img->comps[1].w = img->comps[2].w = img->comps[0].w;
img->comps[1].h = img->comps[2].h = img->comps[0].h;
img->comps[1].dx = img->comps[2].dx = img->comps[0].dx;
img->comps[1].dy = img->comps[2].dy = img->comps[0].dy;
img->color_space = OPJ_CLRSPC_SRGB;
return;
fails:
free(r);
free(g);
free(b);
}/* sycc422_to_rgb() */
| 168,840
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller)
{
tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size);
PrintOutParsingResult(res, 1, caller);
return res;
}
Commit Message: NetKVM: BZ#1169718: Checking the length only on read
Signed-off-by: Joseph Hindin <yhindin@rehat.com>
CWE ID: CWE-20
|
tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller)
tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, BOOLEAN verifyLength, LPCSTR caller)
{
tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size, verifyLength);
PrintOutParsingResult(res, 1, caller);
return res;
}
| 170,144
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 fsmMkfile(rpmfi fi, const char *dest, rpmfiles files,
rpmpsm psm, int nodigest, int *setmeta,
int * firsthardlink)
{
int rc = 0;
int numHardlinks = rpmfiFNlink(fi);
if (numHardlinks > 1) {
/* Create first hardlinked file empty */
if (*firsthardlink < 0) {
*firsthardlink = rpmfiFX(fi);
rc = expandRegular(fi, dest, psm, nodigest, 1);
} else {
/* Create hard links for others */
char *fn = rpmfilesFN(files, *firsthardlink);
rc = link(fn, dest);
if (rc < 0) {
rc = RPMERR_LINK_FAILED;
}
free(fn);
}
}
/* Write normal files or fill the last hardlinked (already
existing) file with content */
if (numHardlinks<=1) {
if (!rc)
rc = expandRegular(fi, dest, psm, nodigest, 0);
} else if (rpmfiArchiveHasContent(fi)) {
if (!rc)
rc = expandRegular(fi, dest, psm, nodigest, 0);
*firsthardlink = -1;
} else {
*setmeta = 0;
}
return rc;
}
Commit Message: Don't follow symlinks on file creation (CVE-2017-7501)
Open newly created files with O_EXCL to prevent symlink tricks.
When reopening hardlinks for writing the actual content, use append
mode instead. This is compatible with the write-only permissions but
is not destructive in case we got redirected to somebody elses file,
verify the target before actually writing anything.
As these are files with the temporary suffix, errors mean a local
user with sufficient privileges to break the installation of the package
anyway is trying to goof us on purpose, don't bother trying to mend it
(we couldn't fix the hardlink case anyhow) but just bail out.
Based on a patch by Florian Festi.
CWE ID: CWE-59
|
static int fsmMkfile(rpmfi fi, const char *dest, rpmfiles files,
rpmpsm psm, int nodigest, int *setmeta,
int * firsthardlink)
{
int rc = 0;
int numHardlinks = rpmfiFNlink(fi);
if (numHardlinks > 1) {
/* Create first hardlinked file empty */
if (*firsthardlink < 0) {
*firsthardlink = rpmfiFX(fi);
rc = expandRegular(fi, dest, psm, 1, nodigest, 1);
} else {
/* Create hard links for others */
char *fn = rpmfilesFN(files, *firsthardlink);
rc = link(fn, dest);
if (rc < 0) {
rc = RPMERR_LINK_FAILED;
}
free(fn);
}
}
/* Write normal files or fill the last hardlinked (already
existing) file with content */
if (numHardlinks<=1) {
if (!rc)
rc = expandRegular(fi, dest, psm, 1, nodigest, 0);
} else if (rpmfiArchiveHasContent(fi)) {
if (!rc)
rc = expandRegular(fi, dest, psm, 0, nodigest, 0);
*firsthardlink = -1;
} else {
*setmeta = 0;
}
return rc;
}
| 168,268
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ping_unhash(struct sock *sk)
{
struct inet_sock *isk = inet_sk(sk);
pr_debug("ping_unhash(isk=%p,isk->num=%u)\n", isk, isk->inet_num);
if (sk_hashed(sk)) {
write_lock_bh(&ping_table.lock);
hlist_nulls_del(&sk->sk_nulls_node);
sock_put(sk);
isk->inet_num = 0;
isk->inet_sport = 0;
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
write_unlock_bh(&ping_table.lock);
}
}
Commit Message: ipv4: Missing sk_nulls_node_init() in ping_unhash().
If we don't do that, then the poison value is left in the ->pprev
backlink.
This can cause crashes if we do a disconnect, followed by a connect().
Tested-by: Linus Torvalds <torvalds@linux-foundation.org>
Reported-by: Wen Xu <hotdog3645@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID:
|
void ping_unhash(struct sock *sk)
{
struct inet_sock *isk = inet_sk(sk);
pr_debug("ping_unhash(isk=%p,isk->num=%u)\n", isk, isk->inet_num);
if (sk_hashed(sk)) {
write_lock_bh(&ping_table.lock);
hlist_nulls_del(&sk->sk_nulls_node);
sk_nulls_node_init(&sk->sk_nulls_node);
sock_put(sk);
isk->inet_num = 0;
isk->inet_sport = 0;
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
write_unlock_bh(&ping_table.lock);
}
}
| 166,623
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: TestJavaScriptDialogManager()
: is_fullscreen_(false), message_loop_runner_(new MessageLoopRunner) {}
Commit Message: If a page shows a popup, end fullscreen.
This was implemented in Blink r159834, but it is susceptible
to a popup/fullscreen race. This CL reverts that implementation
and re-implements it in WebContents.
BUG=752003
TEST=WebContentsImplBrowserTest.PopupsFromJavaScriptEndFullscreen
Change-Id: Ia345cdeda273693c3231ad8f486bebfc3d83927f
Reviewed-on: https://chromium-review.googlesource.com/606987
Commit-Queue: Avi Drissman <avi@chromium.org>
Reviewed-by: Charlie Reis <creis@chromium.org>
Reviewed-by: Philip Jägenstedt <foolip@chromium.org>
Cr-Commit-Position: refs/heads/master@{#498171}
CWE ID: CWE-20
|
TestJavaScriptDialogManager()
TestWCDelegateForDialogsAndFullscreen()
: is_fullscreen_(false), message_loop_runner_(new MessageLoopRunner) {}
| 172,951
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MemBackendImpl::EvictIfNeeded() {
if (current_size_ <= max_size_)
return;
int target_size = std::max(0, max_size_ - kDefaultEvictionSize);
base::LinkNode<MemEntryImpl>* entry = lru_list_.head();
while (current_size_ > target_size && entry != lru_list_.end()) {
MemEntryImpl* to_doom = entry->value();
do {
entry = entry->next();
} while (entry != lru_list_.end() && entry->value()->parent() == to_doom);
if (!to_doom->InUse())
to_doom->Doom();
}
}
Commit Message: [MemCache] Fix bug while iterating LRU list in range doom
This is exact same thing as https://chromium-review.googlesource.com/c/chromium/src/+/987919
but on explicit mass-erase rather than eviction.
Thanks to nedwilliamson@ (on gmail) for the report and testcase.
Bug: 831963
Change-Id: I96a46700c1f058f7feebe038bcf983dc40eb7102
Reviewed-on: https://chromium-review.googlesource.com/1014023
Commit-Queue: Maks Orlovich <morlovich@chromium.org>
Reviewed-by: Josh Karlin <jkarlin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#551205}
CWE ID: CWE-416
|
void MemBackendImpl::EvictIfNeeded() {
if (current_size_ <= max_size_)
return;
int target_size = std::max(0, max_size_ - kDefaultEvictionSize);
base::LinkNode<MemEntryImpl>* entry = lru_list_.head();
while (current_size_ > target_size && entry != lru_list_.end()) {
MemEntryImpl* to_doom = entry->value();
entry = NextSkippingChildren(lru_list_, entry);
if (!to_doom->InUse())
to_doom->Doom();
}
}
| 173,258
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: vcard_apdu_new(unsigned char *raw_apdu, int len, vcard_7816_status_t *status)
{
VCardAPDU *new_apdu;
*status = VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE;
if (len < 4) {
*status = VCARD7816_STATUS_ERROR_WRONG_LENGTH;
return NULL;
}
new_apdu = g_new(VCardAPDU, 1);
new_apdu->a_data = g_memdup(raw_apdu, len);
new_apdu->a_len = len;
*status = vcard_apdu_set_class(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
g_free(new_apdu);
return NULL;
}
*status = vcard_apdu_set_length(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
g_free(new_apdu);
new_apdu = NULL;
}
return new_apdu;
}
Commit Message:
CWE ID: CWE-772
|
vcard_apdu_new(unsigned char *raw_apdu, int len, vcard_7816_status_t *status)
{
VCardAPDU *new_apdu;
*status = VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE;
if (len < 4) {
*status = VCARD7816_STATUS_ERROR_WRONG_LENGTH;
return NULL;
}
new_apdu = g_new(VCardAPDU, 1);
new_apdu->a_data = g_memdup(raw_apdu, len);
new_apdu->a_len = len;
*status = vcard_apdu_set_class(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
vcard_apdu_delete(new_apdu);
return NULL;
}
*status = vcard_apdu_set_length(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
vcard_apdu_delete(new_apdu);
new_apdu = NULL;
}
return new_apdu;
}
| 164,941
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: apr_status_t h2_stream_add_header(h2_stream *stream,
const char *name, size_t nlen,
const char *value, size_t vlen)
{
ap_assert(stream);
if (!stream->has_response) {
if (name[0] == ':') {
if ((vlen) > stream->session->s->limit_req_line) {
/* pseudo header: approximation of request line size check */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): pseudo header %s too long",
stream->session->id, stream->id, name);
return h2_stream_set_error(stream,
HTTP_REQUEST_URI_TOO_LARGE);
}
}
else if ((nlen + 2 + vlen) > stream->session->s->limit_req_fieldsize) {
/* header too long */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): header %s too long",
stream->session->id, stream->id, name);
return h2_stream_set_error(stream,
HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE);
}
if (name[0] != ':') {
++stream->request_headers_added;
if (stream->request_headers_added
> stream->session->s->limit_req_fields) {
/* too many header lines */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): too many header lines",
stream->session->id, stream->id);
return h2_stream_set_error(stream,
HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE);
}
}
}
if (h2_stream_is_scheduled(stream)) {
return add_trailer(stream, name, nlen, value, vlen);
}
else {
if (!stream->rtmp) {
stream->rtmp = h2_req_create(stream->id, stream->pool,
NULL, NULL, NULL, NULL, NULL, 0);
}
if (stream->state != H2_STREAM_ST_OPEN) {
return APR_ECONNRESET;
}
return h2_request_add_header(stream->rtmp, stream->pool,
name, nlen, value, vlen);
}
}
Commit Message: SECURITY: CVE-2016-8740
mod_http2: properly crafted, endless HTTP/2 CONTINUATION frames could be used to exhaust all server's memory.
Reported by: Naveen Tiwari <naveen.tiwari@asu.edu> and CDF/SEFCOM at Arizona State University
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1772576 13f79535-47bb-0310-9956-ffa450edef68
CWE ID: CWE-20
|
apr_status_t h2_stream_add_header(h2_stream *stream,
const char *name, size_t nlen,
const char *value, size_t vlen)
{
int error = 0;
ap_assert(stream);
if (stream->has_response) {
return APR_EINVAL;
}
++stream->request_headers_added;
if (name[0] == ':') {
if ((vlen) > stream->session->s->limit_req_line) {
/* pseudo header: approximation of request line size check */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): pseudo header %s too long",
stream->session->id, stream->id, name);
error = HTTP_REQUEST_URI_TOO_LARGE;
}
}
else if ((nlen + 2 + vlen) > stream->session->s->limit_req_fieldsize) {
/* header too long */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): header %s too long",
stream->session->id, stream->id, name);
error = HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE;
}
if (stream->request_headers_added
> stream->session->s->limit_req_fields + 4) {
/* too many header lines, include 4 pseudo headers */
if (stream->request_headers_added
> stream->session->s->limit_req_fields + 4 + 100) {
/* yeah, right */
return APR_ECONNRESET;
}
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): too many header lines",
stream->session->id, stream->id);
error = HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE;
}
if (h2_stream_is_scheduled(stream)) {
return add_trailer(stream, name, nlen, value, vlen);
}
else if (error) {
return h2_stream_set_error(stream, error);
}
else {
if (!stream->rtmp) {
stream->rtmp = h2_req_create(stream->id, stream->pool,
NULL, NULL, NULL, NULL, NULL, 0);
}
if (stream->state != H2_STREAM_ST_OPEN) {
return APR_ECONNRESET;
}
return h2_request_add_header(stream->rtmp, stream->pool,
name, nlen, value, vlen);
}
}
| 166,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 Image *ReadFAXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
/*
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.
*/
image->storage_class=PseudoClass;
if (image->columns == 0)
image->columns=2592;
if (image->rows == 0)
image->rows=3508;
image->depth=8;
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Monochrome colormap.
*/
image->colormap[0].red=QuantumRange;
image->colormap[0].green=QuantumRange;
image->colormap[0].blue=QuantumRange;
image->colormap[1].red=(Quantum) 0;
image->colormap[1].green=(Quantum) 0;
image->colormap[1].blue=(Quantum) 0;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=HuffmanDecodeImage(image);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
|
static Image *ReadFAXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
/*
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.
*/
image->storage_class=PseudoClass;
if (image->columns == 0)
image->columns=2592;
if (image->rows == 0)
image->rows=3508;
image->depth=8;
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Monochrome colormap.
*/
image->colormap[0].red=QuantumRange;
image->colormap[0].green=QuantumRange;
image->colormap[0].blue=QuantumRange;
image->colormap[1].red=(Quantum) 0;
image->colormap[1].green=(Quantum) 0;
image->colormap[1].blue=(Quantum) 0;
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));
}
status=HuffmanDecodeImage(image);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,564
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: vips_foreign_load_start( VipsImage *out, void *a, void *b )
{
VipsForeignLoad *load = VIPS_FOREIGN_LOAD( b );
VipsForeignLoadClass *class = VIPS_FOREIGN_LOAD_GET_CLASS( load );
if( !load->real ) {
if( !(load->real = vips_foreign_load_temp( load )) )
return( NULL );
#ifdef DEBUG
printf( "vips_foreign_load_start: triggering ->load()\n" );
#endif /*DEBUG*/
/* Read the image in. This may involve a long computation and
* will finish with load->real holding the decompressed image.
*
* We want our caller to be able to see this computation on
* @out, so eval signals on ->real need to appear on ->out.
*/
load->real->progress_signal = load->out;
/* Note the load object on the image. Loaders can use
* this to signal invalidate if they hit a load error. See
* vips_foreign_load_invalidate() below.
*/
g_object_set_qdata( G_OBJECT( load->real ),
vips__foreign_load_operation, load );
if( class->load( load ) ||
vips_image_pio_input( load->real ) )
return( NULL );
/* ->header() read the header into @out, load has read the
* image into @real. They must match exactly in size, bands,
* format and coding for the copy to work.
*
* Some versions of ImageMagick give different results between
* Ping and Load for some formats, for example.
*/
if( !vips_foreign_load_iscompat( load->real, out ) )
return( NULL );
/* We have to tell vips that out depends on real. We've set
* the demand hint below, but not given an input there.
*/
vips_image_pipelinev( load->out, load->out->dhint,
load->real, NULL );
}
return( vips_region_new( load->real ) );
}
Commit Message: fix a crash with delayed load
If a delayed load failed, it could leave the pipeline only half-set up.
Sebsequent threads could then segv.
Set a load-has-failed flag and test before generate.
See https://github.com/jcupitt/libvips/issues/893
CWE ID: CWE-362
|
vips_foreign_load_start( VipsImage *out, void *a, void *b )
{
VipsForeignLoad *load = VIPS_FOREIGN_LOAD( b );
VipsForeignLoadClass *class = VIPS_FOREIGN_LOAD_GET_CLASS( load );
/* If this start has failed before in another thread, we can fail now.
*/
if( load->error )
return( NULL );
if( !load->real ) {
if( !(load->real = vips_foreign_load_temp( load )) )
return( NULL );
#ifdef DEBUG
printf( "vips_foreign_load_start: triggering ->load()\n" );
#endif /*DEBUG*/
/* Read the image in. This may involve a long computation and
* will finish with load->real holding the decompressed image.
*
* We want our caller to be able to see this computation on
* @out, so eval signals on ->real need to appear on ->out.
*/
load->real->progress_signal = load->out;
/* Note the load object on the image. Loaders can use
* this to signal invalidate if they hit a load error. See
* vips_foreign_load_invalidate() below.
*/
g_object_set_qdata( G_OBJECT( load->real ),
vips__foreign_load_operation, load );
/* Load the image and check the result.
*
* ->header() read the header into @out, load has read the
* image into @real. They must match exactly in size, bands,
* format and coding for the copy to work.
*
* Some versions of ImageMagick give different results between
* Ping and Load for some formats, for example.
*
* If the load fails, we need to stop
*/
if( class->load( load ) ||
vips_image_pio_input( load->real ) ||
vips_foreign_load_iscompat( load->real, out ) ) {
vips_operation_invalidate( VIPS_OPERATION( load ) );
load->error = TRUE;
return( NULL );
}
/* We have to tell vips that out depends on real. We've set
* the demand hint below, but not given an input there.
*/
vips_image_pipelinev( load->out, load->out->dhint,
load->real, NULL );
}
return( vips_region_new( load->real ) );
}
| 169,304
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE omx_video::get_config(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_INDEXTYPE configIndex,
OMX_INOUT OMX_PTR configData)
{
(void)hComp;
if (configData == NULL) {
DEBUG_PRINT_ERROR("ERROR: param is null");
return OMX_ErrorBadParameter;
}
if (m_state == OMX_StateInvalid) {
DEBUG_PRINT_ERROR("ERROR: can't be in invalid state");
return OMX_ErrorIncorrectStateOperation;
}
switch ((int)configIndex) {
case OMX_IndexConfigVideoBitrate:
{
OMX_VIDEO_CONFIG_BITRATETYPE* pParam = reinterpret_cast<OMX_VIDEO_CONFIG_BITRATETYPE*>(configData);
memcpy(pParam, &m_sConfigBitrate, sizeof(m_sConfigBitrate));
break;
}
case OMX_IndexConfigVideoFramerate:
{
OMX_CONFIG_FRAMERATETYPE* pParam = reinterpret_cast<OMX_CONFIG_FRAMERATETYPE*>(configData);
memcpy(pParam, &m_sConfigFramerate, sizeof(m_sConfigFramerate));
break;
}
case OMX_IndexConfigCommonRotate:
{
OMX_CONFIG_ROTATIONTYPE* pParam = reinterpret_cast<OMX_CONFIG_ROTATIONTYPE*>(configData);
memcpy(pParam, &m_sConfigFrameRotation, sizeof(m_sConfigFrameRotation));
break;
}
case QOMX_IndexConfigVideoIntraperiod:
{
DEBUG_PRINT_LOW("get_config:QOMX_IndexConfigVideoIntraperiod");
QOMX_VIDEO_INTRAPERIODTYPE* pParam = reinterpret_cast<QOMX_VIDEO_INTRAPERIODTYPE*>(configData);
memcpy(pParam, &m_sIntraperiod, sizeof(m_sIntraperiod));
break;
}
case OMX_IndexConfigVideoAVCIntraPeriod:
{
OMX_VIDEO_CONFIG_AVCINTRAPERIOD *pParam =
reinterpret_cast<OMX_VIDEO_CONFIG_AVCINTRAPERIOD*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_IndexConfigVideoAVCIntraPeriod");
memcpy(pParam, &m_sConfigAVCIDRPeriod, sizeof(m_sConfigAVCIDRPeriod));
break;
}
case OMX_IndexConfigCommonDeinterlace:
{
OMX_VIDEO_CONFIG_DEINTERLACE *pParam =
reinterpret_cast<OMX_VIDEO_CONFIG_DEINTERLACE*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_IndexConfigCommonDeinterlace");
memcpy(pParam, &m_sConfigDeinterlace, sizeof(m_sConfigDeinterlace));
break;
}
case OMX_IndexConfigVideoVp8ReferenceFrame:
{
OMX_VIDEO_VP8REFERENCEFRAMETYPE* pParam =
reinterpret_cast<OMX_VIDEO_VP8REFERENCEFRAMETYPE*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_IndexConfigVideoVp8ReferenceFrame");
memcpy(pParam, &m_sConfigVp8ReferenceFrame, sizeof(m_sConfigVp8ReferenceFrame));
break;
}
case OMX_QcomIndexConfigPerfLevel:
{
OMX_U32 perflevel;
OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *pParam =
reinterpret_cast<OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_QcomIndexConfigPerfLevel");
if (!dev_get_performance_level(&perflevel)) {
DEBUG_PRINT_ERROR("Invalid entry returned from get_performance_level %d",
pParam->ePerfLevel);
} else {
pParam->ePerfLevel = (QOMX_VIDEO_PERF_LEVEL)perflevel;
}
break;
}
default:
DEBUG_PRINT_ERROR("ERROR: unsupported index %d", (int) configIndex);
return OMX_ErrorUnsupportedIndex;
}
return OMX_ErrorNone;
}
Commit Message: DO NOT MERGE mm-video-v4l2: vidc: validate omx param/config data
Check the sanity of config/param strcuture objects
passed to get/set _ config()/parameter() methods.
Bug: 27533317
Security Vulnerability in MediaServer
omx_vdec::get_config() Can lead to arbitrary write
Change-Id: I6c3243afe12055ab94f1a1ecf758c10e88231809
Conflicts:
mm-core/inc/OMX_QCOMExtns.h
mm-video-v4l2/vidc/vdec/src/omx_vdec_msm8974.cpp
mm-video-v4l2/vidc/venc/src/omx_video_base.cpp
mm-video-v4l2/vidc/venc/src/omx_video_encoder.cpp
CWE ID: CWE-20
|
OMX_ERRORTYPE omx_video::get_config(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_INDEXTYPE configIndex,
OMX_INOUT OMX_PTR configData)
{
(void)hComp;
if (configData == NULL) {
DEBUG_PRINT_ERROR("ERROR: param is null");
return OMX_ErrorBadParameter;
}
if (m_state == OMX_StateInvalid) {
DEBUG_PRINT_ERROR("ERROR: can't be in invalid state");
return OMX_ErrorIncorrectStateOperation;
}
switch ((int)configIndex) {
case OMX_IndexConfigVideoBitrate:
{
VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_BITRATETYPE);
OMX_VIDEO_CONFIG_BITRATETYPE* pParam = reinterpret_cast<OMX_VIDEO_CONFIG_BITRATETYPE*>(configData);
memcpy(pParam, &m_sConfigBitrate, sizeof(m_sConfigBitrate));
break;
}
case OMX_IndexConfigVideoFramerate:
{
VALIDATE_OMX_PARAM_DATA(configData, OMX_CONFIG_FRAMERATETYPE);
OMX_CONFIG_FRAMERATETYPE* pParam = reinterpret_cast<OMX_CONFIG_FRAMERATETYPE*>(configData);
memcpy(pParam, &m_sConfigFramerate, sizeof(m_sConfigFramerate));
break;
}
case OMX_IndexConfigCommonRotate:
{
VALIDATE_OMX_PARAM_DATA(configData, OMX_CONFIG_ROTATIONTYPE);
OMX_CONFIG_ROTATIONTYPE* pParam = reinterpret_cast<OMX_CONFIG_ROTATIONTYPE*>(configData);
memcpy(pParam, &m_sConfigFrameRotation, sizeof(m_sConfigFrameRotation));
break;
}
case QOMX_IndexConfigVideoIntraperiod:
{
DEBUG_PRINT_LOW("get_config:QOMX_IndexConfigVideoIntraperiod");
VALIDATE_OMX_PARAM_DATA(configData, QOMX_VIDEO_INTRAPERIODTYPE);
QOMX_VIDEO_INTRAPERIODTYPE* pParam = reinterpret_cast<QOMX_VIDEO_INTRAPERIODTYPE*>(configData);
memcpy(pParam, &m_sIntraperiod, sizeof(m_sIntraperiod));
break;
}
case OMX_IndexConfigVideoAVCIntraPeriod:
{
VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_AVCINTRAPERIOD);
OMX_VIDEO_CONFIG_AVCINTRAPERIOD *pParam =
reinterpret_cast<OMX_VIDEO_CONFIG_AVCINTRAPERIOD*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_IndexConfigVideoAVCIntraPeriod");
memcpy(pParam, &m_sConfigAVCIDRPeriod, sizeof(m_sConfigAVCIDRPeriod));
break;
}
case OMX_IndexConfigCommonDeinterlace:
{
VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_DEINTERLACE);
OMX_VIDEO_CONFIG_DEINTERLACE *pParam =
reinterpret_cast<OMX_VIDEO_CONFIG_DEINTERLACE*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_IndexConfigCommonDeinterlace");
memcpy(pParam, &m_sConfigDeinterlace, sizeof(m_sConfigDeinterlace));
break;
}
case OMX_IndexConfigVideoVp8ReferenceFrame:
{
VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_VP8REFERENCEFRAMETYPE);
OMX_VIDEO_VP8REFERENCEFRAMETYPE* pParam =
reinterpret_cast<OMX_VIDEO_VP8REFERENCEFRAMETYPE*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_IndexConfigVideoVp8ReferenceFrame");
memcpy(pParam, &m_sConfigVp8ReferenceFrame, sizeof(m_sConfigVp8ReferenceFrame));
break;
}
case OMX_QcomIndexConfigPerfLevel:
{
VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL);
OMX_U32 perflevel;
OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *pParam =
reinterpret_cast<OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_QcomIndexConfigPerfLevel");
if (!dev_get_performance_level(&perflevel)) {
DEBUG_PRINT_ERROR("Invalid entry returned from get_performance_level %d",
pParam->ePerfLevel);
} else {
pParam->ePerfLevel = (QOMX_VIDEO_PERF_LEVEL)perflevel;
}
break;
}
default:
DEBUG_PRINT_ERROR("ERROR: unsupported index %d", (int) configIndex);
return OMX_ErrorUnsupportedIndex;
}
return OMX_ErrorNone;
}
| 173,793
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: DWORD WtsSessionProcessDelegate::GetExitCode() {
if (!core_)
return CONTROL_C_EXIT;
return core_->GetExitCode();
}
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
|
DWORD WtsSessionProcessDelegate::GetExitCode() {
DWORD WtsSessionProcessDelegate::GetProcessId() const {
if (core_)
return 0;
return core_->GetProcessId();
}
bool WtsSessionProcessDelegate::IsPermanentError(int failure_count) const {
if (core_)
return false;
return core_->IsPermanentError(failure_count);
}
| 171,557
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 HistoryModelWorker::DoWorkAndWaitUntilDone(Callback0::Type* work) {
WaitableEvent done(false, false);
scoped_refptr<WorkerTask> task(new WorkerTask(work, &done));
history_service_->ScheduleDBTask(task.get(), this);
done.Wait();
}
Commit Message: Enable HistoryModelWorker by default, now that bug 69561 is fixed.
BUG=69561
TEST=Run sync manually and run integration tests, sync should not crash.
Review URL: http://codereview.chromium.org/7016007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85211 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void HistoryModelWorker::DoWorkAndWaitUntilDone(Callback0::Type* work) {
WaitableEvent done(false, false);
scoped_refptr<WorkerTask> task(new WorkerTask(work, &done));
history_service_->ScheduleDBTask(task.get(), &cancelable_consumer_);
done.Wait();
}
| 170,613
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_decrypt)
{
zval **mode;
char *cipher, *key, *data, *iv = NULL;
int cipher_len, key_len, data_len, iv_len = 0;
MCRYPT_GET_CRYPT_ARGS
convert_to_string_ex(mode);
php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_DECRYPT, return_value TSRMLS_CC);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
|
PHP_FUNCTION(mcrypt_decrypt)
{
zval **mode;
char *cipher, *key, *data, *iv = NULL;
int cipher_len, key_len, data_len, iv_len = 0;
MCRYPT_GET_CRYPT_ARGS
convert_to_string_ex(mode);
php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_DECRYPT, return_value TSRMLS_CC);
}
| 167,107
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: err_t verify_signed_hash(const struct RSA_public_key *k
, u_char *s, unsigned int s_max_octets
, u_char **psig
, size_t hash_len
, const u_char *sig_val, size_t sig_len)
{
unsigned int padlen;
/* actual exponentiation; see PKCS#1 v2.0 5.1 */
{
chunk_t temp_s;
MP_INT c;
n_to_mpz(&c, sig_val, sig_len);
oswcrypto.mod_exp(&c, &c, &k->e, &k->n);
temp_s = mpz_to_n(&c, sig_len); /* back to octets */
if(s_max_octets < sig_len) {
return "2""exponentiation failed; too many octets";
}
memcpy(s, temp_s.ptr, sig_len);
pfree(temp_s.ptr);
mpz_clear(&c);
}
/* check signature contents */
/* verify padding (not including any DER digest info! */
padlen = sig_len - 3 - hash_len;
/* now check padding */
DBG(DBG_CRYPT,
DBG_dump("verify_sh decrypted SIG1:", s, sig_len));
DBG(DBG_CRYPT, DBG_log("pad_len calculated: %d hash_len: %d", padlen, (int)hash_len));
/* skip padding */
if(s[0] != 0x00
|| s[1] != 0x01
|| s[padlen+2] != 0x00) {
return "3""SIG padding does not check out";
}
s += padlen + 3;
(*psig) = s;
/* return SUCCESS */
return NULL;
}
Commit Message: wo#7449 . verify padding contents for IKEv2 RSA sig check
Special thanks to Sze Yiu Chau of Purdue University (schau@purdue.edu)
who reported the issue.
CWE ID: CWE-347
|
err_t verify_signed_hash(const struct RSA_public_key *k
, u_char *s, unsigned int s_max_octets
, u_char **psig
, size_t hash_len
, const u_char *sig_val, size_t sig_len)
{
unsigned int padlen;
/* actual exponentiation; see PKCS#1 v2.0 5.1 */
{
chunk_t temp_s;
MP_INT c;
n_to_mpz(&c, sig_val, sig_len);
oswcrypto.mod_exp(&c, &c, &k->e, &k->n);
temp_s = mpz_to_n(&c, sig_len); /* back to octets */
if(s_max_octets < sig_len) {
return "2""exponentiation failed; too many octets";
}
memcpy(s, temp_s.ptr, sig_len);
pfree(temp_s.ptr);
mpz_clear(&c);
}
/* check signature contents */
/* verify padding (not including any DER digest info! */
padlen = sig_len - 3 - hash_len;
/* now check padding */
DBG(DBG_CRYPT,
DBG_dump("verify_sh decrypted SIG1:", s, sig_len));
DBG(DBG_CRYPT, DBG_log("pad_len calculated: %d hash_len: %d", padlen, (int)hash_len));
/* skip padding */
if(s[0] != 0x00
|| s[1] != 0x01
|| s[padlen+2] != 0x00) {
return "3""SIG padding does not check out";
}
/* signature starts after ASN wrapped padding [00,01,FF..FF,00] */
(*psig) = s + padlen + 3;
/* verify padding contents */
{
const u_char *p;
size_t cnt_ffs = 0;
for (p = s+2; p < s+padlen+2; p++)
if (*p == 0xFF)
cnt_ffs ++;
if (cnt_ffs != padlen)
return "4" "invalid Padding String";
}
/* return SUCCESS */
return NULL;
}
| 169,097
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view,
scoped_ptr<Delegate> delegate)
: content::RenderViewObserver(render_view),
content::RenderViewObserverTracker<PrintWebViewHelper>(render_view),
reset_prep_frame_view_(false),
is_print_ready_metafile_sent_(false),
ignore_css_margins_(false),
is_scripted_printing_blocked_(false),
notify_browser_of_print_failure_(true),
print_for_preview_(false),
delegate_(delegate.Pass()),
print_node_in_progress_(false),
is_loading_(false),
is_scripted_preview_delayed_(false),
weak_ptr_factory_(this) {
if (!delegate_->IsPrintPreviewEnabled())
DisablePreview();
}
Commit Message: Crash on nested IPC handlers in PrintWebViewHelper
Class is not designed to handle nested IPC. Regular flows also does not
expect them. Still during printing of plugging them may show message
boxes and start nested message loops.
For now we are going just crash. If stats show us that this case is
frequent we will have to do something more complicated.
BUG=502562
Review URL: https://codereview.chromium.org/1228693002
Cr-Commit-Position: refs/heads/master@{#338100}
CWE ID:
|
PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view,
scoped_ptr<Delegate> delegate)
: content::RenderViewObserver(render_view),
content::RenderViewObserverTracker<PrintWebViewHelper>(render_view),
reset_prep_frame_view_(false),
is_print_ready_metafile_sent_(false),
ignore_css_margins_(false),
is_scripted_printing_blocked_(false),
notify_browser_of_print_failure_(true),
print_for_preview_(false),
delegate_(delegate.Pass()),
print_node_in_progress_(false),
is_loading_(false),
is_scripted_preview_delayed_(false),
ipc_nesting_level_(0),
weak_ptr_factory_(this) {
if (!delegate_->IsPrintPreviewEnabled())
DisablePreview();
}
| 171,878
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ImageInputType::ensurePrimaryContent()
{
if (!m_useFallbackContent)
return;
m_useFallbackContent = false;
reattachFallbackContent();
}
Commit Message: ImageInputType::ensurePrimaryContent should recreate UA shadow tree.
Once the fallback shadow tree was created, it was never recreated even if
ensurePrimaryContent was called. Such situation happens by updating |src|
attribute.
BUG=589838
Review URL: https://codereview.chromium.org/1732753004
Cr-Commit-Position: refs/heads/master@{#377804}
CWE ID: CWE-361
|
void ImageInputType::ensurePrimaryContent()
{
if (!m_useFallbackContent)
return;
m_useFallbackContent = false;
if (ShadowRoot* root = element().userAgentShadowRoot())
root->removeChildren();
createShadowSubtree();
reattachFallbackContent();
}
| 172,285
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SProcXFixesSelectCursorInput(ClientPtr client)
{
REQUEST(xXFixesSelectCursorInputReq);
swaps(&stuff->length);
swapl(&stuff->window);
return (*ProcXFixesVector[stuff->xfixesReqType]) (client);
}
Commit Message:
CWE ID: CWE-20
|
SProcXFixesSelectCursorInput(ClientPtr client)
{
REQUEST(xXFixesSelectCursorInputReq);
REQUEST_SIZE_MATCH(xXFixesSelectCursorInputReq);
swaps(&stuff->length);
swapl(&stuff->window);
return (*ProcXFixesVector[stuff->xfixesReqType]) (client);
}
| 165,441
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 llc_sap_rcv(struct llc_sap *sap, struct sk_buff *skb,
struct sock *sk)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
ev->type = LLC_SAP_EV_TYPE_PDU;
ev->reason = 0;
skb->sk = sk;
llc_sap_state_process(sap, skb);
}
Commit Message: net/llc: avoid BUG_ON() in skb_orphan()
It seems nobody used LLC since linux-3.12.
Fortunately fuzzers like syzkaller still know how to run this code,
otherwise it would be no fun.
Setting skb->sk without skb->destructor leads to all kinds of
bugs, we now prefer to be very strict about it.
Ideally here we would use skb_set_owner() but this helper does not exist yet,
only CAN seems to have a private helper for that.
Fixes: 376c7311bdb6 ("net: add a temporary sanity check in skb_orphan()")
Signed-off-by: Eric Dumazet <edumazet@google.com>
Reported-by: Andrey Konovalov <andreyknvl@google.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-20
|
static void llc_sap_rcv(struct llc_sap *sap, struct sk_buff *skb,
struct sock *sk)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
ev->type = LLC_SAP_EV_TYPE_PDU;
ev->reason = 0;
skb_orphan(skb);
sock_hold(sk);
skb->sk = sk;
skb->destructor = sock_efree;
llc_sap_state_process(sap, skb);
}
| 168,349
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: uint8_t rfc_parse_data(tRFC_MCB* p_mcb, MX_FRAME* p_frame, BT_HDR* p_buf) {
uint8_t ead, eal, fcs;
uint8_t* p_data = (uint8_t*)(p_buf + 1) + p_buf->offset;
uint8_t* p_start = p_data;
uint16_t len;
if (p_buf->len < RFCOMM_CTRL_FRAME_LEN) {
RFCOMM_TRACE_ERROR("Bad Length1: %d", p_buf->len);
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_CTRL_FIELD(ead, p_frame->cr, p_frame->dlci, p_data);
if (!ead) {
RFCOMM_TRACE_ERROR("Bad Address(EA must be 1)");
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_TYPE_FIELD(p_frame->type, p_frame->pf, p_data);
RFCOMM_PARSE_LEN_FIELD(eal, len, p_data);
p_buf->len -= (3 + !ead + !eal + 1); /* Additional 1 for FCS */
p_buf->offset += (3 + !ead + !eal);
/* handle credit if credit based flow control */
if ((p_mcb->flow == PORT_FC_CREDIT) && (p_frame->type == RFCOMM_UIH) &&
(p_frame->dlci != RFCOMM_MX_DLCI) && (p_frame->pf == 1)) {
p_frame->credit = *p_data++;
p_buf->len--;
p_buf->offset++;
} else
p_frame->credit = 0;
if (p_buf->len != len) {
RFCOMM_TRACE_ERROR("Bad Length2 %d %d", p_buf->len, len);
return (RFC_EVENT_BAD_FRAME);
}
fcs = *(p_data + len);
/* All control frames that we are sending are sent with P=1, expect */
/* reply with F=1 */
/* According to TS 07.10 spec ivalid frames are discarded without */
/* notification to the sender */
switch (p_frame->type) {
case RFCOMM_SABME:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad SABME");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_SABME);
case RFCOMM_UA:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UA");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_UA);
case RFCOMM_DM:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || len ||
!RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DM");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DM);
case RFCOMM_DISC:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DISC");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DISC);
case RFCOMM_UIH:
if (!RFCOMM_VALID_DLCI(p_frame->dlci)) {
RFCOMM_TRACE_ERROR("Bad UIH - invalid DLCI");
return (RFC_EVENT_BAD_FRAME);
} else if (!rfc_check_fcs(2, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UIH - FCS");
return (RFC_EVENT_BAD_FRAME);
} else if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr)) {
/* we assume that this is ok to allow bad implementations to work */
RFCOMM_TRACE_ERROR("Bad UIH - response");
return (RFC_EVENT_UIH);
} else
return (RFC_EVENT_UIH);
}
return (RFC_EVENT_BAD_FRAME);
}
Commit Message: Add bound check for rfc_parse_data
Bug: 78288018
Test: manual
Change-Id: I44349cd22c141483d01bce0f5a2131b727d0feb0
(cherry picked from commit 6039cb7225733195192b396ad19c528800feb735)
CWE ID: CWE-125
|
uint8_t rfc_parse_data(tRFC_MCB* p_mcb, MX_FRAME* p_frame, BT_HDR* p_buf) {
uint8_t ead, eal, fcs;
uint8_t* p_data = (uint8_t*)(p_buf + 1) + p_buf->offset;
uint8_t* p_start = p_data;
uint16_t len;
if (p_buf->len < RFCOMM_CTRL_FRAME_LEN) {
RFCOMM_TRACE_ERROR("Bad Length1: %d", p_buf->len);
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_CTRL_FIELD(ead, p_frame->cr, p_frame->dlci, p_data);
if (!ead) {
RFCOMM_TRACE_ERROR("Bad Address(EA must be 1)");
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_TYPE_FIELD(p_frame->type, p_frame->pf, p_data);
eal = *(p_data)&RFCOMM_EA;
len = *(p_data)++ >> RFCOMM_SHIFT_LENGTH1;
if (eal == 0 && p_buf->len < RFCOMM_CTRL_FRAME_LEN) {
len += (*(p_data)++ << RFCOMM_SHIFT_LENGTH2);
} else if (eal == 0) {
RFCOMM_TRACE_ERROR("Bad Length when EAL = 0: %d", p_buf->len);
android_errorWriteLog(0x534e4554, "78288018");
return RFC_EVENT_BAD_FRAME;
}
p_buf->len -= (3 + !ead + !eal + 1); /* Additional 1 for FCS */
p_buf->offset += (3 + !ead + !eal);
/* handle credit if credit based flow control */
if ((p_mcb->flow == PORT_FC_CREDIT) && (p_frame->type == RFCOMM_UIH) &&
(p_frame->dlci != RFCOMM_MX_DLCI) && (p_frame->pf == 1)) {
p_frame->credit = *p_data++;
p_buf->len--;
p_buf->offset++;
} else
p_frame->credit = 0;
if (p_buf->len != len) {
RFCOMM_TRACE_ERROR("Bad Length2 %d %d", p_buf->len, len);
return (RFC_EVENT_BAD_FRAME);
}
fcs = *(p_data + len);
/* All control frames that we are sending are sent with P=1, expect */
/* reply with F=1 */
/* According to TS 07.10 spec ivalid frames are discarded without */
/* notification to the sender */
switch (p_frame->type) {
case RFCOMM_SABME:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad SABME");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_SABME);
case RFCOMM_UA:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UA");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_UA);
case RFCOMM_DM:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || len ||
!RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DM");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DM);
case RFCOMM_DISC:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DISC");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DISC);
case RFCOMM_UIH:
if (!RFCOMM_VALID_DLCI(p_frame->dlci)) {
RFCOMM_TRACE_ERROR("Bad UIH - invalid DLCI");
return (RFC_EVENT_BAD_FRAME);
} else if (!rfc_check_fcs(2, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UIH - FCS");
return (RFC_EVENT_BAD_FRAME);
} else if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr)) {
/* we assume that this is ok to allow bad implementations to work */
RFCOMM_TRACE_ERROR("Bad UIH - response");
return (RFC_EVENT_UIH);
} else
return (RFC_EVENT_UIH);
}
return (RFC_EVENT_BAD_FRAME);
}
| 174,612
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: const Track* Tracks::GetTrackByIndex(unsigned long idx) const
{
const ptrdiff_t count = m_trackEntriesEnd - m_trackEntries;
if (idx >= static_cast<unsigned long>(count))
return NULL;
return m_trackEntries[idx];
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
const Track* Tracks::GetTrackByIndex(unsigned long idx) const
return m_trackEntries[idx];
}
| 174,370
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: 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 <michaelni@gmx.at>
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: void svc_rdma_send_error(struct svcxprt_rdma *xprt, struct rpcrdma_msg *rmsgp,
int status)
{
struct ib_send_wr err_wr;
struct page *p;
struct svc_rdma_op_ctxt *ctxt;
enum rpcrdma_errcode err;
__be32 *va;
int length;
int ret;
ret = svc_rdma_repost_recv(xprt, GFP_KERNEL);
if (ret)
return;
p = alloc_page(GFP_KERNEL);
if (!p)
return;
va = page_address(p);
/* XDR encode an error reply */
err = ERR_CHUNK;
if (status == -EPROTONOSUPPORT)
err = ERR_VERS;
length = svc_rdma_xdr_encode_error(xprt, rmsgp, err, va);
ctxt = svc_rdma_get_context(xprt);
ctxt->direction = DMA_TO_DEVICE;
ctxt->count = 1;
ctxt->pages[0] = p;
/* Prepare SGE for local address */
ctxt->sge[0].lkey = xprt->sc_pd->local_dma_lkey;
ctxt->sge[0].length = length;
ctxt->sge[0].addr = ib_dma_map_page(xprt->sc_cm_id->device,
p, 0, length, DMA_TO_DEVICE);
if (ib_dma_mapping_error(xprt->sc_cm_id->device, ctxt->sge[0].addr)) {
dprintk("svcrdma: Error mapping buffer for protocol error\n");
svc_rdma_put_context(ctxt, 1);
return;
}
svc_rdma_count_mappings(xprt, ctxt);
/* Prepare SEND WR */
memset(&err_wr, 0, sizeof(err_wr));
ctxt->cqe.done = svc_rdma_wc_send;
err_wr.wr_cqe = &ctxt->cqe;
err_wr.sg_list = ctxt->sge;
err_wr.num_sge = 1;
err_wr.opcode = IB_WR_SEND;
err_wr.send_flags = IB_SEND_SIGNALED;
/* Post It */
ret = svc_rdma_send(xprt, &err_wr);
if (ret) {
dprintk("svcrdma: Error %d posting send for protocol error\n",
ret);
svc_rdma_unmap_dma(ctxt);
svc_rdma_put_context(ctxt, 1);
}
}
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_send_error(struct svcxprt_rdma *xprt, struct rpcrdma_msg *rmsgp,
| 168,174
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)
{
struct page *pages[NFS4ACL_MAXPAGES];
struct nfs_getaclargs args = {
.fh = NFS_FH(inode),
.acl_pages = pages,
.acl_len = buflen,
};
struct nfs_getaclres res = {
.acl_len = buflen,
};
void *resp_buf;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL],
.rpc_argp = &args,
.rpc_resp = &res,
};
struct page *localpage = NULL;
int ret;
if (buflen < PAGE_SIZE) {
/* As long as we're doing a round trip to the server anyway,
* let's be prepared for a page of acl data. */
localpage = alloc_page(GFP_KERNEL);
resp_buf = page_address(localpage);
if (localpage == NULL)
return -ENOMEM;
args.acl_pages[0] = localpage;
args.acl_pgbase = 0;
args.acl_len = PAGE_SIZE;
} else {
resp_buf = buf;
buf_to_pages(buf, buflen, args.acl_pages, &args.acl_pgbase);
}
ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode), &msg, &args.seq_args, &res.seq_res, 0);
if (ret)
goto out_free;
if (res.acl_len > args.acl_len)
nfs4_write_cached_acl(inode, NULL, res.acl_len);
else
nfs4_write_cached_acl(inode, resp_buf, res.acl_len);
if (buf) {
ret = -ERANGE;
if (res.acl_len > buflen)
goto out_free;
if (localpage)
memcpy(buf, resp_buf, res.acl_len);
}
ret = res.acl_len;
out_free:
if (localpage)
__free_page(localpage);
return ret;
}
Commit Message: NFSv4: include bitmap in nfsv4 get acl data
The NFSv4 bitmap size is unbounded: a server can return an arbitrary
sized bitmap in an FATTR4_WORD0_ACL request. Replace using the
nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server
with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data
xdr length to the (cached) acl page data.
This is a general solution to commit e5012d1f "NFSv4.1: update
nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead
when getting ACLs.
Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr
was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved.
Cc: stable@kernel.org
Signed-off-by: Andy Adamson <andros@netapp.com>
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
CWE ID: CWE-189
|
static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)
{
struct page *pages[NFS4ACL_MAXPAGES] = {NULL, };
struct nfs_getaclargs args = {
.fh = NFS_FH(inode),
.acl_pages = pages,
.acl_len = buflen,
};
struct nfs_getaclres res = {
.acl_len = buflen,
};
void *resp_buf;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL],
.rpc_argp = &args,
.rpc_resp = &res,
};
int ret = -ENOMEM, npages, i, acl_len = 0;
npages = (buflen + PAGE_SIZE - 1) >> PAGE_SHIFT;
/* As long as we're doing a round trip to the server anyway,
* let's be prepared for a page of acl data. */
if (npages == 0)
npages = 1;
for (i = 0; i < npages; i++) {
pages[i] = alloc_page(GFP_KERNEL);
if (!pages[i])
goto out_free;
}
if (npages > 1) {
/* for decoding across pages */
args.acl_scratch = alloc_page(GFP_KERNEL);
if (!args.acl_scratch)
goto out_free;
}
args.acl_len = npages * PAGE_SIZE;
args.acl_pgbase = 0;
/* Let decode_getfacl know not to fail if the ACL data is larger than
* the page we send as a guess */
if (buf == NULL)
res.acl_flags |= NFS4_ACL_LEN_REQUEST;
resp_buf = page_address(pages[0]);
dprintk("%s buf %p buflen %ld npages %d args.acl_len %ld\n",
__func__, buf, buflen, npages, args.acl_len);
ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode),
&msg, &args.seq_args, &res.seq_res, 0);
if (ret)
goto out_free;
acl_len = res.acl_len - res.acl_data_offset;
if (acl_len > args.acl_len)
nfs4_write_cached_acl(inode, NULL, acl_len);
else
nfs4_write_cached_acl(inode, resp_buf + res.acl_data_offset,
acl_len);
if (buf) {
ret = -ERANGE;
if (acl_len > buflen)
goto out_free;
_copy_from_pages(buf, pages, res.acl_data_offset,
res.acl_len);
}
ret = acl_len;
out_free:
for (i = 0; i < npages; i++)
if (pages[i])
__free_page(pages[i]);
if (args.acl_scratch)
__free_page(args.acl_scratch);
return ret;
}
| 165,716
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ZeroSuggestProvider::Start(const AutocompleteInput& input,
bool minimal_changes) {
TRACE_EVENT0("omnibox", "ZeroSuggestProvider::Start");
matches_.clear();
if (!input.from_omnibox_focus() || client()->IsOffTheRecord() ||
input.type() == metrics::OmniboxInputType::INVALID)
return;
Stop(true, false);
set_field_trial_triggered(false);
set_field_trial_triggered_in_session(false);
results_from_cache_ = false;
permanent_text_ = input.text();
current_query_ = input.current_url().spec();
current_title_ = input.current_title();
current_page_classification_ = input.current_page_classification();
current_url_match_ = MatchForCurrentURL();
std::string url_string = GetContextualSuggestionsUrl();
GURL suggest_url(url_string);
if (!suggest_url.is_valid())
return;
const TemplateURLService* template_url_service =
client()->GetTemplateURLService();
const TemplateURL* default_provider =
template_url_service->GetDefaultSearchProvider();
const bool can_send_current_url =
CanSendURL(input.current_url(), suggest_url, default_provider,
current_page_classification_,
template_url_service->search_terms_data(), client());
GURL arbitrary_insecure_url(kArbitraryInsecureUrlString);
ZeroSuggestEligibility eligibility = ZeroSuggestEligibility::ELIGIBLE;
if (!can_send_current_url) {
const bool can_send_ordinary_url =
CanSendURL(arbitrary_insecure_url, suggest_url, default_provider,
current_page_classification_,
template_url_service->search_terms_data(), client());
eligibility = can_send_ordinary_url
? ZeroSuggestEligibility::URL_INELIGIBLE
: ZeroSuggestEligibility::GENERALLY_INELIGIBLE;
}
UMA_HISTOGRAM_ENUMERATION(
"Omnibox.ZeroSuggest.Eligible.OnFocus", static_cast<int>(eligibility),
static_cast<int>(ZeroSuggestEligibility::ELIGIBLE_MAX_VALUE));
if (can_send_current_url &&
!OmniboxFieldTrial::InZeroSuggestPersonalizedFieldTrial() &&
!OmniboxFieldTrial::InZeroSuggestMostVisitedFieldTrial()) {
if (OmniboxFieldTrial::InZeroSuggestRedirectToChromeFieldTrial()) {
url_string +=
"/url=" + net::EscapePath(current_query_) +
OmniboxFieldTrial::ZeroSuggestRedirectToChromeAdditionalFields();
suggest_url = GURL(url_string);
} else {
base::string16 prefix;
TemplateURLRef::SearchTermsArgs search_term_args(prefix);
search_term_args.current_page_url = current_query_;
suggest_url =
GURL(default_provider->suggestions_url_ref().ReplaceSearchTerms(
search_term_args, template_url_service->search_terms_data()));
}
} else if (!ShouldShowNonContextualZeroSuggest(input.current_url())) {
return;
}
done_ = false;
MaybeUseCachedSuggestions();
Run(suggest_url);
}
Commit Message: Provide experimental contextual suggestions when current URL comes from a google domain.
The counts for the Omnibox.ZeroSuggestRequests historgram are 35% smaller for groups that are running under the ZeroSuggestRedirectToChrome flag. Note that previous to this CL, a request was not made when the user was visiting an HTTPS page and the domain of the current was different from that of the service providing zero suggestions. This CL addresses this restrictions by making sure that requests are sent to the experimental service when Google is the default search engine AND the same request was validated to be sent to Google.
BUG=692471
Review-Url: https://codereview.chromium.org/2915163003
Cr-Commit-Position: refs/heads/master@{#476786}
CWE ID:
|
void ZeroSuggestProvider::Start(const AutocompleteInput& input,
bool minimal_changes) {
TRACE_EVENT0("omnibox", "ZeroSuggestProvider::Start");
matches_.clear();
if (!input.from_omnibox_focus() || client()->IsOffTheRecord() ||
input.type() == metrics::OmniboxInputType::INVALID)
return;
Stop(true, false);
set_field_trial_triggered(false);
set_field_trial_triggered_in_session(false);
results_from_cache_ = false;
permanent_text_ = input.text();
current_query_ = input.current_url().spec();
current_title_ = input.current_title();
current_page_classification_ = input.current_page_classification();
current_url_match_ = MatchForCurrentURL();
GURL suggest_url(GetContextualSuggestionsUrl());
if (!suggest_url.is_valid())
return;
const TemplateURLService* template_url_service =
client()->GetTemplateURLService();
const TemplateURL* default_provider =
template_url_service->GetDefaultSearchProvider();
const bool can_send_current_url =
CanSendURL(input.current_url(), suggest_url, default_provider,
current_page_classification_,
template_url_service->search_terms_data(), client());
GURL arbitrary_insecure_url(kArbitraryInsecureUrlString);
ZeroSuggestEligibility eligibility = ZeroSuggestEligibility::ELIGIBLE;
if (!can_send_current_url) {
const bool can_send_ordinary_url =
CanSendURL(arbitrary_insecure_url, suggest_url, default_provider,
current_page_classification_,
template_url_service->search_terms_data(), client());
eligibility = can_send_ordinary_url
? ZeroSuggestEligibility::URL_INELIGIBLE
: ZeroSuggestEligibility::GENERALLY_INELIGIBLE;
}
UMA_HISTOGRAM_ENUMERATION(
"Omnibox.ZeroSuggest.Eligible.OnFocus", static_cast<int>(eligibility),
static_cast<int>(ZeroSuggestEligibility::ELIGIBLE_MAX_VALUE));
if (can_send_current_url &&
!OmniboxFieldTrial::InZeroSuggestPersonalizedFieldTrial() &&
!OmniboxFieldTrial::InZeroSuggestMostVisitedFieldTrial()) {
if (UseExperimentalSuggestService(*template_url_service)) {
suggest_url = GURL(
OmniboxFieldTrial::ZeroSuggestRedirectToChromeServerAddress() +
"/url=" + net::EscapePath(current_query_) +
OmniboxFieldTrial::ZeroSuggestRedirectToChromeAdditionalFields());
} else {
base::string16 prefix;
TemplateURLRef::SearchTermsArgs search_term_args(prefix);
search_term_args.current_page_url = current_query_;
suggest_url =
GURL(default_provider->suggestions_url_ref().ReplaceSearchTerms(
search_term_args, template_url_service->search_terms_data()));
}
} else if (!ShouldShowNonContextualZeroSuggest(input.current_url())) {
return;
}
done_ = false;
MaybeUseCachedSuggestions();
Run(suggest_url);
}
| 172,013
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: xps_parse_color(xps_document *doc, char *base_uri, char *string,
fz_colorspace **csp, float *samples)
{
char *p;
int i, n;
char buf[1024];
char *profile;
*csp = fz_device_rgb(doc->ctx);
samples[0] = 1;
samples[1] = 0;
samples[3] = 0;
if (string[0] == '#')
{
if (strlen(string) == 9)
{
samples[0] = unhex(string[1]) * 16 + unhex(string[2]);
samples[1] = unhex(string[3]) * 16 + unhex(string[4]);
samples[2] = unhex(string[5]) * 16 + unhex(string[6]);
samples[3] = unhex(string[7]) * 16 + unhex(string[8]);
}
else
{
samples[0] = 255;
samples[1] = unhex(string[1]) * 16 + unhex(string[2]);
samples[2] = unhex(string[3]) * 16 + unhex(string[4]);
samples[3] = unhex(string[5]) * 16 + unhex(string[6]);
}
samples[0] /= 255;
samples[1] /= 255;
samples[2] /= 255;
samples[3] /= 255;
}
else if (string[0] == 's' && string[1] == 'c' && string[2] == '#')
{
if (count_commas(string) == 2)
sscanf(string, "sc#%g,%g,%g", samples + 1, samples + 2, samples + 3);
if (count_commas(string) == 3)
sscanf(string, "sc#%g,%g,%g,%g", samples, samples + 1, samples + 2, samples + 3);
}
else if (strstr(string, "ContextColor ") == string)
{
/* Crack the string for profile name and sample values */
fz_strlcpy(buf, string, sizeof buf);
profile = strchr(buf, ' ');
profile = strchr(buf, ' ');
if (!profile)
{
fz_warn(doc->ctx, "cannot find icc profile uri in '%s'", string);
return;
}
p = strchr(profile, ' ');
p = strchr(profile, ' ');
if (!p)
{
fz_warn(doc->ctx, "cannot find component values in '%s'", profile);
return;
}
*p++ = 0;
n = count_commas(p) + 1;
i = 0;
while (i < n)
{
p ++;
}
while (i < n)
{
samples[i++] = 0;
}
/* TODO: load ICC profile */
switch (n)
{
case 2: *csp = fz_device_gray(doc->ctx); break;
case 4: *csp = fz_device_rgb(doc->ctx); break;
case 5: *csp = fz_device_cmyk(doc->ctx); break;
/* TODO: load ICC profile */
switch (n)
{
case 2: *csp = fz_device_gray(doc->ctx); break;
case 4: *csp = fz_device_rgb(doc->ctx); break;
case 5: *csp = fz_device_cmyk(doc->ctx); break;
default: *csp = fz_device_gray(doc->ctx); break;
}
}
}
for (i = 0; i < colorspace->n; i++)
doc->color[i] = samples[i + 1];
doc->alpha = samples[0] * doc->opacity[doc->opacity_top];
}
Commit Message:
CWE ID: CWE-119
|
xps_parse_color(xps_document *doc, char *base_uri, char *string,
fz_colorspace **csp, float *samples)
{
fz_context *ctx = doc->ctx;
char *p;
int i, n;
char buf[1024];
char *profile;
*csp = fz_device_rgb(ctx);
samples[0] = 1;
samples[1] = 0;
samples[3] = 0;
if (string[0] == '#')
{
if (strlen(string) == 9)
{
samples[0] = unhex(string[1]) * 16 + unhex(string[2]);
samples[1] = unhex(string[3]) * 16 + unhex(string[4]);
samples[2] = unhex(string[5]) * 16 + unhex(string[6]);
samples[3] = unhex(string[7]) * 16 + unhex(string[8]);
}
else
{
samples[0] = 255;
samples[1] = unhex(string[1]) * 16 + unhex(string[2]);
samples[2] = unhex(string[3]) * 16 + unhex(string[4]);
samples[3] = unhex(string[5]) * 16 + unhex(string[6]);
}
samples[0] /= 255;
samples[1] /= 255;
samples[2] /= 255;
samples[3] /= 255;
}
else if (string[0] == 's' && string[1] == 'c' && string[2] == '#')
{
if (count_commas(string) == 2)
sscanf(string, "sc#%g,%g,%g", samples + 1, samples + 2, samples + 3);
if (count_commas(string) == 3)
sscanf(string, "sc#%g,%g,%g,%g", samples, samples + 1, samples + 2, samples + 3);
}
else if (strstr(string, "ContextColor ") == string)
{
/* Crack the string for profile name and sample values */
fz_strlcpy(buf, string, sizeof buf);
profile = strchr(buf, ' ');
profile = strchr(buf, ' ');
if (!profile)
{
fz_warn(ctx, "cannot find icc profile uri in '%s'", string);
return;
}
p = strchr(profile, ' ');
p = strchr(profile, ' ');
if (!p)
{
fz_warn(ctx, "cannot find component values in '%s'", profile);
return;
}
*p++ = 0;
n = count_commas(p) + 1;
if (n > FZ_MAX_COLORS)
{
fz_warn(ctx, "ignoring %d color components (max %d allowed)", n - FZ_MAX_COLORS, FZ_MAX_COLORS);
n = FZ_MAX_COLORS;
}
i = 0;
while (i < n)
{
p ++;
}
while (i < n)
{
samples[i++] = 0;
}
/* TODO: load ICC profile */
switch (n)
{
case 2: *csp = fz_device_gray(doc->ctx); break;
case 4: *csp = fz_device_rgb(doc->ctx); break;
case 5: *csp = fz_device_cmyk(doc->ctx); break;
/* TODO: load ICC profile */
switch (n)
{
case 2: *csp = fz_device_gray(ctx); break;
case 4: *csp = fz_device_rgb(ctx); break;
case 5: *csp = fz_device_cmyk(ctx); break;
default: *csp = fz_device_gray(ctx); break;
}
}
}
for (i = 0; i < colorspace->n; i++)
doc->color[i] = samples[i + 1];
doc->alpha = samples[0] * doc->opacity[doc->opacity_top];
}
| 165,228
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: I18NCustomBindings::I18NCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetL10nMessage",
base::Bind(&I18NCustomBindings::GetL10nMessage, base::Unretained(this)));
RouteFunction("GetL10nUILanguage",
base::Bind(&I18NCustomBindings::GetL10nUILanguage,
base::Unretained(this)));
RouteFunction("DetectTextLanguage",
base::Bind(&I18NCustomBindings::DetectTextLanguage,
base::Unretained(this)));
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284
|
I18NCustomBindings::I18NCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetL10nMessage", "i18n",
base::Bind(&I18NCustomBindings::GetL10nMessage, base::Unretained(this)));
RouteFunction("GetL10nUILanguage", "i18n",
base::Bind(&I18NCustomBindings::GetL10nUILanguage,
base::Unretained(this)));
RouteFunction("DetectTextLanguage", "i18n",
base::Bind(&I18NCustomBindings::DetectTextLanguage,
base::Unretained(this)));
}
| 172,249
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 php_stream_temp_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) /* {{{ */
{
php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract;
switch(option) {
case PHP_STREAM_OPTION_META_DATA_API:
if (ts->meta) {
zend_hash_copy(Z_ARRVAL_P((zval*)ptrparam), Z_ARRVAL_P(ts->meta), (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval*));
}
return PHP_STREAM_OPTION_RETURN_OK;
default:
if (ts->innerstream) {
return php_stream_set_option(ts->innerstream, option, value, ptrparam);
}
return PHP_STREAM_OPTION_RETURN_NOTIMPL;
}
}
/* }}} */
Commit Message:
CWE ID: CWE-20
|
static int php_stream_temp_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) /* {{{ */
{
php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract;
switch(option) {
case PHP_STREAM_OPTION_META_DATA_API:
if (ts->meta) {
zend_hash_copy(Z_ARRVAL_P((zval*)ptrparam), Z_ARRVAL_P(ts->meta), (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval*));
}
return PHP_STREAM_OPTION_RETURN_OK;
default:
if (ts->innerstream) {
return php_stream_set_option(ts->innerstream, option, value, ptrparam);
}
return PHP_STREAM_OPTION_RETURN_NOTIMPL;
}
}
/* }}} */
| 165,482
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static ScriptPromise fulfillImageBitmap(ExecutionContext* context, PassRefPtrWillBeRawPtr<ImageBitmap> imageBitmap)
{
RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(context);
ScriptPromise promise = resolver->promise();
resolver->resolve(imageBitmap);
return promise;
}
Commit Message: Fix crash when creating an ImageBitmap from an invalid canvas
BUG=354356
Review URL: https://codereview.chromium.org/211313003
git-svn-id: svn://svn.chromium.org/blink/trunk@169973 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
static ScriptPromise fulfillImageBitmap(ExecutionContext* context, PassRefPtrWillBeRawPtr<ImageBitmap> imageBitmap)
{
RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(context);
ScriptPromise promise = resolver->promise();
if (imageBitmap) {
resolver->resolve(imageBitmap);
} else {
v8::Isolate* isolate = ScriptState::current()->isolate();
resolver->reject(ScriptValue(v8::Null(isolate), isolate));
}
return promise;
}
| 171,395
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 phar_add_virtual_dirs(phar_archive_data *phar, char *filename, int filename_len TSRMLS_DC) /* {{{ */
{
const char *s;
while ((s = zend_memrchr(filename, '/', filename_len))) {
filename_len = s - filename;
if (FAILURE == zend_hash_add_empty_element(&phar->virtual_dirs, filename, filename_len)) {
break;
}
}
}
/* }}} */
Commit Message:
CWE ID: CWE-189
|
void phar_add_virtual_dirs(phar_archive_data *phar, char *filename, int filename_len TSRMLS_DC) /* {{{ */
{
const char *s;
while ((s = zend_memrchr(filename, '/', filename_len))) {
filename_len = s - filename;
if (!filename_len || FAILURE == zend_hash_add_empty_element(&phar->virtual_dirs, filename, filename_len)) {
break;
}
}
}
/* }}} */
| 164,572
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ImageBitmapFactories::ImageBitmapLoader::RejectPromise(
ImageBitmapRejectionReason reason) {
switch (reason) {
case kUndecodableImageBitmapRejectionReason:
resolver_->Reject(
DOMException::Create(DOMExceptionCode::kInvalidStateError,
"The source image could not be decoded."));
break;
case kAllocationFailureImageBitmapRejectionReason:
resolver_->Reject(
DOMException::Create(DOMExceptionCode::kInvalidStateError,
"The ImageBitmap could not be allocated."));
break;
default:
NOTREACHED();
}
factory_->DidFinishLoading(this);
}
Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader
FileReaderLoader stores its client as a raw pointer, so in cases like
ImageBitmapLoader where the FileReaderLoaderClient really is garbage
collected we have to make sure to destroy the FileReaderLoader when
the ExecutionContext that owns it is destroyed.
Bug: 913970
Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861
Reviewed-on: https://chromium-review.googlesource.com/c/1374511
Reviewed-by: Jeremy Roman <jbroman@chromium.org>
Commit-Queue: Marijn Kruisselbrink <mek@chromium.org>
Cr-Commit-Position: refs/heads/master@{#616342}
CWE ID: CWE-416
|
void ImageBitmapFactories::ImageBitmapLoader::RejectPromise(
ImageBitmapRejectionReason reason) {
switch (reason) {
case kUndecodableImageBitmapRejectionReason:
resolver_->Reject(
DOMException::Create(DOMExceptionCode::kInvalidStateError,
"The source image could not be decoded."));
break;
case kAllocationFailureImageBitmapRejectionReason:
resolver_->Reject(
DOMException::Create(DOMExceptionCode::kInvalidStateError,
"The ImageBitmap could not be allocated."));
break;
default:
NOTREACHED();
}
loader_.reset();
factory_->DidFinishLoading(this);
}
| 173,069
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mkvparser::Match(
IMkvReader* pReader,
long long& pos,
unsigned long id_,
long long& val)
{
assert(pReader);
assert(pos >= 0);
long long total, available;
const long status = pReader->Length(&total, &available);
assert(status >= 0);
assert((total < 0) || (available <= total));
if (status < 0)
return false;
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0);
assert(len > 0);
assert(len <= 8);
assert((pos + len) <= available);
if ((unsigned long)id != id_)
return false;
pos += len; //consume id
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert(size <= 8);
assert(len > 0);
assert(len <= 8);
assert((pos + len) <= available);
pos += len; //consume length of size of payload
val = UnserializeUInt(pReader, pos, size);
assert(val >= 0);
pos += size; //consume size of payload
return true;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
bool mkvparser::Match(
long long total, available;
const long status = pReader->Length(&total, &available);
assert(status >= 0);
assert((total < 0) || (available <= total));
if (status < 0)
return false;
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0);
assert(len > 0);
assert(len <= 8);
assert((pos + len) <= available);
if ((unsigned long)id != id_)
return false;
pos += len; // consume id
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert(size <= 8);
assert(len > 0);
assert(len <= 8);
assert((pos + len) <= available);
pos += len; // consume length of size of payload
val = UnserializeUInt(pReader, pos, size);
assert(val >= 0);
pos += size; // consume size of payload
return true;
}
| 174,398
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: std::string DataUseUserData::GetServiceNameAsString(ServiceName service_name) {
switch (service_name) {
case SUGGESTIONS:
return "Suggestions";
case NOT_TAGGED:
return "NotTagged";
case TRANSLATE:
return "Translate";
case SYNC:
return "Sync";
case OMNIBOX:
return "Omnibox";
case INVALIDATION:
return "Invalidation";
case RAPPOR:
return "Rappor";
case VARIATIONS:
return "Variations";
case UMA:
return "UMA";
case DOMAIN_RELIABILITY:
return "DomainReliability";
case PROFILE_DOWNLOADER:
return "ProfileDownloader";
case GOOGLE_URL_TRACKER:
return "GoogleURLTracker";
case AUTOFILL:
return "Autofill";
case POLICY:
return "Policy";
case SPELL_CHECKER:
return "SpellChecker";
case NTP_SNIPPETS:
return "NTPSnippets";
case SAFE_BROWSING:
return "SafeBrowsing";
case DATA_REDUCTION_PROXY:
return "DataReductionProxy";
case PRECACHE:
return "Precache";
case NTP_TILES:
return "NTPTiles";
case FEEDBACK_UPLOADER:
return "FeedbackUploader";
case TRACING_UPLOADER:
return "TracingUploader";
case DOM_DISTILLER:
return "DOMDistiller";
case CLOUD_PRINT:
return "CloudPrint";
case SEARCH_PROVIDER_LOGOS:
return "SearchProviderLogos";
case UPDATE_CLIENT:
return "UpdateClient";
case GCM_DRIVER:
return "GCMDriver";
case WEB_HISTORY_SERVICE:
return "WebHistoryService";
case NETWORK_TIME_TRACKER:
return "NetworkTimeTracker";
case SUPERVISED_USER:
return "SupervisedUser";
case IMAGE_FETCHER_UNTAGGED:
return "ImageFetcherUntagged";
case GAIA:
return "GAIA";
}
return "INVALID";
}
Commit Message: Add data usage tracking for chrome services
Add data usage tracking for captive portal, web resource and signin services
BUG=655749
Review-Url: https://codereview.chromium.org/2643013004
Cr-Commit-Position: refs/heads/master@{#445810}
CWE ID: CWE-190
|
std::string DataUseUserData::GetServiceNameAsString(ServiceName service_name) {
switch (service_name) {
case SUGGESTIONS:
return "Suggestions";
case NOT_TAGGED:
return "NotTagged";
case TRANSLATE:
return "Translate";
case SYNC:
return "Sync";
case OMNIBOX:
return "Omnibox";
case INVALIDATION:
return "Invalidation";
case RAPPOR:
return "Rappor";
case VARIATIONS:
return "Variations";
case UMA:
return "UMA";
case DOMAIN_RELIABILITY:
return "DomainReliability";
case PROFILE_DOWNLOADER:
return "ProfileDownloader";
case GOOGLE_URL_TRACKER:
return "GoogleURLTracker";
case AUTOFILL:
return "Autofill";
case POLICY:
return "Policy";
case SPELL_CHECKER:
return "SpellChecker";
case NTP_SNIPPETS:
return "NTPSnippets";
case SAFE_BROWSING:
return "SafeBrowsing";
case DATA_REDUCTION_PROXY:
return "DataReductionProxy";
case PRECACHE:
return "Precache";
case NTP_TILES:
return "NTPTiles";
case FEEDBACK_UPLOADER:
return "FeedbackUploader";
case TRACING_UPLOADER:
return "TracingUploader";
case DOM_DISTILLER:
return "DOMDistiller";
case CLOUD_PRINT:
return "CloudPrint";
case SEARCH_PROVIDER_LOGOS:
return "SearchProviderLogos";
case UPDATE_CLIENT:
return "UpdateClient";
case GCM_DRIVER:
return "GCMDriver";
case WEB_HISTORY_SERVICE:
return "WebHistoryService";
case NETWORK_TIME_TRACKER:
return "NetworkTimeTracker";
case SUPERVISED_USER:
return "SupervisedUser";
case IMAGE_FETCHER_UNTAGGED:
return "ImageFetcherUntagged";
case GAIA:
return "GAIA";
case CAPTIVE_PORTAL:
return "CaptivePortal";
case WEB_RESOURCE_SERVICE:
return "WebResourceService";
case SIGNIN:
return "Signin";
}
return "INVALID";
}
| 172,018
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: image_transform_png_set_gray_to_rgb_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return (colour_type & PNG_COLOR_MASK_COLOR) == 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
image_transform_png_set_gray_to_rgb_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return (colour_type & PNG_COLOR_MASK_COLOR) == 0;
}
| 173,635
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int nodigest, int nocontent)
{
FD_t wfd = NULL;
int rc = 0;
/* Create the file with 0200 permissions (write by owner). */
{
mode_t old_umask = umask(0577);
wfd = Fopen(dest, "w.ufdio");
umask(old_umask);
}
if (Ferror(wfd)) {
rc = RPMERR_OPEN_FAILED;
goto exit;
}
if (!nocontent)
rc = rpmfiArchiveReadToFilePsm(fi, wfd, nodigest, psm);
exit:
if (wfd) {
int myerrno = errno;
Fclose(wfd);
errno = myerrno;
}
return rc;
}
Commit Message: Don't follow symlinks on file creation (CVE-2017-7501)
Open newly created files with O_EXCL to prevent symlink tricks.
When reopening hardlinks for writing the actual content, use append
mode instead. This is compatible with the write-only permissions but
is not destructive in case we got redirected to somebody elses file,
verify the target before actually writing anything.
As these are files with the temporary suffix, errors mean a local
user with sufficient privileges to break the installation of the package
anyway is trying to goof us on purpose, don't bother trying to mend it
(we couldn't fix the hardlink case anyhow) but just bail out.
Based on a patch by Florian Festi.
CWE ID: CWE-59
|
static int expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int nodigest, int nocontent)
static int expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int exclusive, int nodigest, int nocontent)
{
FD_t wfd = NULL;
int rc = 0;
/* Create the file with 0200 permissions (write by owner). */
{
mode_t old_umask = umask(0577);
wfd = Fopen(dest, exclusive ? "wx.ufdio" : "a.ufdio");
umask(old_umask);
/* If reopening, make sure the file is what we expect */
if (!exclusive && wfd != NULL && !linkSane(wfd, dest)) {
rc = RPMERR_OPEN_FAILED;
goto exit;
}
}
if (Ferror(wfd)) {
rc = RPMERR_OPEN_FAILED;
goto exit;
}
if (!nocontent)
rc = rpmfiArchiveReadToFilePsm(fi, wfd, nodigest, psm);
exit:
if (wfd) {
int myerrno = errno;
Fclose(wfd);
errno = myerrno;
}
return rc;
}
| 168,267
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
int nb_sectors)
{
return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
nb_sectors * BDRV_SECTOR_SIZE);
}
Commit Message:
CWE ID: CWE-190
|
static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
int nb_sectors)
{
if (nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) {
return -EIO;
}
return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
nb_sectors * BDRV_SECTOR_SIZE);
}
| 165,408
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 const char *parse_scheme(struct parse_state *state)
{
size_t mb;
const char *tmp = state->ptr;
do {
switch (*state->ptr) {
case ':':
/* scheme delimiter */
state->url.scheme = &state->buffer[0];
state->buffer[state->offset++] = 0;
return ++state->ptr;
case '0': case '1': case '2': case '3': case '4': case '5': case '6':
case '7': case '8': case '9':
case '+': case '-': case '.':
if (state->ptr == tmp) {
return tmp;
}
/* no break */
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
case 'V': case 'W': case 'X': case 'Y': case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y': case 'z':
/* scheme part */
state->buffer[state->offset++] = *state->ptr;
break;
default:
if (!(mb = parse_mb(state, PARSE_SCHEME, state->ptr, state->end, tmp, 1))) {
/* soft fail; parse path next */
return tmp;
}
state->ptr += mb - 1;
}
} while (++state->ptr != state->end);
return state->ptr = tmp;
}
Commit Message: fix bug #71719 (Buffer overflow in HTTP url parsing functions)
The parser's offset was not reset when we softfail in scheme
parsing and continue to parse a path.
Thanks to hlt99 at blinkenshell dot org for the report.
CWE ID: CWE-119
|
static const char *parse_scheme(struct parse_state *state)
{
size_t mb;
const char *tmp = state->ptr;
do {
switch (*state->ptr) {
case ':':
/* scheme delimiter */
state->url.scheme = &state->buffer[0];
state->buffer[state->offset++] = 0;
return ++state->ptr;
case '0': case '1': case '2': case '3': case '4': case '5': case '6':
case '7': case '8': case '9':
case '+': case '-': case '.':
if (state->ptr == tmp) {
goto softfail;
}
/* no break */
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
case 'V': case 'W': case 'X': case 'Y': case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y': case 'z':
/* scheme part */
state->buffer[state->offset++] = *state->ptr;
break;
default:
if (!(mb = parse_mb(state, PARSE_SCHEME, state->ptr, state->end, tmp, 1))) {
goto softfail;
}
state->ptr += mb - 1;
}
} while (++state->ptr != state->end);
softfail:
state->offset = 0;
return state->ptr = tmp;
}
| 168,833
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 set_own_dir(const char *argv0) {
size_t l = strlen(argv0);
while(l && argv0[l - 1] != '/')
l--;
if(l == 0)
memcpy(own_dir, ".", 2);
else {
memcpy(own_dir, argv0, l - 1);
own_dir[l] = 0;
}
}
Commit Message: fix for CVE-2015-3887
closes #60
CWE ID: CWE-426
|
static void set_own_dir(const char *argv0) {
size_t l = strlen(argv0);
while(l && argv0[l - 1] != '/')
l--;
if(l == 0)
#ifdef SUPER_SECURE
memcpy(own_dir, "/dev/null/", 2);
#else
memcpy(own_dir, ".", 2);
#endif
else {
memcpy(own_dir, argv0, l - 1);
own_dir[l] = 0;
}
}
| 168,884
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ExtensionTtsController::ExtensionTtsController()
: ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)),
current_utterance_(NULL),
platform_impl_(NULL) {
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
ExtensionTtsController::ExtensionTtsController()
| 170,376
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: archive_read_format_zip_cleanup(struct archive_read *a)
{
struct zip *zip;
struct zip_entry *zip_entry, *next_zip_entry;
zip = (struct zip *)(a->format->data);
#ifdef HAVE_ZLIB_H
if (zip->stream_valid)
inflateEnd(&zip->stream);
#endif
#if HAVA_LZMA_H && HAVE_LIBLZMA
if (zip->zipx_lzma_valid) {
lzma_end(&zip->zipx_lzma_stream);
}
#endif
#ifdef HAVE_BZLIB_H
if (zip->bzstream_valid) {
BZ2_bzDecompressEnd(&zip->bzstream);
}
#endif
free(zip->uncompressed_buffer);
if (zip->ppmd8_valid)
__archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
if (zip->zip_entries) {
zip_entry = zip->zip_entries;
while (zip_entry != NULL) {
next_zip_entry = zip_entry->next;
archive_string_free(&zip_entry->rsrcname);
free(zip_entry);
zip_entry = next_zip_entry;
}
}
free(zip->decrypted_buffer);
if (zip->cctx_valid)
archive_decrypto_aes_ctr_release(&zip->cctx);
if (zip->hctx_valid)
archive_hmac_sha1_cleanup(&zip->hctx);
free(zip->iv);
free(zip->erd);
free(zip->v_data);
archive_string_free(&zip->format_name);
free(zip);
(a->format->data) = NULL;
return (ARCHIVE_OK);
}
Commit Message: Fix typo in preprocessor macro in archive_read_format_zip_cleanup()
Frees lzma_stream on cleanup()
Fixes #1165
CWE ID: CWE-399
|
archive_read_format_zip_cleanup(struct archive_read *a)
{
struct zip *zip;
struct zip_entry *zip_entry, *next_zip_entry;
zip = (struct zip *)(a->format->data);
#ifdef HAVE_ZLIB_H
if (zip->stream_valid)
inflateEnd(&zip->stream);
#endif
#if HAVE_LZMA_H && HAVE_LIBLZMA
if (zip->zipx_lzma_valid) {
lzma_end(&zip->zipx_lzma_stream);
}
#endif
#ifdef HAVE_BZLIB_H
if (zip->bzstream_valid) {
BZ2_bzDecompressEnd(&zip->bzstream);
}
#endif
free(zip->uncompressed_buffer);
if (zip->ppmd8_valid)
__archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
if (zip->zip_entries) {
zip_entry = zip->zip_entries;
while (zip_entry != NULL) {
next_zip_entry = zip_entry->next;
archive_string_free(&zip_entry->rsrcname);
free(zip_entry);
zip_entry = next_zip_entry;
}
}
free(zip->decrypted_buffer);
if (zip->cctx_valid)
archive_decrypto_aes_ctr_release(&zip->cctx);
if (zip->hctx_valid)
archive_hmac_sha1_cleanup(&zip->hctx);
free(zip->iv);
free(zip->erd);
free(zip->v_data);
archive_string_free(&zip->format_name);
free(zip);
(a->format->data) = NULL;
return (ARCHIVE_OK);
}
| 169,695
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: status_t OMXNodeInstance::allocateBufferWithBackup(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
if (params == NULL || buffer == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size()) {
return BAD_VALUE;
}
BufferMeta *buffer_meta = new BufferMeta(params, portIndex, true);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_AllocateBuffer(
mHandle, &header, portIndex, buffer_meta, allottedSize);
if (err != OMX_ErrorNone) {
CLOG_ERROR(allocateBufferWithBackup, err,
SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer()));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p",
params->size(), params->pointer(), allottedSize, header->pBuffer));
return OK;
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200
|
status_t OMXNodeInstance::allocateBufferWithBackup(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
if (params == NULL || buffer == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size() || portIndex >= NELEM(mNumPortBuffers)) {
return BAD_VALUE;
}
// metadata buffers are not connected cross process; only copy if not meta
bool copy = mMetadataType[portIndex] == kMetadataBufferTypeInvalid;
BufferMeta *buffer_meta = new BufferMeta(
params, portIndex,
(portIndex == kPortIndexInput) && copy /* copyToOmx */,
(portIndex == kPortIndexOutput) && copy /* copyFromOmx */,
NULL /* data */);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_AllocateBuffer(
mHandle, &header, portIndex, buffer_meta, allottedSize);
if (err != OMX_ErrorNone) {
CLOG_ERROR(allocateBufferWithBackup, err,
SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer()));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
memset(header->pBuffer, 0, header->nAllocLen);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p",
params->size(), params->pointer(), allottedSize, header->pBuffer));
return OK;
}
| 174,130
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long long BlockGroup::GetDurationTimeCode() const
{
return m_duration;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long long BlockGroup::GetDurationTimeCode() const
| 174,308
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 xmlrpc_char_encode(char *outbuffer, const char *s1)
{
long unsigned int i;
unsigned char c;
char buf2[15];
mowgli_string_t *s = mowgli_string_create();
*buf2 = '\0';
*outbuffer = '\0';
if ((!(s1) || (*(s1) == '\0')))
{
return;
}
for (i = 0; s1[i] != '\0'; i++)
{
c = s1[i];
if (c > 127)
{
snprintf(buf2, sizeof buf2, "&#%d;", c);
s->append(s, buf2, strlen(buf2));
}
else if (c == '&')
{
s->append(s, "&", 5);
}
else if (c == '<')
{
s->append(s, "<", 4);
}
else if (c == '>')
{
s->append(s, ">", 4);
}
else if (c == '"')
{
s->append(s, """, 6);
}
else
{
s->append_char(s, c);
}
}
memcpy(outbuffer, s->str, XMLRPC_BUFSIZE);
}
Commit Message: Do not copy more bytes than were allocated
CWE ID: CWE-119
|
void xmlrpc_char_encode(char *outbuffer, const char *s1)
{
long unsigned int i;
unsigned char c;
char buf2[15];
mowgli_string_t *s = mowgli_string_create();
*buf2 = '\0';
*outbuffer = '\0';
if ((!(s1) || (*(s1) == '\0')))
{
return;
}
for (i = 0; s1[i] != '\0'; i++)
{
c = s1[i];
if (c > 127)
{
snprintf(buf2, sizeof buf2, "&#%d;", c);
s->append(s, buf2, strlen(buf2));
}
else if (c == '&')
{
s->append(s, "&", 5);
}
else if (c == '<')
{
s->append(s, "<", 4);
}
else if (c == '>')
{
s->append(s, ">", 4);
}
else if (c == '"')
{
s->append(s, """, 6);
}
else
{
s->append_char(s, c);
}
}
s->append_char(s, 0);
strncpy(outbuffer, s->str, XMLRPC_BUFSIZE);
}
| 167,260
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::release(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, "Release: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
if (!releaseJob(id.cluster,
id.proc,
reason.c_str(),
true, // Always perform this action within a transaction
false, // Do not email the user about this action
false // Do not email admin about this action
)) {
text = "Failed to release job";
return false;
}
return true;
}
Commit Message:
CWE ID: CWE-20
|
SchedulerObject::release(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, "Release: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
if (!releaseJob(id.cluster,
id.proc,
reason.c_str(),
true, // Always perform this action within a transaction
false, // Do not email the user about this action
false // Do not email admin about this action
)) {
text = "Failed to release job";
return false;
}
return true;
}
| 164,833
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: TemplateURLRef::SearchTermsArgs::ContextualSearchParams::ContextualSearchParams(
int version,
const std::string& selection,
const std::string& base_page_url,
int now_on_tap_version)
: version(version),
start(base::string16::npos),
end(base::string16::npos),
selection(selection),
base_page_url(base_page_url),
now_on_tap_version(now_on_tap_version) {}
Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards"
BUG=644934
Review-Url: https://codereview.chromium.org/2361163003
Cr-Commit-Position: refs/heads/master@{#420899}
CWE ID:
|
TemplateURLRef::SearchTermsArgs::ContextualSearchParams::ContextualSearchParams(
int version,
const std::string& selection,
const std::string& base_page_url,
int contextual_cards_version)
: version(version),
start(base::string16::npos),
end(base::string16::npos),
selection(selection),
base_page_url(base_page_url),
| 171,646
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: BluetoothChooserDesktop::~BluetoothChooserDesktop() {
bluetooth_chooser_controller_->ResetEventHandler();
}
Commit Message: Ensure device choosers are closed on navigation
The requestDevice() IPCs can race with navigation. This change ensures
that choosers are closed on navigation and adds browser tests to
exercise this for Web Bluetooth and WebUSB.
Bug: 723503
Change-Id: I66760161220e17bd2be9309cca228d161fe76e9c
Reviewed-on: https://chromium-review.googlesource.com/1099961
Commit-Queue: Reilly Grant <reillyg@chromium.org>
Reviewed-by: Michael Wasserman <msw@chromium.org>
Reviewed-by: Jeffrey Yasskin <jyasskin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#569900}
CWE ID: CWE-362
|
BluetoothChooserDesktop::~BluetoothChooserDesktop() {
bluetooth_chooser_controller_->ResetEventHandler();
if (bubble_)
bubble_->CloseBubble(BUBBLE_CLOSE_FORCED);
}
| 173,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: void SecurityHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
host_ = frame_host;
if (enabled_ && host_)
AttachToRenderFrameHost();
}
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 <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
void SecurityHandler::SetRenderer(RenderProcessHost* process_host,
void SecurityHandler::SetRenderer(int process_host_id,
RenderFrameHostImpl* frame_host) {
host_ = frame_host;
if (enabled_ && host_)
AttachToRenderFrameHost();
}
| 172,765
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain)
{
int r;
size_t len = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
r = sc_check_sw(card, sm->sw1, sm->sw2);
if (r == SC_SUCCESS) {
if (exdata->sm) {
if (0 != decrypt_response(card, sm->resp, plain->resp, &len))
return SC_ERROR_CARD_CMD_FAILED;
}
else {
memcpy(plain->resp, sm->resp, sm->resplen);
len = sm->resplen;
}
}
plain->resplen = len;
plain->sw1 = sm->sw1;
plain->sw2 = sm->sw2;
sc_log(card->ctx,
"unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X",
plain->resplen, plain->sw1, plain->sw2);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
|
epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain)
{
int r;
size_t len = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
r = sc_check_sw(card, sm->sw1, sm->sw2);
if (r == SC_SUCCESS) {
if (exdata->sm) {
if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len))
return SC_ERROR_CARD_CMD_FAILED;
}
else {
memcpy(plain->resp, sm->resp, sm->resplen);
len = sm->resplen;
}
}
plain->resplen = len;
plain->sw1 = sm->sw1;
plain->sw2 = sm->sw2;
sc_log(card->ctx,
"unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X",
plain->resplen, plain->sw1, plain->sw2);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
| 169,055
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LoadingStatsCollector::RecordPreconnectStats(
std::unique_ptr<PreconnectStats> stats) {
const GURL& main_frame_url = stats->url;
auto it = preconnect_stats_.find(main_frame_url);
if (it != preconnect_stats_.end()) {
ReportPreconnectAccuracy(*it->second,
std::map<GURL, OriginRequestSummary>());
preconnect_stats_.erase(it);
}
preconnect_stats_.emplace(main_frame_url, std::move(stats));
}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org>
Reviewed-by: Alex Ilin <alexilin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125
|
void LoadingStatsCollector::RecordPreconnectStats(
std::unique_ptr<PreconnectStats> stats) {
const GURL& main_frame_url = stats->url;
auto it = preconnect_stats_.find(main_frame_url);
if (it != preconnect_stats_.end()) {
ReportPreconnectAccuracy(*it->second, {});
preconnect_stats_.erase(it);
}
preconnect_stats_.emplace(main_frame_url, std::move(stats));
}
| 172,371
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 on_accept(private_stroke_socket_t *this, stream_t *stream)
{
stroke_msg_t *msg;
uint16_t len;
FILE *out;
/* read length */
if (!stream->read_all(stream, &len, sizeof(len)))
{
if (errno != EWOULDBLOCK)
{
DBG1(DBG_CFG, "reading length of stroke message failed: %s",
strerror(errno));
}
return FALSE;
}
/* read message (we need an additional byte to terminate the buffer) */
msg = malloc(len + 1);
DBG1(DBG_CFG, "reading stroke message failed: %s", strerror(errno));
}
Commit Message:
CWE ID: CWE-787
|
static bool on_accept(private_stroke_socket_t *this, stream_t *stream)
{
stroke_msg_t *msg;
uint16_t len;
FILE *out;
/* read length */
if (!stream->read_all(stream, &len, sizeof(len)))
{
if (errno != EWOULDBLOCK)
{
DBG1(DBG_CFG, "reading length of stroke message failed: %s",
strerror(errno));
}
return FALSE;
}
if (len < offsetof(stroke_msg_t, buffer))
{
DBG1(DBG_CFG, "invalid stroke message length %d", len);
return FALSE;
}
/* read message (we need an additional byte to terminate the buffer) */
msg = malloc(len + 1);
DBG1(DBG_CFG, "reading stroke message failed: %s", strerror(errno));
}
| 165,152
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_connect(gboolean full)
{
int rc = pcmk_ok;
static gboolean need_pass = TRUE;
CRM_CHECK(cib != NULL, return -EINVAL);
if (getenv("CIB_passwd") != NULL) {
need_pass = FALSE;
}
if(watch_fencing && st == NULL) {
st = stonith_api_new();
}
if(watch_fencing && st->state == stonith_disconnected) {
crm_trace("Connecting to stonith");
rc = st->cmds->connect(st, crm_system_name, NULL);
if(rc == pcmk_ok) {
crm_trace("Setting up stonith callbacks");
st->cmds->register_notification(st, T_STONITH_NOTIFY_FENCE, mon_st_callback);
}
}
if (cib->state != cib_connected_query && cib->state != cib_connected_command) {
crm_trace("Connecting to the CIB");
if (as_console && need_pass && cib->variant == cib_remote) {
need_pass = FALSE;
print_as("Password:");
}
rc = cib->cmds->signon(cib, crm_system_name, cib_query);
if (rc != pcmk_ok) {
return rc;
}
current_cib = get_cib_copy(cib);
mon_refresh_display(NULL);
if (full) {
if (rc == pcmk_ok) {
rc = cib->cmds->set_connection_dnotify(cib, mon_cib_connection_destroy);
if (rc == -EPROTONOSUPPORT) {
print_as("Notification setup failed, won't be able to reconnect after failure");
if (as_console) {
sleep(2);
}
rc = pcmk_ok;
}
}
if (rc == pcmk_ok) {
cib->cmds->del_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update);
rc = cib->cmds->add_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update);
}
if (rc != pcmk_ok) {
print_as("Notification setup failed, could not monitor CIB actions");
if (as_console) {
sleep(2);
}
clean_up(-rc);
}
}
}
return rc;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
|
cib_connect(gboolean full)
{
int rc = pcmk_ok;
static gboolean need_pass = TRUE;
CRM_CHECK(cib != NULL, return -EINVAL);
if (getenv("CIB_passwd") != NULL) {
need_pass = FALSE;
}
if(watch_fencing && st == NULL) {
st = stonith_api_new();
}
if(watch_fencing && st->state == stonith_disconnected) {
crm_trace("Connecting to stonith");
rc = st->cmds->connect(st, crm_system_name, NULL);
if(rc == pcmk_ok) {
crm_trace("Setting up stonith callbacks");
st->cmds->register_notification(st, T_STONITH_NOTIFY_FENCE, mon_st_callback);
}
}
if (cib->state != cib_connected_query && cib->state != cib_connected_command) {
crm_trace("Connecting to the CIB");
if (as_console && need_pass && cib->variant == cib_remote) {
need_pass = FALSE;
print_as("Password:");
}
rc = cib->cmds->signon(cib, crm_system_name, cib_query);
if (rc != pcmk_ok) {
return rc;
}
current_cib = get_cib_copy(cib);
mon_refresh_display(NULL);
if (full) {
if (rc == pcmk_ok) {
rc = cib->cmds->set_connection_dnotify(cib, mon_cib_connection_destroy);
if (rc == -EPROTONOSUPPORT) {
print_as("Notification setup not supported, won't be able to reconnect after failure");
if (as_console) {
sleep(2);
}
rc = pcmk_ok;
}
}
if (rc == pcmk_ok) {
cib->cmds->del_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update);
rc = cib->cmds->add_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update);
}
if (rc != pcmk_ok) {
print_as("Notification setup failed, could not monitor CIB actions");
if (as_console) {
sleep(2);
}
clean_up(-rc);
}
}
}
return rc;
}
| 166,165
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static struct nfs4_state *nfs4_do_open(struct inode *dir, struct path *path, int flags, struct iattr *sattr, struct rpc_cred *cred)
{
struct nfs4_exception exception = { };
struct nfs4_state *res;
int status;
do {
status = _nfs4_do_open(dir, path, flags, sattr, cred, &res);
if (status == 0)
break;
/* NOTE: BAD_SEQID means the server and client disagree about the
* book-keeping w.r.t. state-changing operations
* (OPEN/CLOSE/LOCK/LOCKU...)
* It is actually a sign of a bug on the client or on the server.
*
* If we receive a BAD_SEQID error in the particular case of
* doing an OPEN, we assume that nfs_increment_open_seqid() will
* have unhashed the old state_owner for us, and that we can
* therefore safely retry using a new one. We should still warn
* the user though...
*/
if (status == -NFS4ERR_BAD_SEQID) {
printk(KERN_WARNING "NFS: v4 server %s "
" returned a bad sequence-id error!\n",
NFS_SERVER(dir)->nfs_client->cl_hostname);
exception.retry = 1;
continue;
}
/*
* BAD_STATEID on OPEN means that the server cancelled our
* state before it received the OPEN_CONFIRM.
* Recover by retrying the request as per the discussion
* on Page 181 of RFC3530.
*/
if (status == -NFS4ERR_BAD_STATEID) {
exception.retry = 1;
continue;
}
if (status == -EAGAIN) {
/* We must have found a delegation */
exception.retry = 1;
continue;
}
res = ERR_PTR(nfs4_handle_exception(NFS_SERVER(dir),
status, &exception));
} while (exception.retry);
return res;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
CWE ID:
|
static struct nfs4_state *nfs4_do_open(struct inode *dir, struct path *path, int flags, struct iattr *sattr, struct rpc_cred *cred)
static struct nfs4_state *nfs4_do_open(struct inode *dir, struct path *path, fmode_t fmode, int flags, struct iattr *sattr, struct rpc_cred *cred)
{
struct nfs4_exception exception = { };
struct nfs4_state *res;
int status;
do {
status = _nfs4_do_open(dir, path, fmode, flags, sattr, cred, &res);
if (status == 0)
break;
/* NOTE: BAD_SEQID means the server and client disagree about the
* book-keeping w.r.t. state-changing operations
* (OPEN/CLOSE/LOCK/LOCKU...)
* It is actually a sign of a bug on the client or on the server.
*
* If we receive a BAD_SEQID error in the particular case of
* doing an OPEN, we assume that nfs_increment_open_seqid() will
* have unhashed the old state_owner for us, and that we can
* therefore safely retry using a new one. We should still warn
* the user though...
*/
if (status == -NFS4ERR_BAD_SEQID) {
printk(KERN_WARNING "NFS: v4 server %s "
" returned a bad sequence-id error!\n",
NFS_SERVER(dir)->nfs_client->cl_hostname);
exception.retry = 1;
continue;
}
/*
* BAD_STATEID on OPEN means that the server cancelled our
* state before it received the OPEN_CONFIRM.
* Recover by retrying the request as per the discussion
* on Page 181 of RFC3530.
*/
if (status == -NFS4ERR_BAD_STATEID) {
exception.retry = 1;
continue;
}
if (status == -EAGAIN) {
/* We must have found a delegation */
exception.retry = 1;
continue;
}
res = ERR_PTR(nfs4_handle_exception(NFS_SERVER(dir),
status, &exception));
} while (exception.retry);
return res;
}
| 165,692
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ComputePrincipleComponent(const float *covariance,
DDSVector3 *principle)
{
DDSVector4
row0,
row1,
row2,
v;
register ssize_t
i;
row0.x = covariance[0];
row0.y = covariance[1];
row0.z = covariance[2];
row0.w = 0.0f;
row1.x = covariance[1];
row1.y = covariance[3];
row1.z = covariance[4];
row1.w = 0.0f;
row2.x = covariance[2];
row2.y = covariance[4];
row2.z = covariance[5];
row2.w = 0.0f;
VectorInit(v,1.0f);
for (i=0; i < 8; i++)
{
DDSVector4
w;
float
a;
w.x = row0.x * v.x;
w.y = row0.y * v.x;
w.z = row0.z * v.x;
w.w = row0.w * v.x;
w.x = (row1.x * v.y) + w.x;
w.y = (row1.y * v.y) + w.y;
w.z = (row1.z * v.y) + w.z;
w.w = (row1.w * v.y) + w.w;
w.x = (row2.x * v.z) + w.x;
w.y = (row2.y * v.z) + w.y;
w.z = (row2.z * v.z) + w.z;
w.w = (row2.w * v.z) + w.w;
a = 1.0f / MaxF(w.x,MaxF(w.y,w.z));
v.x = w.x * a;
v.y = w.y * a;
v.z = w.z * a;
v.w = w.w * a;
}
VectorCopy43(v,principle);
}
Commit Message: Added extra EOF check and some minor refactoring.
CWE ID: CWE-20
|
static void ComputePrincipleComponent(const float *covariance,
DDSVector3 *principle)
{
DDSVector4
row0,
row1,
row2,
v;
register ssize_t
i;
row0.x = covariance[0];
row0.y = covariance[1];
row0.z = covariance[2];
row0.w = 0.0f;
row1.x = covariance[1];
row1.y = covariance[3];
row1.z = covariance[4];
row1.w = 0.0f;
row2.x = covariance[2];
row2.y = covariance[4];
row2.z = covariance[5];
row2.w = 0.0f;
VectorInit(v,1.0f);
for (i=0; i < 8; i++)
{
DDSVector4
w;
float
a;
w.x = row0.x * v.x;
w.y = row0.y * v.x;
w.z = row0.z * v.x;
w.w = row0.w * v.x;
w.x = (row1.x * v.y) + w.x;
w.y = (row1.y * v.y) + w.y;
w.z = (row1.z * v.y) + w.z;
w.w = (row1.w * v.y) + w.w;
w.x = (row2.x * v.z) + w.x;
w.y = (row2.y * v.z) + w.y;
w.z = (row2.z * v.z) + w.z;
w.w = (row2.w * v.z) + w.w;
a = 1.0f / MagickMax(w.x,MagickMax(w.y,w.z));
v.x = w.x * a;
v.y = w.y * a;
v.z = w.z * a;
v.w = w.w * a;
}
VectorCopy43(v,principle);
}
| 168,898
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PixelChannels **AcquirePixelThreadSet(const Image *images)
{
const Image
*next;
PixelChannels
**pixels;
register ssize_t
i;
size_t
columns,
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(PixelChannels **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (PixelChannels **) NULL)
return((PixelChannels **) NULL);
(void) memset(pixels,0,number_threads*sizeof(*pixels));
columns=images->columns;
for (next=images; next != (Image *) NULL; next=next->next)
columns=MagickMax(next->columns,columns);
for (i=0; i < (ssize_t) number_threads; i++)
{
register ssize_t
j;
pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels));
if (pixels[i] == (PixelChannels *) NULL)
return(DestroyPixelThreadSet(pixels));
for (j=0; j < (ssize_t) columns; j++)
{
register ssize_t
k;
for (k=0; k < MaxPixelChannels; k++)
pixels[i][j].channel[k]=0.0;
}
}
return(pixels);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1615
CWE ID: CWE-119
|
static PixelChannels **AcquirePixelThreadSet(const Image *images)
{
const Image
*next;
PixelChannels
**pixels;
register ssize_t
i;
size_t
columns,
rows;
rows=MagickMax(GetImageListLength(images),
(size_t) GetMagickResourceLimit(ThreadResource));
pixels=(PixelChannels **) AcquireQuantumMemory(rows,sizeof(*pixels));
if (pixels == (PixelChannels **) NULL)
return((PixelChannels **) NULL);
columns=MaxPixelChannels;
for (next=images; next != (Image *) NULL; next=next->next)
columns=MagickMax(next->columns,columns);
for (i=0; i < (ssize_t) rows; i++)
{
register ssize_t
j;
pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels));
if (pixels[i] == (PixelChannels *) NULL)
return(DestroyPixelThreadSet(pixels));
for (j=0; j < (ssize_t) columns; j++)
{
register ssize_t
k;
for (k=0; k < MaxPixelChannels; k++)
pixels[i][j].channel[k]=0.0;
}
}
return(pixels);
}
| 170,201
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_FUNCTION(locale_get_display_language)
{
get_icu_disp_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125
|
PHP_FUNCTION(locale_get_display_language)
PHP_FUNCTION(locale_get_display_language)
{
get_icu_disp_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
| 167,186
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ipv6_dup_options(struct sock *sk, struct ipv6_txoptions *opt)
{
struct ipv6_txoptions *opt2;
opt2 = sock_kmalloc(sk, opt->tot_len, GFP_ATOMIC);
if (opt2) {
long dif = (char *)opt2 - (char *)opt;
memcpy(opt2, opt, opt->tot_len);
if (opt2->hopopt)
*((char **)&opt2->hopopt) += dif;
if (opt2->dst0opt)
*((char **)&opt2->dst0opt) += dif;
if (opt2->dst1opt)
*((char **)&opt2->dst1opt) += dif;
if (opt2->srcrt)
*((char **)&opt2->srcrt) += dif;
}
return opt2;
}
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 <dvyukov@google.com>
Signed-off-by: Eric Dumazet <edumazet@google.com>
Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-416
|
ipv6_dup_options(struct sock *sk, struct ipv6_txoptions *opt)
{
struct ipv6_txoptions *opt2;
opt2 = sock_kmalloc(sk, opt->tot_len, GFP_ATOMIC);
if (opt2) {
long dif = (char *)opt2 - (char *)opt;
memcpy(opt2, opt, opt->tot_len);
if (opt2->hopopt)
*((char **)&opt2->hopopt) += dif;
if (opt2->dst0opt)
*((char **)&opt2->dst0opt) += dif;
if (opt2->dst1opt)
*((char **)&opt2->dst1opt) += dif;
if (opt2->srcrt)
*((char **)&opt2->srcrt) += dif;
atomic_set(&opt2->refcnt, 1);
}
return opt2;
}
| 167,330
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool PrintWebViewHelper::InitPrintSettingsAndPrepareFrame(
WebKit::WebFrame* frame, WebKit::WebNode* node,
scoped_ptr<PrepareFrameAndViewForPrint>* prepare) {
if (!InitPrintSettings(frame, node, false))
return false;
DCHECK(!prepare->get());
prepare->reset(new PrepareFrameAndViewForPrint(print_pages_params_->params,
frame, node));
UpdatePrintableSizeInPrintParameters(frame, node, prepare->get(),
&print_pages_params_->params);
Send(new PrintHostMsg_DidGetDocumentCookie(
routing_id(), print_pages_params_->params.document_cookie));
return true;
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool PrintWebViewHelper::InitPrintSettingsAndPrepareFrame(
WebKit::WebFrame* frame, WebKit::WebNode* node,
scoped_ptr<PrepareFrameAndViewForPrint>* prepare) {
if (!InitPrintSettings(frame))
return false;
DCHECK(!prepare->get());
prepare->reset(new PrepareFrameAndViewForPrint(print_pages_params_->params,
frame, node));
UpdatePrintableSizeInPrintParameters(frame, node, prepare->get(),
&print_pages_params_->params);
Send(new PrintHostMsg_DidGetDocumentCookie(
routing_id(), print_pages_params_->params.document_cookie));
return true;
}
| 170,260
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
jas_stream_t *in)
{
jpc_siz_t *siz = &ms->parms.siz;
unsigned int i;
uint_fast8_t tmp;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (jpc_getuint16(in, &siz->caps) ||
jpc_getuint32(in, &siz->width) ||
jpc_getuint32(in, &siz->height) ||
jpc_getuint32(in, &siz->xoff) ||
jpc_getuint32(in, &siz->yoff) ||
jpc_getuint32(in, &siz->tilewidth) ||
jpc_getuint32(in, &siz->tileheight) ||
jpc_getuint32(in, &siz->tilexoff) ||
jpc_getuint32(in, &siz->tileyoff) ||
jpc_getuint16(in, &siz->numcomps)) {
return -1;
}
if (!siz->width || !siz->height || !siz->tilewidth ||
!siz->tileheight || !siz->numcomps || siz->numcomps > 16384) {
return -1;
}
if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) {
return -1;
}
for (i = 0; i < siz->numcomps; ++i) {
if (jpc_getuint8(in, &tmp) ||
jpc_getuint8(in, &siz->comps[i].hsamp) ||
jpc_getuint8(in, &siz->comps[i].vsamp)) {
jas_free(siz->comps);
return -1;
}
if (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) {
jas_eprintf("invalid XRsiz value %d\n", siz->comps[i].hsamp);
jas_free(siz->comps);
return -1;
}
if (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) {
jas_eprintf("invalid YRsiz value %d\n", siz->comps[i].vsamp);
jas_free(siz->comps);
return -1;
}
siz->comps[i].sgnd = (tmp >> 7) & 1;
siz->comps[i].prec = (tmp & 0x7f) + 1;
}
if (jas_stream_eof(in)) {
jas_free(siz->comps);
return -1;
}
return 0;
}
Commit Message: Ensure that not all tiles lie outside the image area.
CWE ID: CWE-20
|
static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
jas_stream_t *in)
{
jpc_siz_t *siz = &ms->parms.siz;
unsigned int i;
uint_fast8_t tmp;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (jpc_getuint16(in, &siz->caps) ||
jpc_getuint32(in, &siz->width) ||
jpc_getuint32(in, &siz->height) ||
jpc_getuint32(in, &siz->xoff) ||
jpc_getuint32(in, &siz->yoff) ||
jpc_getuint32(in, &siz->tilewidth) ||
jpc_getuint32(in, &siz->tileheight) ||
jpc_getuint32(in, &siz->tilexoff) ||
jpc_getuint32(in, &siz->tileyoff) ||
jpc_getuint16(in, &siz->numcomps)) {
return -1;
}
if (!siz->width || !siz->height || !siz->tilewidth ||
!siz->tileheight || !siz->numcomps || siz->numcomps > 16384) {
return -1;
}
if (siz->tilexoff >= siz->width || siz->tileyoff >= siz->height) {
jas_eprintf("all tiles are outside the image area\n");
return -1;
}
if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) {
return -1;
}
for (i = 0; i < siz->numcomps; ++i) {
if (jpc_getuint8(in, &tmp) ||
jpc_getuint8(in, &siz->comps[i].hsamp) ||
jpc_getuint8(in, &siz->comps[i].vsamp)) {
jas_free(siz->comps);
return -1;
}
if (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) {
jas_eprintf("invalid XRsiz value %d\n", siz->comps[i].hsamp);
jas_free(siz->comps);
return -1;
}
if (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) {
jas_eprintf("invalid YRsiz value %d\n", siz->comps[i].vsamp);
jas_free(siz->comps);
return -1;
}
siz->comps[i].sgnd = (tmp >> 7) & 1;
siz->comps[i].prec = (tmp & 0x7f) + 1;
}
if (jas_stream_eof(in)) {
jas_free(siz->comps);
return -1;
}
return 0;
}
| 168,736
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void DefragTrackerInit(DefragTracker *dt, Packet *p)
{
/* copy address */
COPY_ADDRESS(&p->src, &dt->src_addr);
COPY_ADDRESS(&p->dst, &dt->dst_addr);
if (PKT_IS_IPV4(p)) {
dt->id = (int32_t)IPV4_GET_IPID(p);
dt->af = AF_INET;
} else {
dt->id = (int32_t)IPV6_EXTHDR_GET_FH_ID(p);
dt->af = AF_INET6;
}
dt->vlan_id[0] = p->vlan_id[0];
dt->vlan_id[1] = p->vlan_id[1];
dt->policy = DefragGetOsPolicy(p);
dt->host_timeout = DefragPolicyGetHostTimeout(p);
dt->remove = 0;
dt->seen_last = 0;
TAILQ_INIT(&dt->frags);
(void) DefragTrackerIncrUsecnt(dt);
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358
|
static void DefragTrackerInit(DefragTracker *dt, Packet *p)
{
/* copy address */
COPY_ADDRESS(&p->src, &dt->src_addr);
COPY_ADDRESS(&p->dst, &dt->dst_addr);
if (PKT_IS_IPV4(p)) {
dt->id = (int32_t)IPV4_GET_IPID(p);
dt->af = AF_INET;
} else {
dt->id = (int32_t)IPV6_EXTHDR_GET_FH_ID(p);
dt->af = AF_INET6;
}
dt->proto = IP_GET_IPPROTO(p);
dt->vlan_id[0] = p->vlan_id[0];
dt->vlan_id[1] = p->vlan_id[1];
dt->policy = DefragGetOsPolicy(p);
dt->host_timeout = DefragPolicyGetHostTimeout(p);
dt->remove = 0;
dt->seen_last = 0;
TAILQ_INIT(&dt->frags);
(void) DefragTrackerIncrUsecnt(dt);
}
| 168,293
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: xsltNumberFormatGetAnyLevel(xsltTransformContextPtr context,
xmlNodePtr node,
xsltCompMatchPtr countPat,
xsltCompMatchPtr fromPat,
double *array,
xmlDocPtr doc,
xmlNodePtr elem)
{
int amount = 0;
int cnt = 0;
xmlNodePtr cur;
/* select the starting node */
switch (node->type) {
case XML_ELEMENT_NODE:
cur = node;
break;
case XML_ATTRIBUTE_NODE:
cur = ((xmlAttrPtr) node)->parent;
break;
case XML_TEXT_NODE:
case XML_PI_NODE:
case XML_COMMENT_NODE:
cur = node->parent;
break;
default:
cur = NULL;
break;
}
while (cur != NULL) {
/* process current node */
if (countPat == NULL) {
if ((node->type == cur->type) &&
/* FIXME: must use expanded-name instead of local name */
xmlStrEqual(node->name, cur->name)) {
if ((node->ns == cur->ns) ||
((node->ns != NULL) &&
(cur->ns != NULL) &&
(xmlStrEqual(node->ns->href,
cur->ns->href) )))
cnt++;
}
} else {
if (xsltTestCompMatchList(context, cur, countPat))
cnt++;
}
if ((fromPat != NULL) &&
xsltTestCompMatchList(context, cur, fromPat)) {
break; /* while */
}
/* Skip to next preceding or ancestor */
if ((cur->type == XML_DOCUMENT_NODE) ||
#ifdef LIBXML_DOCB_ENABLED
(cur->type == XML_DOCB_DOCUMENT_NODE) ||
#endif
(cur->type == XML_HTML_DOCUMENT_NODE))
break; /* while */
while ((cur->prev != NULL) && ((cur->prev->type == XML_DTD_NODE) ||
(cur->prev->type == XML_XINCLUDE_START) ||
(cur->prev->type == XML_XINCLUDE_END)))
cur = cur->prev;
if (cur->prev != NULL) {
for (cur = cur->prev; cur->last != NULL; cur = cur->last);
} else {
cur = cur->parent;
}
}
array[amount++] = (double) cnt;
return(amount);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
|
xsltNumberFormatGetAnyLevel(xsltTransformContextPtr context,
xmlNodePtr node,
xsltCompMatchPtr countPat,
xsltCompMatchPtr fromPat,
double *array)
{
int amount = 0;
int cnt = 0;
xmlNodePtr cur;
/* select the starting node */
switch (node->type) {
case XML_ELEMENT_NODE:
cur = node;
break;
case XML_ATTRIBUTE_NODE:
cur = ((xmlAttrPtr) node)->parent;
break;
case XML_TEXT_NODE:
case XML_PI_NODE:
case XML_COMMENT_NODE:
cur = node->parent;
break;
default:
cur = NULL;
break;
}
while (cur != NULL) {
/* process current node */
if (xsltTestCompMatchCount(context, cur, countPat, node))
cnt++;
if ((fromPat != NULL) &&
xsltTestCompMatchList(context, cur, fromPat)) {
break; /* while */
}
/* Skip to next preceding or ancestor */
if ((cur->type == XML_DOCUMENT_NODE) ||
#ifdef LIBXML_DOCB_ENABLED
(cur->type == XML_DOCB_DOCUMENT_NODE) ||
#endif
(cur->type == XML_HTML_DOCUMENT_NODE))
break; /* while */
while ((cur->prev != NULL) && ((cur->prev->type == XML_DTD_NODE) ||
(cur->prev->type == XML_XINCLUDE_START) ||
(cur->prev->type == XML_XINCLUDE_END)))
cur = cur->prev;
if (cur->prev != NULL) {
for (cur = cur->prev; cur->last != NULL; cur = cur->last);
} else {
cur = cur->parent;
}
}
array[amount++] = (double) cnt;
return(amount);
}
| 173,308
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: GF_Err urn_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i, to_read;
char *tmpName;
GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s;
if (! ptr->size ) return GF_OK;
to_read = (u32) ptr->size;
tmpName = (char*)gf_malloc(sizeof(char) * to_read);
if (!tmpName) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, tmpName, to_read);
i = 0;
while ( (tmpName[i] != 0) && (i < to_read) ) {
i++;
}
if (i == to_read) {
gf_free(tmpName);
return GF_ISOM_INVALID_FILE;
}
if (i == to_read - 1) {
ptr->nameURN = tmpName;
ptr->location = NULL;
return GF_OK;
}
ptr->nameURN = (char*)gf_malloc(sizeof(char) * (i+1));
if (!ptr->nameURN) {
gf_free(tmpName);
return GF_OUT_OF_MEM;
}
ptr->location = (char*)gf_malloc(sizeof(char) * (to_read - i - 1));
if (!ptr->location) {
gf_free(tmpName);
gf_free(ptr->nameURN);
ptr->nameURN = NULL;
return GF_OUT_OF_MEM;
}
memcpy(ptr->nameURN, tmpName, i + 1);
memcpy(ptr->location, tmpName + i + 1, (to_read - i - 1));
gf_free(tmpName);
return GF_OK;
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125
|
GF_Err urn_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i, to_read;
char *tmpName;
GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s;
if (! ptr->size ) return GF_OK;
to_read = (u32) ptr->size;
tmpName = (char*)gf_malloc(sizeof(char) * to_read);
if (!tmpName) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, tmpName, to_read);
i = 0;
while ( (i < to_read) && (tmpName[i] != 0) ) {
i++;
}
if (i == to_read) {
gf_free(tmpName);
return GF_ISOM_INVALID_FILE;
}
if (i == to_read - 1) {
ptr->nameURN = tmpName;
ptr->location = NULL;
return GF_OK;
}
ptr->nameURN = (char*)gf_malloc(sizeof(char) * (i+1));
if (!ptr->nameURN) {
gf_free(tmpName);
return GF_OUT_OF_MEM;
}
ptr->location = (char*)gf_malloc(sizeof(char) * (to_read - i - 1));
if (!ptr->location) {
gf_free(tmpName);
gf_free(ptr->nameURN);
ptr->nameURN = NULL;
return GF_OUT_OF_MEM;
}
memcpy(ptr->nameURN, tmpName, i + 1);
memcpy(ptr->location, tmpName + i + 1, (to_read - i - 1));
gf_free(tmpName);
return GF_OK;
}
| 169,167
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cJSON_ReplaceItemInArray( cJSON *array, int which, cJSON *newitem )
{
cJSON *c = array->child;
while ( c && which > 0 ) {
c = c->next;
--which;
}
if ( ! c )
return;
newitem->next = c->next;
newitem->prev = c->prev;
if ( newitem->next )
newitem->next->prev = newitem;
if ( c == array->child )
array->child = newitem;
else
newitem->prev->next = newitem;
c->next = c->prev = 0;
cJSON_Delete( c );
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <bmah@es.net>
CWE ID: CWE-119
|
void cJSON_ReplaceItemInArray( cJSON *array, int which, cJSON *newitem )
| 167,295
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in)
{
jpc_dec_tile_t *tile;
jpc_pi_t *pi;
int ret;
tile = dec->curtile;
pi = tile->pi;
for (;;) {
if (!tile->pkthdrstream || jas_stream_peekc(tile->pkthdrstream) == EOF) {
switch (jpc_dec_lookahead(in)) {
case JPC_MS_EOC:
case JPC_MS_SOT:
return 0;
break;
case JPC_MS_SOP:
case JPC_MS_EPH:
case 0:
break;
default:
return -1;
break;
}
}
if ((ret = jpc_pi_next(pi))) {
return ret;
}
if (dec->maxpkts >= 0 && dec->numpkts >= dec->maxpkts) {
jas_eprintf("warning: stopping decode prematurely as requested\n");
return 0;
}
if (jas_getdbglevel() >= 1) {
jas_eprintf("packet offset=%08ld prg=%d cmptno=%02d "
"rlvlno=%02d prcno=%03d lyrno=%02d\n", (long)
jas_stream_getrwcount(in), jpc_pi_prg(pi), jpc_pi_cmptno(pi),
jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi));
}
if (jpc_dec_decodepkt(dec, pkthdrstream, in, jpc_pi_cmptno(pi), jpc_pi_rlvlno(pi),
jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) {
return -1;
}
++dec->numpkts;
}
return 0;
}
Commit Message: Fixed numerous integer overflow problems in the code for packet iterators
in the JPC decoder.
CWE ID: CWE-125
|
int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in)
{
jpc_dec_tile_t *tile;
jpc_pi_t *pi;
int ret;
tile = dec->curtile;
pi = tile->pi;
for (;;) {
if (!tile->pkthdrstream || jas_stream_peekc(tile->pkthdrstream) == EOF) {
switch (jpc_dec_lookahead(in)) {
case JPC_MS_EOC:
case JPC_MS_SOT:
return 0;
break;
case JPC_MS_SOP:
case JPC_MS_EPH:
case 0:
break;
default:
return -1;
break;
}
}
if ((ret = jpc_pi_next(pi))) {
return ret;
}
if (dec->maxpkts >= 0 && dec->numpkts >= dec->maxpkts) {
jas_eprintf("warning: stopping decode prematurely as requested\n");
return 0;
}
if (jas_getdbglevel() >= 1) {
jas_eprintf("packet offset=%08ld prg=%d cmptno=%02d "
"rlvlno=%02d prcno=%03d lyrno=%02d\n", (long)
jas_stream_getrwcount(in), jpc_pi_prg(pi), jpc_pi_cmptno(pi),
jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi));
}
if (jpc_dec_decodepkt(dec, pkthdrstream, in, jpc_pi_cmptno(pi),
jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) {
return -1;
}
++dec->numpkts;
}
return 0;
}
| 169,443
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings(
const DictionaryValue& job_settings, const PageRanges& ranges) {
#if defined(OS_CHROMEOS)
bool landscape = false;
if (!job_settings.GetBoolean(kSettingLandscape, &landscape))
return OnError();
settings_.SetOrientation(landscape);
settings_.ranges = ranges;
return OK;
#else
DCHECK(!in_print_job_);
if (!print_dialog_->UpdateSettings(job_settings, ranges))
return OnError();
return OK;
#endif
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings(
const DictionaryValue& job_settings, const PageRanges& ranges) {
#if defined(OS_CHROMEOS)
bool landscape = false;
if (!job_settings.GetBoolean(kSettingLandscape, &landscape))
return OnError();
settings_.SetOrientation(landscape);
settings_.ranges = ranges;
return OK;
#else
DCHECK(!in_print_job_);
if (!print_dialog_) {
print_dialog_ = create_dialog_func_(this);
print_dialog_->AddRefToDialog();
}
if (!print_dialog_->UpdateSettings(job_settings, ranges))
return OnError();
return OK;
#endif
}
| 170,267
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 _out_verify(conn_t out, nad_t nad) {
int attr, ns;
jid_t from, to;
conn_t in;
char *rkey;
int valid;
attr = nad_find_attr(nad, 0, -1, "from", NULL);
if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid from on db verify packet");
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "to", NULL);
if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid to on db verify packet");
jid_free(from);
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "id", NULL);
if(attr < 0) {
log_debug(ZONE, "missing id on db verify packet");
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
/* get the incoming conn */
in = xhash_getx(out->s2s->in, NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr));
if(in == NULL) {
log_debug(ZONE, "got a verify for incoming conn %.*s, but it doesn't exist, dropping the packet", NAD_AVAL_L(nad, attr), NAD_AVAL(nad, attr));
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
rkey = s2s_route_key(NULL, to->domain, from->domain);
attr = nad_find_attr(nad, 0, -1, "type", "valid");
if(attr >= 0) {
xhash_put(in->states, pstrdup(xhash_pool(in->states), rkey), (void *) conn_VALID);
log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now valid%s%s", in->fd->fd, in->ip, in->port, rkey, (in->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", in->s->compressed ? ", ZLIB compression enabled" : "");
valid = 1;
} else {
log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now invalid", in->fd->fd, in->ip, in->port, rkey);
valid = 0;
}
free(rkey);
nad_free(nad);
/* decrement outstanding verify counter */
--out->verify;
/* let them know what happened */
nad = nad_new();
ns = nad_add_namespace(nad, uri_DIALBACK, "db");
nad_append_elem(nad, ns, "result", 0);
nad_append_attr(nad, -1, "to", from->domain);
nad_append_attr(nad, -1, "from", to->domain);
nad_append_attr(nad, -1, "type", valid ? "valid" : "invalid");
/* off it goes */
sx_nad_write(in->s, nad);
/* if invalid, close the stream */
if (!valid) {
/* generate stream error */
sx_error(in->s, stream_err_INVALID_ID, "dialback negotiation failed");
/* close the incoming stream */
sx_close(in->s);
}
jid_free(from);
jid_free(to);
}
Commit Message: Fixed possibility of Unsolicited Dialback Attacks
CWE ID: CWE-20
|
static void _out_verify(conn_t out, nad_t nad) {
int attr, ns;
jid_t from, to;
conn_t in;
char *rkey;
int valid;
attr = nad_find_attr(nad, 0, -1, "from", NULL);
if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid from on db verify packet");
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "to", NULL);
if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid to on db verify packet");
jid_free(from);
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "id", NULL);
if(attr < 0) {
log_debug(ZONE, "missing id on db verify packet");
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
/* get the incoming conn */
in = xhash_getx(out->s2s->in, NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr));
if(in == NULL) {
log_debug(ZONE, "got a verify for incoming conn %.*s, but it doesn't exist, dropping the packet", NAD_AVAL_L(nad, attr), NAD_AVAL(nad, attr));
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
rkey = s2s_route_key(NULL, to->domain, from->domain);
attr = nad_find_attr(nad, 0, -1, "type", "valid");
if(attr >= 0 && xhash_get(in->states, rkey) == (void*) conn_INPROGRESS) {
xhash_put(in->states, pstrdup(xhash_pool(in->states), rkey), (void *) conn_VALID);
log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now valid%s%s", in->fd->fd, in->ip, in->port, rkey, (in->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", in->s->compressed ? ", ZLIB compression enabled" : "");
valid = 1;
} else {
log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now invalid", in->fd->fd, in->ip, in->port, rkey);
valid = 0;
}
free(rkey);
nad_free(nad);
/* decrement outstanding verify counter */
--out->verify;
/* let them know what happened */
nad = nad_new();
ns = nad_add_namespace(nad, uri_DIALBACK, "db");
nad_append_elem(nad, ns, "result", 0);
nad_append_attr(nad, -1, "to", from->domain);
nad_append_attr(nad, -1, "from", to->domain);
nad_append_attr(nad, -1, "type", valid ? "valid" : "invalid");
/* off it goes */
sx_nad_write(in->s, nad);
/* if invalid, close the stream */
if (!valid) {
/* generate stream error */
sx_error(in->s, stream_err_INVALID_ID, "dialback negotiation failed");
/* close the incoming stream */
sx_close(in->s);
}
jid_free(from);
jid_free(to);
}
| 165,577
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 StopCast() {
CastConfigDelegate* cast_config =
Shell::GetInstance()->system_tray_delegate()->GetCastConfigDelegate();
if (cast_config && cast_config->HasCastExtension()) {
cast_config->GetReceiversAndActivities(
base::Bind(&StopCastCallback, cast_config));
}
}
Commit Message: Allow the cast tray to function as expected when the installed extension is missing API methods.
BUG=489445
Review URL: https://codereview.chromium.org/1145833003
Cr-Commit-Position: refs/heads/master@{#330663}
CWE ID: CWE-79
|
void StopCast() {
| 171,625
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: hb_buffer_clear (hb_buffer_t *buffer)
{
buffer->have_output = FALSE;
buffer->have_positions = FALSE;
buffer->len = 0;
buffer->out_len = 0;
buffer->i = 0;
buffer->max_lig_id = 0;
buffer->max_lig_id = 0;
}
Commit Message:
CWE ID:
|
hb_buffer_clear (hb_buffer_t *buffer)
{
buffer->have_output = FALSE;
buffer->have_positions = FALSE;
buffer->in_error = FALSE;
buffer->len = 0;
buffer->out_len = 0;
buffer->i = 0;
buffer->max_lig_id = 0;
buffer->max_lig_id = 0;
}
| 164,772
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 read_header_tga(gdIOCtx *ctx, oTga *tga)
{
unsigned char header[18];
if (gdGetBuf(header, sizeof(header), ctx) < 18) {
gd_error("fail to read header");
return -1;
}
tga->identsize = header[0];
tga->colormaptype = header[1];
tga->imagetype = header[2];
tga->colormapstart = header[3] + (header[4] << 8);
tga->colormaplength = header[5] + (header[6] << 8);
tga->colormapbits = header[7];
tga->xstart = header[8] + (header[9] << 8);
tga->ystart = header[10] + (header[11] << 8);
tga->width = header[12] + (header[13] << 8);
tga->height = header[14] + (header[15] << 8);
tga->bits = header[16];
tga->alphabits = header[17] & 0x0f;
tga->fliph = (header[17] & 0x10) ? 1 : 0;
tga->flipv = (header[17] & 0x20) ? 0 : 1;
#if DEBUG
printf("format bps: %i\n", tga->bits);
printf("flip h/v: %i / %i\n", tga->fliph, tga->flipv);
printf("alpha: %i\n", tga->alphabits);
printf("wxh: %i %i\n", tga->width, tga->height);
#endif
switch(tga->bits) {
case 8:
case 16:
case 24:
case 32:
break;
default:
gd_error("bps %i not supported", tga->bits);
return -1;
break;
}
tga->ident = NULL;
if (tga->identsize > 0) {
tga->ident = (char *) gdMalloc(tga->identsize * sizeof(char));
if(tga->ident == NULL) {
return -1;
}
gdGetBuf(tga->ident, tga->identsize, ctx);
}
return 1;
}
Commit Message: Unsupported TGA bpp/alphabit combinations should error gracefully
Currently, only 24bpp without alphabits and 32bpp with 8 alphabits are
really supported. All other combinations will be rejected with a warning.
CWE ID: CWE-125
|
int read_header_tga(gdIOCtx *ctx, oTga *tga)
{
unsigned char header[18];
if (gdGetBuf(header, sizeof(header), ctx) < 18) {
gd_error("fail to read header");
return -1;
}
tga->identsize = header[0];
tga->colormaptype = header[1];
tga->imagetype = header[2];
tga->colormapstart = header[3] + (header[4] << 8);
tga->colormaplength = header[5] + (header[6] << 8);
tga->colormapbits = header[7];
tga->xstart = header[8] + (header[9] << 8);
tga->ystart = header[10] + (header[11] << 8);
tga->width = header[12] + (header[13] << 8);
tga->height = header[14] + (header[15] << 8);
tga->bits = header[16];
tga->alphabits = header[17] & 0x0f;
tga->fliph = (header[17] & 0x10) ? 1 : 0;
tga->flipv = (header[17] & 0x20) ? 0 : 1;
#if DEBUG
printf("format bps: %i\n", tga->bits);
printf("flip h/v: %i / %i\n", tga->fliph, tga->flipv);
printf("alpha: %i\n", tga->alphabits);
printf("wxh: %i %i\n", tga->width, tga->height);
#endif
if (!((tga->bits == TGA_BPP_24 && tga->alphabits == 0)
|| (tga->bits == TGA_BPP_32 && tga->alphabits == 8)))
{
gd_error_ex(GD_WARNING, "gd-tga: %u bits per pixel with %u alpha bits not supported\n",
tga->bits, tga->alphabits);
return -1;
}
tga->ident = NULL;
if (tga->identsize > 0) {
tga->ident = (char *) gdMalloc(tga->identsize * sizeof(char));
if(tga->ident == NULL) {
return -1;
}
gdGetBuf(tga->ident, tga->identsize, ctx);
}
return 1;
}
| 167,005
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: u32 h264bsdInit(storage_t *pStorage, u32 noOutputReordering)
{
/* Variables */
u32 size;
/* Code */
ASSERT(pStorage);
h264bsdInitStorage(pStorage);
/* allocate mbLayer to be next multiple of 64 to enable use of
* specific NEON optimized "memset" for clearing the structure */
size = (sizeof(macroblockLayer_t) + 63) & ~0x3F;
pStorage->mbLayer = (macroblockLayer_t*)H264SwDecMalloc(size);
if (!pStorage->mbLayer)
return HANTRO_NOK;
if (noOutputReordering)
pStorage->noReordering = HANTRO_TRUE;
return HANTRO_OK;
}
Commit Message: h264dec: check for overflows when calculating allocation size.
Bug: 27855419
Change-Id: Idabedca52913ec31ea5cb6a6109ab94e3fb2badd
CWE ID: CWE-119
|
u32 h264bsdInit(storage_t *pStorage, u32 noOutputReordering)
{
/* Variables */
u32 size;
/* Code */
ASSERT(pStorage);
h264bsdInitStorage(pStorage);
/* allocate mbLayer to be next multiple of 64 to enable use of
* specific NEON optimized "memset" for clearing the structure */
size = (sizeof(macroblockLayer_t) + 63) & ~0x3F;
pStorage->mbLayer = (macroblockLayer_t*)H264SwDecMalloc(size, 1);
if (!pStorage->mbLayer)
return HANTRO_NOK;
if (noOutputReordering)
pStorage->noReordering = HANTRO_TRUE;
return HANTRO_OK;
}
| 173,876
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PermissionsData::CanCaptureVisiblePage(
const GURL& document_url,
int tab_id,
std::string* error,
CaptureRequirement capture_requirement) const {
bool has_active_tab = false;
bool has_all_urls = false;
bool has_page_capture = false;
url::Origin origin = url::Origin::Create(document_url);
const GURL origin_url = origin.GetURL();
{
base::AutoLock auto_lock(runtime_lock_);
if (location_ != Manifest::COMPONENT &&
IsPolicyBlockedHostUnsafe(origin_url)) {
if (error)
*error = extension_misc::kPolicyBlockedScripting;
return false;
}
const PermissionSet* tab_permissions = GetTabSpecificPermissions(tab_id);
has_active_tab = tab_permissions &&
tab_permissions->HasAPIPermission(APIPermission::kTab);
const URLPattern all_urls(URLPattern::SCHEME_ALL,
URLPattern::kAllUrlsPattern);
has_all_urls =
active_permissions_unsafe_->explicit_hosts().ContainsPattern(all_urls);
has_page_capture = active_permissions_unsafe_->HasAPIPermission(
APIPermission::kPageCapture);
}
std::string access_error;
if (capture_requirement == CaptureRequirement::kActiveTabOrAllUrls) {
if (!has_active_tab && !has_all_urls) {
if (error)
*error = manifest_errors::kAllURLOrActiveTabNeeded;
return false;
}
if (GetPageAccess(origin_url, tab_id, &access_error) ==
PageAccess::kAllowed)
return true;
} else {
DCHECK_EQ(CaptureRequirement::kPageCapture, capture_requirement);
if (!has_page_capture) {
if (error)
*error = manifest_errors::kPageCaptureNeeded;
}
if ((origin_url.SchemeIs(url::kHttpScheme) ||
origin_url.SchemeIs(url::kHttpsScheme)) &&
!origin.IsSameOriginWith(url::Origin::Create(
ExtensionsClient::Get()->GetWebstoreBaseURL()))) {
return true;
}
}
if (origin_url.host() == extension_id_)
return true;
bool allowed_with_active_tab =
origin_url.SchemeIs(content::kChromeUIScheme) ||
origin_url.SchemeIs(kExtensionScheme) ||
document_url.SchemeIs(url::kDataScheme) ||
origin.IsSameOriginWith(
url::Origin::Create(ExtensionsClient::Get()->GetWebstoreBaseURL()));
if (!allowed_with_active_tab) {
if (error)
*error = access_error;
return false;
}
if (has_active_tab)
return true;
if (error)
*error = manifest_errors::kActiveTabPermissionNotGranted;
return false;
}
Commit Message: [Extensions] Have URLPattern::Contains() properly check schemes
Have URLPattern::Contains() properly check the schemes of the patterns
when evaluating if one pattern contains another. This is important in
order to prevent extensions from requesting chrome:-scheme permissions
via the permissions API when <all_urls> is specified as an optional
permission.
Bug: 859600,918470
Change-Id: If04d945ad0c939e84a80d83502c0f84b6ef0923d
Reviewed-on: https://chromium-review.googlesource.com/c/1396561
Commit-Queue: Devlin <rdevlin.cronin@chromium.org>
Reviewed-by: Karan Bhatia <karandeepb@chromium.org>
Cr-Commit-Position: refs/heads/master@{#621410}
CWE ID: CWE-79
|
bool PermissionsData::CanCaptureVisiblePage(
const GURL& document_url,
int tab_id,
std::string* error,
CaptureRequirement capture_requirement) const {
bool has_active_tab = false;
bool has_all_urls = false;
bool has_page_capture = false;
url::Origin origin = url::Origin::Create(document_url);
const GURL origin_url = origin.GetURL();
{
base::AutoLock auto_lock(runtime_lock_);
if (location_ != Manifest::COMPONENT &&
IsPolicyBlockedHostUnsafe(origin_url)) {
if (error)
*error = extension_misc::kPolicyBlockedScripting;
return false;
}
const PermissionSet* tab_permissions = GetTabSpecificPermissions(tab_id);
has_active_tab = tab_permissions &&
tab_permissions->HasAPIPermission(APIPermission::kTab);
// Check if any of the host permissions match all urls. We don't use
// URLPatternSet::ContainsPattern() here because a) the schemes may be
// different and b) this is more efficient.
for (const auto& pattern : active_permissions_unsafe_->explicit_hosts()) {
if (pattern.match_all_urls()) {
has_all_urls = true;
break;
}
}
has_page_capture = active_permissions_unsafe_->HasAPIPermission(
APIPermission::kPageCapture);
}
std::string access_error;
if (capture_requirement == CaptureRequirement::kActiveTabOrAllUrls) {
if (!has_active_tab && !has_all_urls) {
if (error)
*error = manifest_errors::kAllURLOrActiveTabNeeded;
return false;
}
if (GetPageAccess(origin_url, tab_id, &access_error) ==
PageAccess::kAllowed)
return true;
} else {
DCHECK_EQ(CaptureRequirement::kPageCapture, capture_requirement);
if (!has_page_capture) {
if (error)
*error = manifest_errors::kPageCaptureNeeded;
}
if ((origin_url.SchemeIs(url::kHttpScheme) ||
origin_url.SchemeIs(url::kHttpsScheme)) &&
!origin.IsSameOriginWith(url::Origin::Create(
ExtensionsClient::Get()->GetWebstoreBaseURL()))) {
return true;
}
}
if (origin_url.host() == extension_id_)
return true;
bool allowed_with_active_tab =
origin_url.SchemeIs(content::kChromeUIScheme) ||
origin_url.SchemeIs(kExtensionScheme) ||
document_url.SchemeIs(url::kDataScheme) ||
origin.IsSameOriginWith(
url::Origin::Create(ExtensionsClient::Get()->GetWebstoreBaseURL()));
if (!allowed_with_active_tab) {
if (error)
*error = access_error;
return false;
}
if (has_active_tab)
return true;
if (error)
*error = manifest_errors::kActiveTabPermissionNotGranted;
return false;
}
| 173,119
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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: static byte parseHexByte(const char * &str) {
byte b = parseHexChar(str[0]);
if (str[1] == ':' || str[1] == '\0') {
str += 2;
return b;
} else {
b = b << 4 | parseHexChar(str[1]);
str += 3;
return b;
}
}
Commit Message: Deal correctly with short strings
The parseMacAddress function anticipates only properly formed
MAC addresses (6 hexadecimal octets separated by ":"). This
change properly deals with situations where the string is
shorter than expected, making sure that the passed in char*
reference in parseHexByte never exceeds the end of the string.
BUG: 28164077
TEST: Added a main function:
int main(int argc, char **argv) {
unsigned char addr[6];
if (argc > 1) {
memset(addr, 0, sizeof(addr));
parseMacAddress(argv[1], addr);
printf("Result: %02x:%02x:%02x:%02x:%02x:%02x\n",
addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
}
}
Tested with "", "a" "ab" "ab:c" "abxc".
Change-Id: I0db8d0037e48b62333d475296a45b22ab0efe386
CWE ID: CWE-200
|
static byte parseHexByte(const char * &str) {
if (str[0] == '\0') {
ALOGE("Passed an empty string");
return 0;
}
byte b = parseHexChar(str[0]);
if (str[1] == '\0' || str[1] == ':') {
str ++;
} else {
b = b << 4 | parseHexChar(str[1]);
str += 2;
}
// Skip trailing delimiter if not at the end of the string.
if (str[0] != '\0') {
str++;
}
return b;
}
| 173,500
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped");
gfx::PluginWindowHandle handle =
GpuSurfaceTracker::Get()->GetSurfaceWindowHandle(params.surface_id);
if (handle != gfx::kNullPluginWindow) {
RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
return;
}
base::ScopedClosureRunner scoped_completion_runner(
base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU,
host_id_, params.route_id,
true /* alive */, false /* presented */));
int render_process_id = 0;
int render_widget_id = 0;
if (!GpuSurfaceTracker::Get()->GetRenderWidgetIDForSurface(
params.surface_id, &render_process_id, &render_widget_id)) {
return;
}
RenderWidgetHelper* helper =
RenderWidgetHelper::FromProcessHostID(render_process_id);
if (!helper)
return;
scoped_completion_runner.Release();
helper->DidReceiveBackingStoreMsg(ViewHostMsg_CompositorSurfaceBuffersSwapped(
render_widget_id,
params.surface_id,
params.surface_handle,
params.route_id,
params.size,
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
TBR=sky@chromium.org
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 GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped");
gfx::PluginWindowHandle handle =
GpuSurfaceTracker::Get()->GetSurfaceWindowHandle(params.surface_id);
if (handle != gfx::kNullPluginWindow) {
RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
return;
}
base::ScopedClosureRunner scoped_completion_runner(
base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU,
host_id_, params.route_id,
true /* alive */, params.surface_handle));
int render_process_id = 0;
int render_widget_id = 0;
if (!GpuSurfaceTracker::Get()->GetRenderWidgetIDForSurface(
params.surface_id, &render_process_id, &render_widget_id)) {
return;
}
RenderWidgetHelper* helper =
RenderWidgetHelper::FromProcessHostID(render_process_id);
if (!helper)
return;
scoped_completion_runner.Release();
helper->DidReceiveBackingStoreMsg(ViewHostMsg_CompositorSurfaceBuffersSwapped(
render_widget_id,
params.surface_id,
params.surface_handle,
params.route_id,
params.size,
host_id_));
}
| 171,355
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_read_mmco_commands(struct _DecStruct * ps_dec)
{
dec_bit_stream_t *ps_bitstrm = ps_dec->ps_bitstrm;
dpb_commands_t *ps_dpb_cmds = ps_dec->ps_dpb_cmds;
dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice;
WORD32 j;
UWORD8 u1_buf_mode;
struct MMCParams *ps_mmc_params;
UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
UWORD32 u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst;
ps_slice->u1_mmco_equalto5 = 0;
{
if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL)
{
ps_slice->u1_no_output_of_prior_pics_flag =
ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: no_output_of_prior_pics_flag",
ps_slice->u1_no_output_of_prior_pics_flag);
ps_slice->u1_long_term_reference_flag = ih264d_get_bit_h264(
ps_bitstrm);
COPYTHECONTEXT("SH: long_term_reference_flag",
ps_slice->u1_long_term_reference_flag);
ps_dpb_cmds->u1_idr_pic = 1;
ps_dpb_cmds->u1_no_output_of_prior_pics_flag =
ps_slice->u1_no_output_of_prior_pics_flag;
ps_dpb_cmds->u1_long_term_reference_flag =
ps_slice->u1_long_term_reference_flag;
}
else
{
u1_buf_mode = ih264d_get_bit_h264(ps_bitstrm); //0 - sliding window; 1 - arbitrary
COPYTHECONTEXT("SH: adaptive_ref_pic_buffering_flag", u1_buf_mode);
ps_dpb_cmds->u1_buf_mode = u1_buf_mode;
j = 0;
if(u1_buf_mode == 1)
{
UWORD32 u4_mmco;
UWORD32 u4_diff_pic_num;
UWORD32 u4_lt_idx, u4_max_lt_idx;
u4_mmco = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
while(u4_mmco != END_OF_MMCO)
{
ps_mmc_params = &ps_dpb_cmds->as_mmc_params[j];
ps_mmc_params->u4_mmco = u4_mmco;
switch(u4_mmco)
{
case MARK_ST_PICNUM_AS_NONREF:
u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num;
break;
case MARK_LT_INDEX_AS_NONREF:
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
case MARK_ST_PICNUM_AS_LT_INDEX:
u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num;
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
case SET_MAX_LT_INDEX:
{
u4_max_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_max_lt_idx_plus1 = u4_max_lt_idx;
break;
}
case RESET_REF_PICTURES:
{
ps_slice->u1_mmco_equalto5 = 1;
break;
}
case SET_LT_INDEX:
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
default:
break;
}
u4_mmco = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
j++;
}
ps_dpb_cmds->u1_num_of_commands = j;
}
}
ps_dpb_cmds->u1_dpb_commands_read = 1;
ps_dpb_cmds->u1_dpb_commands_read_slc = 1;
}
u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst - u4_bit_ofst;
return u4_bit_ofst;
}
Commit Message: Return error when there are more mmco params than allocated size
Bug: 25818142
Change-Id: I5c1b23985eeca5192b42703c627ca3d060e4e13d
CWE ID: CWE-119
|
WORD32 ih264d_read_mmco_commands(struct _DecStruct * ps_dec)
{
dec_bit_stream_t *ps_bitstrm = ps_dec->ps_bitstrm;
dpb_commands_t *ps_dpb_cmds = ps_dec->ps_dpb_cmds;
dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice;
WORD32 j;
UWORD8 u1_buf_mode;
struct MMCParams *ps_mmc_params;
UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
UWORD32 u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst;
ps_slice->u1_mmco_equalto5 = 0;
{
if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL)
{
ps_slice->u1_no_output_of_prior_pics_flag =
ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: no_output_of_prior_pics_flag",
ps_slice->u1_no_output_of_prior_pics_flag);
ps_slice->u1_long_term_reference_flag = ih264d_get_bit_h264(
ps_bitstrm);
COPYTHECONTEXT("SH: long_term_reference_flag",
ps_slice->u1_long_term_reference_flag);
ps_dpb_cmds->u1_idr_pic = 1;
ps_dpb_cmds->u1_no_output_of_prior_pics_flag =
ps_slice->u1_no_output_of_prior_pics_flag;
ps_dpb_cmds->u1_long_term_reference_flag =
ps_slice->u1_long_term_reference_flag;
}
else
{
u1_buf_mode = ih264d_get_bit_h264(ps_bitstrm); //0 - sliding window; 1 - arbitrary
COPYTHECONTEXT("SH: adaptive_ref_pic_buffering_flag", u1_buf_mode);
ps_dpb_cmds->u1_buf_mode = u1_buf_mode;
j = 0;
if(u1_buf_mode == 1)
{
UWORD32 u4_mmco;
UWORD32 u4_diff_pic_num;
UWORD32 u4_lt_idx, u4_max_lt_idx;
u4_mmco = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
while(u4_mmco != END_OF_MMCO)
{
if (j >= MAX_REF_BUFS)
{
ALOGE("b/25818142");
android_errorWriteLog(0x534e4554, "25818142");
ps_dpb_cmds->u1_num_of_commands = 0;
return -1;
}
ps_mmc_params = &ps_dpb_cmds->as_mmc_params[j];
ps_mmc_params->u4_mmco = u4_mmco;
switch(u4_mmco)
{
case MARK_ST_PICNUM_AS_NONREF:
u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num;
break;
case MARK_LT_INDEX_AS_NONREF:
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
case MARK_ST_PICNUM_AS_LT_INDEX:
u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num;
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
case SET_MAX_LT_INDEX:
{
u4_max_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_max_lt_idx_plus1 = u4_max_lt_idx;
break;
}
case RESET_REF_PICTURES:
{
ps_slice->u1_mmco_equalto5 = 1;
break;
}
case SET_LT_INDEX:
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
default:
break;
}
u4_mmco = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
j++;
}
ps_dpb_cmds->u1_num_of_commands = j;
}
}
ps_dpb_cmds->u1_dpb_commands_read = 1;
ps_dpb_cmds->u1_dpb_commands_read_slc = 1;
}
u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst - u4_bit_ofst;
return u4_bit_ofst;
}
| 173,907
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_seq_ioctl_remove_events(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_remove_events info;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
/*
* Input mostly not implemented XXX.
*/
if (info.remove_mode & SNDRV_SEQ_REMOVE_INPUT) {
/*
* No restrictions so for a user client we can clear
* the whole fifo
*/
if (client->type == USER_CLIENT)
snd_seq_fifo_clear(client->data.user.fifo);
}
if (info.remove_mode & SNDRV_SEQ_REMOVE_OUTPUT)
snd_seq_queue_remove_cells(client->number, &info);
return 0;
}
Commit Message: ALSA: seq: Fix missing NULL check at remove_events ioctl
snd_seq_ioctl_remove_events() calls snd_seq_fifo_clear()
unconditionally even if there is no FIFO assigned, and this leads to
an Oops due to NULL dereference. The fix is just to add a proper NULL
check.
Reported-by: Dmitry Vyukov <dvyukov@google.com>
Tested-by: Dmitry Vyukov <dvyukov@google.com>
Cc: <stable@vger.kernel.org>
Signed-off-by: Takashi Iwai <tiwai@suse.de>
CWE ID:
|
static int snd_seq_ioctl_remove_events(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_remove_events info;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
/*
* Input mostly not implemented XXX.
*/
if (info.remove_mode & SNDRV_SEQ_REMOVE_INPUT) {
/*
* No restrictions so for a user client we can clear
* the whole fifo
*/
if (client->type == USER_CLIENT && client->data.user.fifo)
snd_seq_fifo_clear(client->data.user.fifo);
}
if (info.remove_mode & SNDRV_SEQ_REMOVE_OUTPUT)
snd_seq_queue_remove_cells(client->number, &info);
return 0;
}
| 167,410
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: BufferMeta(size_t size)
: mSize(size),
mIsBackup(false) {
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119
|
BufferMeta(size_t size)
BufferMeta(size_t size, OMX_U32 portIndex)
: mSize(size),
mIsBackup(false),
mPortIndex(portIndex) {
}
| 173,522
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
ULONG tcpipDataAt;
tTcpIpPacketParsingResult res = _res;
tcpipDataAt = ipHeaderSize + sizeof(TCPHeader);
res.xxpStatus = ppresXxpIncomplete;
res.TcpUdp = ppresIsTCP;
if (len >= tcpipDataAt)
{
TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
res.xxpStatus = ppresXxpKnown;
tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader);
res.XxpIpHeaderSize = tcpipDataAt;
}
else
{
DPrintf(2, ("tcp: %d < min headers %d\n", len, tcpipDataAt));
}
return res;
}
Commit Message: NetKVM: BZ#1169718: More rigoruous testing of incoming packet
Signed-off-by: Joseph Hindin <yhindin@rehat.com>
CWE ID: CWE-20
|
ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
ULONG tcpipDataAt;
tTcpIpPacketParsingResult res = _res;
tcpipDataAt = ipHeaderSize + sizeof(TCPHeader);
res.TcpUdp = ppresIsTCP;
if (len >= tcpipDataAt)
{
TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
res.xxpStatus = ppresXxpKnown;
res.xxpFull = TRUE;
tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader);
res.XxpIpHeaderSize = tcpipDataAt;
}
else
{
DPrintf(2, ("tcp: %d < min headers %d\n", len, tcpipDataAt));
res.xxpFull = FALSE;
res.xxpStatus = ppresXxpIncomplete;
}
return res;
}
| 168,889
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool AXNodeObject::isMultiSelectable() const {
const AtomicString& ariaMultiSelectable =
getAttribute(aria_multiselectableAttr);
if (equalIgnoringCase(ariaMultiSelectable, "true"))
return true;
if (equalIgnoringCase(ariaMultiSelectable, "false"))
return false;
return isHTMLSelectElement(getNode()) &&
toHTMLSelectElement(*getNode()).isMultiple();
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
|
bool AXNodeObject::isMultiSelectable() const {
const AtomicString& ariaMultiSelectable =
getAttribute(aria_multiselectableAttr);
if (equalIgnoringASCIICase(ariaMultiSelectable, "true"))
return true;
if (equalIgnoringASCIICase(ariaMultiSelectable, "false"))
return false;
return isHTMLSelectElement(getNode()) &&
toHTMLSelectElement(*getNode()).isMultiple();
}
| 171,917
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void coroutine_fn v9fs_link(void *opaque)
{
V9fsPDU *pdu = opaque;
int32_t dfid, oldfid;
V9fsFidState *dfidp, *oldfidp;
V9fsString name;
size_t offset = 7;
int err = 0;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dds", &dfid, &oldfid, &name);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_link(pdu->tag, pdu->id, dfid, oldfid, name.data);
if (name_is_illegal(name.data)) {
err = -ENOENT;
goto out_nofid;
}
if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
err = -EEXIST;
goto out_nofid;
}
dfidp = get_fid(pdu, dfid);
if (dfidp == NULL) {
err = -ENOENT;
goto out_nofid;
}
oldfidp = get_fid(pdu, oldfid);
if (oldfidp == NULL) {
err = -ENOENT;
goto out;
}
err = v9fs_co_link(pdu, oldfidp, dfidp, &name);
if (!err) {
err = offset;
}
out:
put_fid(pdu, dfidp);
out_nofid:
pdu_complete(pdu, err);
}
Commit Message:
CWE ID: CWE-399
|
static void coroutine_fn v9fs_link(void *opaque)
{
V9fsPDU *pdu = opaque;
int32_t dfid, oldfid;
V9fsFidState *dfidp, *oldfidp;
V9fsString name;
size_t offset = 7;
int err = 0;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dds", &dfid, &oldfid, &name);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_link(pdu->tag, pdu->id, dfid, oldfid, name.data);
if (name_is_illegal(name.data)) {
err = -ENOENT;
goto out_nofid;
}
if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
err = -EEXIST;
goto out_nofid;
}
dfidp = get_fid(pdu, dfid);
if (dfidp == NULL) {
err = -ENOENT;
goto out_nofid;
}
oldfidp = get_fid(pdu, oldfid);
if (oldfidp == NULL) {
err = -ENOENT;
goto out;
}
err = v9fs_co_link(pdu, oldfidp, dfidp, &name);
if (!err) {
err = offset;
}
put_fid(pdu, oldfidp);
out:
put_fid(pdu, dfidp);
out_nofid:
pdu_complete(pdu, err);
}
| 164,907
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
unsigned long int req, void *buf,
BlockCompletionFunc *cb, void *opaque)
{
IscsiLun *iscsilun = bs->opaque;
struct iscsi_context *iscsi = iscsilun->iscsi;
struct iscsi_data data;
IscsiAIOCB *acb;
acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
acb->iscsilun = iscsilun;
acb->bh = NULL;
acb->status = -EINPROGRESS;
acb->buf = NULL;
acb->ioh = buf;
if (req != SG_IO) {
iscsi_ioctl_handle_emulated(acb, req, buf);
return &acb->common;
}
acb->task = malloc(sizeof(struct scsi_task));
if (acb->task == NULL) {
error_report("iSCSI: Failed to allocate task for scsi command. %s",
case SG_DXFER_TO_DEV:
acb->task->xfer_dir = SCSI_XFER_WRITE;
break;
case SG_DXFER_FROM_DEV:
acb->task->xfer_dir = SCSI_XFER_READ;
break;
default:
acb->task->xfer_dir = SCSI_XFER_NONE;
break;
}
acb->task->cdb_size = acb->ioh->cmd_len;
memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
acb->task->expxferlen = acb->ioh->dxfer_len;
data.size = 0;
if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
if (acb->ioh->iovec_count == 0) {
data.data = acb->ioh->dxferp;
data.size = acb->ioh->dxfer_len;
} else {
scsi_task_set_iov_out(acb->task,
(struct scsi_iovec *) acb->ioh->dxferp,
acb->ioh->iovec_count);
}
}
if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
iscsi_aio_ioctl_cb,
(data.size > 0) ? &data : NULL,
acb) != 0) {
scsi_free_scsi_task(acb->task);
qemu_aio_unref(acb);
return NULL;
}
/* tell libiscsi to read straight into the buffer we got from ioctl */
if (acb->task->xfer_dir == SCSI_XFER_READ) {
if (acb->ioh->iovec_count == 0) {
scsi_task_add_data_in_buffer(acb->task,
acb->ioh->dxfer_len,
acb->ioh->dxferp);
} else {
scsi_task_set_iov_in(acb->task,
(struct scsi_iovec *) acb->ioh->dxferp,
acb->ioh->iovec_count);
}
}
iscsi_set_events(iscsilun);
return &acb->common;
}
Commit Message:
CWE ID: CWE-119
|
static BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
unsigned long int req, void *buf,
BlockCompletionFunc *cb, void *opaque)
{
IscsiLun *iscsilun = bs->opaque;
struct iscsi_context *iscsi = iscsilun->iscsi;
struct iscsi_data data;
IscsiAIOCB *acb;
acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
acb->iscsilun = iscsilun;
acb->bh = NULL;
acb->status = -EINPROGRESS;
acb->buf = NULL;
acb->ioh = buf;
if (req != SG_IO) {
iscsi_ioctl_handle_emulated(acb, req, buf);
return &acb->common;
}
if (acb->ioh->cmd_len > SCSI_CDB_MAX_SIZE) {
error_report("iSCSI: ioctl error CDB exceeds max size (%d > %d)",
acb->ioh->cmd_len, SCSI_CDB_MAX_SIZE);
qemu_aio_unref(acb);
return NULL;
}
acb->task = malloc(sizeof(struct scsi_task));
if (acb->task == NULL) {
error_report("iSCSI: Failed to allocate task for scsi command. %s",
case SG_DXFER_TO_DEV:
acb->task->xfer_dir = SCSI_XFER_WRITE;
break;
case SG_DXFER_FROM_DEV:
acb->task->xfer_dir = SCSI_XFER_READ;
break;
default:
acb->task->xfer_dir = SCSI_XFER_NONE;
break;
}
acb->task->cdb_size = acb->ioh->cmd_len;
memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
acb->task->expxferlen = acb->ioh->dxfer_len;
data.size = 0;
if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
if (acb->ioh->iovec_count == 0) {
data.data = acb->ioh->dxferp;
data.size = acb->ioh->dxfer_len;
} else {
scsi_task_set_iov_out(acb->task,
(struct scsi_iovec *) acb->ioh->dxferp,
acb->ioh->iovec_count);
}
}
if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
iscsi_aio_ioctl_cb,
(data.size > 0) ? &data : NULL,
acb) != 0) {
scsi_free_scsi_task(acb->task);
qemu_aio_unref(acb);
return NULL;
}
/* tell libiscsi to read straight into the buffer we got from ioctl */
if (acb->task->xfer_dir == SCSI_XFER_READ) {
if (acb->ioh->iovec_count == 0) {
scsi_task_add_data_in_buffer(acb->task,
acb->ioh->dxfer_len,
acb->ioh->dxferp);
} else {
scsi_task_set_iov_in(acb->task,
(struct scsi_iovec *) acb->ioh->dxferp,
acb->ioh->iovec_count);
}
}
iscsi_set_events(iscsilun);
return &acb->common;
}
| 165,014
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void ext4_put_super(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int i, err;
ext4_unregister_li_request(sb);
dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
flush_workqueue(sbi->rsv_conversion_wq);
destroy_workqueue(sbi->rsv_conversion_wq);
if (sbi->s_journal) {
err = jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
if (err < 0)
ext4_abort(sb, "Couldn't clean up the journal");
}
ext4_unregister_sysfs(sb);
ext4_es_unregister_shrinker(sbi);
del_timer_sync(&sbi->s_err_report);
ext4_release_system_zone(sb);
ext4_mb_release(sb);
ext4_ext_release(sb);
ext4_xattr_put_super(sb);
if (!(sb->s_flags & MS_RDONLY)) {
ext4_clear_feature_journal_needs_recovery(sb);
es->s_state = cpu_to_le16(sbi->s_mount_state);
}
if (!(sb->s_flags & MS_RDONLY))
ext4_commit_super(sb, 1);
for (i = 0; i < sbi->s_gdb_count; i++)
brelse(sbi->s_group_desc[i]);
kvfree(sbi->s_group_desc);
kvfree(sbi->s_flex_groups);
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
brelse(sbi->s_sbh);
#ifdef CONFIG_QUOTA
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
/* Debugging code just in case the in-memory inode orphan list
* isn't empty. The on-disk one can be non-empty if we've
* detected an error and taken the fs readonly, but the
* in-memory list had better be clean by this point. */
if (!list_empty(&sbi->s_orphan))
dump_orphan_list(sb, sbi);
J_ASSERT(list_empty(&sbi->s_orphan));
sync_blockdev(sb->s_bdev);
invalidate_bdev(sb->s_bdev);
if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) {
/*
* Invalidate the journal device's buffers. We don't want them
* floating about in memory - the physical journal device may
* hotswapped, and it breaks the `ro-after' testing code.
*/
sync_blockdev(sbi->journal_bdev);
invalidate_bdev(sbi->journal_bdev);
ext4_blkdev_remove(sbi);
}
if (sbi->s_mb_cache) {
ext4_xattr_destroy_cache(sbi->s_mb_cache);
sbi->s_mb_cache = NULL;
}
if (sbi->s_mmp_tsk)
kthread_stop(sbi->s_mmp_tsk);
sb->s_fs_info = NULL;
/*
* Now that we are completely done shutting down the
* superblock, we need to actually destroy the kobject.
*/
kobject_put(&sbi->s_kobj);
wait_for_completion(&sbi->s_kobj_unregister);
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
CWE ID: CWE-19
|
static void ext4_put_super(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int i, err;
ext4_unregister_li_request(sb);
dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
flush_workqueue(sbi->rsv_conversion_wq);
destroy_workqueue(sbi->rsv_conversion_wq);
if (sbi->s_journal) {
err = jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
if (err < 0)
ext4_abort(sb, "Couldn't clean up the journal");
}
ext4_unregister_sysfs(sb);
ext4_es_unregister_shrinker(sbi);
del_timer_sync(&sbi->s_err_report);
ext4_release_system_zone(sb);
ext4_mb_release(sb);
ext4_ext_release(sb);
if (!(sb->s_flags & MS_RDONLY)) {
ext4_clear_feature_journal_needs_recovery(sb);
es->s_state = cpu_to_le16(sbi->s_mount_state);
}
if (!(sb->s_flags & MS_RDONLY))
ext4_commit_super(sb, 1);
for (i = 0; i < sbi->s_gdb_count; i++)
brelse(sbi->s_group_desc[i]);
kvfree(sbi->s_group_desc);
kvfree(sbi->s_flex_groups);
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
brelse(sbi->s_sbh);
#ifdef CONFIG_QUOTA
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
/* Debugging code just in case the in-memory inode orphan list
* isn't empty. The on-disk one can be non-empty if we've
* detected an error and taken the fs readonly, but the
* in-memory list had better be clean by this point. */
if (!list_empty(&sbi->s_orphan))
dump_orphan_list(sb, sbi);
J_ASSERT(list_empty(&sbi->s_orphan));
sync_blockdev(sb->s_bdev);
invalidate_bdev(sb->s_bdev);
if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) {
/*
* Invalidate the journal device's buffers. We don't want them
* floating about in memory - the physical journal device may
* hotswapped, and it breaks the `ro-after' testing code.
*/
sync_blockdev(sbi->journal_bdev);
invalidate_bdev(sbi->journal_bdev);
ext4_blkdev_remove(sbi);
}
if (sbi->s_mb_cache) {
ext4_xattr_destroy_cache(sbi->s_mb_cache);
sbi->s_mb_cache = NULL;
}
if (sbi->s_mmp_tsk)
kthread_stop(sbi->s_mmp_tsk);
sb->s_fs_info = NULL;
/*
* Now that we are completely done shutting down the
* superblock, we need to actually destroy the kobject.
*/
kobject_put(&sbi->s_kobj);
wait_for_completion(&sbi->s_kobj_unregister);
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
}
| 169,987
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: struct import_t* MACH0_(get_imports)(struct MACH0_(obj_t)* bin) {
struct import_t *imports;
int i, j, idx, stridx;
const char *symstr;
if (!bin->symtab || !bin->symstr || !bin->sects || !bin->indirectsyms)
return NULL;
if (bin->dysymtab.nundefsym < 1 || bin->dysymtab.nundefsym > 0xfffff) {
return NULL;
}
if (!(imports = malloc ((bin->dysymtab.nundefsym + 1) * sizeof (struct import_t)))) {
return NULL;
}
for (i = j = 0; i < bin->dysymtab.nundefsym; i++) {
idx = bin->dysymtab.iundefsym + i;
if (idx < 0 || idx >= bin->nsymtab) {
bprintf ("WARNING: Imports index out of bounds. Ignoring relocs\n");
free (imports);
return NULL;
}
stridx = bin->symtab[idx].n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char *)bin->symstr + stridx;
} else {
symstr = "";
}
if (!*symstr) {
continue;
}
{
int i = 0;
int len = 0;
char *symstr_dup = NULL;
len = bin->symstrlen - stridx;
imports[j].name[0] = 0;
if (len > 0) {
for (i = 0; i < len; i++) {
if ((unsigned char)symstr[i] == 0xff || !symstr[i]) {
len = i;
break;
}
}
symstr_dup = r_str_ndup (symstr, len);
if (symstr_dup) {
r_str_ncpy (imports[j].name, symstr_dup, R_BIN_MACH0_STRING_LENGTH);
r_str_filter (imports[j].name, - 1);
imports[j].name[R_BIN_MACH0_STRING_LENGTH - 2] = 0;
free (symstr_dup);
}
}
}
imports[j].ord = i;
imports[j++].last = 0;
}
imports[j].last = 1;
if (!bin->imports_by_ord_size) {
if (j > 0) {
bin->imports_by_ord_size = j;
bin->imports_by_ord = (RBinImport**)calloc (j, sizeof (RBinImport*));
} else {
bin->imports_by_ord_size = 0;
bin->imports_by_ord = NULL;
}
}
return imports;
}
Commit Message: Fix #9970 - heap oobread in mach0 parser (#10026)
CWE ID: CWE-125
|
struct import_t* MACH0_(get_imports)(struct MACH0_(obj_t)* bin) {
struct import_t *imports;
int i, j, idx, stridx;
const char *symstr;
if (!bin->symtab || !bin->symstr || !bin->sects || !bin->indirectsyms) {
return NULL;
}
if (bin->dysymtab.nundefsym < 1 || bin->dysymtab.nundefsym > 0xfffff) {
return NULL;
}
if (!(imports = malloc ((bin->dysymtab.nundefsym + 1) * sizeof (struct import_t)))) {
return NULL;
}
for (i = j = 0; i < bin->dysymtab.nundefsym; i++) {
idx = bin->dysymtab.iundefsym + i;
if (idx < 0 || idx >= bin->nsymtab) {
bprintf ("WARNING: Imports index out of bounds. Ignoring relocs\n");
free (imports);
return NULL;
}
stridx = bin->symtab[idx].n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char *)bin->symstr + stridx;
} else {
symstr = "";
}
if (!*symstr) {
continue;
}
{
int i = 0;
int len = 0;
char *symstr_dup = NULL;
len = bin->symstrlen - stridx;
imports[j].name[0] = 0;
if (len > 0) {
for (i = 0; i < len; i++) {
if ((unsigned char)symstr[i] == 0xff || !symstr[i]) {
len = i;
break;
}
}
symstr_dup = r_str_ndup (symstr, len);
if (symstr_dup) {
r_str_ncpy (imports[j].name, symstr_dup, R_BIN_MACH0_STRING_LENGTH);
r_str_filter (imports[j].name, - 1);
imports[j].name[R_BIN_MACH0_STRING_LENGTH - 2] = 0;
free (symstr_dup);
}
}
}
imports[j].ord = i;
imports[j++].last = 0;
}
imports[j].last = 1;
if (!bin->imports_by_ord_size) {
if (j > 0) {
bin->imports_by_ord_size = j;
bin->imports_by_ord = (RBinImport**)calloc (j, sizeof (RBinImport*));
} else {
bin->imports_by_ord_size = 0;
bin->imports_by_ord = NULL;
}
}
return imports;
}
| 169,225
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: std::string SanitizeRevision(const std::string& revision) {
for (size_t i = 0; i < revision.length(); i++) {
if (!(revision[i] == '@' && i == 0)
&& !(revision[i] >= '0' && revision[i] <= '9')
&& !(revision[i] >= 'a' && revision[i] <= 'z')
&& !(revision[i] >= 'A' && revision[i] <= 'Z')) {
return std::string();
}
}
return revision;
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
CWE ID: CWE-200
|
std::string SanitizeRevision(const std::string& revision) {
| 172,464
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
{
int dy = y1 - y0;
int adx = x1 - x0;
int ady = abs(dy);
int base;
int x=x0,y=y0;
int err = 0;
int sy;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
if (dy < 0) {
base = -integer_divide_table[ady][adx];
sy = base-1;
} else {
base = integer_divide_table[ady][adx];
sy = base+1;
}
} else {
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
}
#else
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
#endif
ady -= abs(base) * adx;
if (x1 > n) x1 = n;
if (x < x1) {
LINE_OP(output[x], inverse_db_table[y]);
for (++x; x < x1; ++x) {
err += ady;
if (err >= adx) {
err -= adx;
y += sy;
} else
y += base;
LINE_OP(output[x], inverse_db_table[y]);
}
}
}
Commit Message: Fix seven bugs discovered and fixed by ForAllSecure:
CVE-2019-13217: heap buffer overflow in start_decoder()
CVE-2019-13218: stack buffer overflow in compute_codewords()
CVE-2019-13219: uninitialized memory in vorbis_decode_packet_rest()
CVE-2019-13220: out-of-range read in draw_line()
CVE-2019-13221: issue with large 1D codebooks in lookup1_values()
CVE-2019-13222: unchecked NULL returned by get_window()
CVE-2019-13223: division by zero in predict_point()
CWE ID: CWE-20
|
static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
{
int dy = y1 - y0;
int adx = x1 - x0;
int ady = abs(dy);
int base;
int x=x0,y=y0;
int err = 0;
int sy;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
if (dy < 0) {
base = -integer_divide_table[ady][adx];
sy = base-1;
} else {
base = integer_divide_table[ady][adx];
sy = base+1;
}
} else {
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
}
#else
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
#endif
ady -= abs(base) * adx;
if (x1 > n) x1 = n;
if (x < x1) {
LINE_OP(output[x], inverse_db_table[y&255]);
for (++x; x < x1; ++x) {
err += ady;
if (err >= adx) {
err -= adx;
y += sy;
} else
y += base;
LINE_OP(output[x], inverse_db_table[y&255]);
}
}
}
| 169,614
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: NTSTATUS check_reduced_name_with_privilege(connection_struct *conn,
const char *fname,
struct smb_request *smbreq)
{
NTSTATUS status;
TALLOC_CTX *ctx = talloc_tos();
const char *conn_rootdir;
size_t rootdir_len;
char *dir_name = NULL;
const char *last_component = NULL;
char *resolved_name = NULL;
char *saved_dir = NULL;
struct smb_filename *smb_fname_cwd = NULL;
struct privilege_paths *priv_paths = NULL;
int ret;
DEBUG(3,("check_reduced_name_with_privilege [%s] [%s]\n",
fname,
priv_paths = talloc_zero(smbreq, struct privilege_paths);
if (!priv_paths) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (!parent_dirname(ctx, fname, &dir_name, &last_component)) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
priv_paths->parent_name.base_name = talloc_strdup(priv_paths, dir_name);
priv_paths->file_name.base_name = talloc_strdup(priv_paths, last_component);
if (priv_paths->parent_name.base_name == NULL ||
priv_paths->file_name.base_name == NULL) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (SMB_VFS_STAT(conn, &priv_paths->parent_name) != 0) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Remember where we were. */
saved_dir = vfs_GetWd(ctx, conn);
if (!saved_dir) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Go to the parent directory to lock in memory. */
if (vfs_ChDir(conn, priv_paths->parent_name.base_name) == -1) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Get the absolute path of the parent directory. */
resolved_name = SMB_VFS_REALPATH(conn,".");
if (!resolved_name) {
status = map_nt_error_from_unix(errno);
goto err;
}
if (*resolved_name != '/') {
DEBUG(0,("check_reduced_name_with_privilege: realpath "
"doesn't return absolute paths !\n"));
status = NT_STATUS_OBJECT_NAME_INVALID;
goto err;
}
DEBUG(10,("check_reduced_name_with_privilege: realpath [%s] -> [%s]\n",
priv_paths->parent_name.base_name,
resolved_name));
/* Now check the stat value is the same. */
smb_fname_cwd = synthetic_smb_fname(talloc_tos(), ".", NULL, NULL);
if (smb_fname_cwd == NULL) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (SMB_VFS_LSTAT(conn, smb_fname_cwd) != 0) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Ensure we're pointing at the same place. */
if (!check_same_stat(&smb_fname_cwd->st, &priv_paths->parent_name.st)) {
DEBUG(0,("check_reduced_name_with_privilege: "
"device/inode/uid/gid on directory %s changed. "
"Denying access !\n",
priv_paths->parent_name.base_name));
status = NT_STATUS_ACCESS_DENIED;
goto err;
}
/* Ensure we're below the connect path. */
conn_rootdir = SMB_VFS_CONNECTPATH(conn, fname);
if (conn_rootdir == NULL) {
DEBUG(2, ("check_reduced_name_with_privilege: Could not get "
"conn_rootdir\n"));
status = NT_STATUS_ACCESS_DENIED;
goto err;
}
}
Commit Message:
CWE ID: CWE-264
|
NTSTATUS check_reduced_name_with_privilege(connection_struct *conn,
const char *fname,
struct smb_request *smbreq)
{
NTSTATUS status;
TALLOC_CTX *ctx = talloc_tos();
const char *conn_rootdir;
size_t rootdir_len;
char *dir_name = NULL;
const char *last_component = NULL;
char *resolved_name = NULL;
char *saved_dir = NULL;
struct smb_filename *smb_fname_cwd = NULL;
struct privilege_paths *priv_paths = NULL;
int ret;
bool matched;
DEBUG(3,("check_reduced_name_with_privilege [%s] [%s]\n",
fname,
priv_paths = talloc_zero(smbreq, struct privilege_paths);
if (!priv_paths) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (!parent_dirname(ctx, fname, &dir_name, &last_component)) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
priv_paths->parent_name.base_name = talloc_strdup(priv_paths, dir_name);
priv_paths->file_name.base_name = talloc_strdup(priv_paths, last_component);
if (priv_paths->parent_name.base_name == NULL ||
priv_paths->file_name.base_name == NULL) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (SMB_VFS_STAT(conn, &priv_paths->parent_name) != 0) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Remember where we were. */
saved_dir = vfs_GetWd(ctx, conn);
if (!saved_dir) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Go to the parent directory to lock in memory. */
if (vfs_ChDir(conn, priv_paths->parent_name.base_name) == -1) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Get the absolute path of the parent directory. */
resolved_name = SMB_VFS_REALPATH(conn,".");
if (!resolved_name) {
status = map_nt_error_from_unix(errno);
goto err;
}
if (*resolved_name != '/') {
DEBUG(0,("check_reduced_name_with_privilege: realpath "
"doesn't return absolute paths !\n"));
status = NT_STATUS_OBJECT_NAME_INVALID;
goto err;
}
DEBUG(10,("check_reduced_name_with_privilege: realpath [%s] -> [%s]\n",
priv_paths->parent_name.base_name,
resolved_name));
/* Now check the stat value is the same. */
smb_fname_cwd = synthetic_smb_fname(talloc_tos(), ".", NULL, NULL);
if (smb_fname_cwd == NULL) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (SMB_VFS_LSTAT(conn, smb_fname_cwd) != 0) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Ensure we're pointing at the same place. */
if (!check_same_stat(&smb_fname_cwd->st, &priv_paths->parent_name.st)) {
DEBUG(0,("check_reduced_name_with_privilege: "
"device/inode/uid/gid on directory %s changed. "
"Denying access !\n",
priv_paths->parent_name.base_name));
status = NT_STATUS_ACCESS_DENIED;
goto err;
}
/* Ensure we're below the connect path. */
conn_rootdir = SMB_VFS_CONNECTPATH(conn, fname);
if (conn_rootdir == NULL) {
DEBUG(2, ("check_reduced_name_with_privilege: Could not get "
"conn_rootdir\n"));
status = NT_STATUS_ACCESS_DENIED;
goto err;
}
}
| 164,683
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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;
}
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: jpeg2000: check log2_cblk dimensions
Fixes out of array access
Fixes Ticket2895
Found-by: Piotr Bandurski <ami_stuff@o2.pl>
Signed-off-by: Michael Niedermayer <michaelni@gmx.at>
CWE ID: CWE-119
|
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;
}
| 165,920
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.