instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int parallels_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVParallelsState *s = bs->opaque;
int i;
struct parallels_header ph;
int ret;
bs->read_only = 1; // no write support yet
ret = bdrv_pread(bs->file, 0, &ph, sizeof(ph));
if (ret < 0) {
goto fail;
}
if (memcmp(ph.magic, HEADER_MAGIC, 16) ||
(le32_to_cpu(ph.version) != HEADER_VERSION)) {
error_setg(errp, "Image not in Parallels format");
ret = -EINVAL;
goto fail;
}
bs->total_sectors = le32_to_cpu(ph.nb_sectors);
s->tracks = le32_to_cpu(ph.tracks);
s->catalog_size = le32_to_cpu(ph.catalog_entries);
s->catalog_bitmap = g_malloc(s->catalog_size * 4);
ret = bdrv_pread(bs->file, 64, s->catalog_bitmap, s->catalog_size * 4);
le32_to_cpus(&s->catalog_bitmap[i]);
qemu_co_mutex_init(&s->lock);
return 0;
fail:
g_free(s->catalog_bitmap);
return ret;
}
Commit Message:
CWE ID: CWE-190 | static int parallels_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVParallelsState *s = bs->opaque;
int i;
struct parallels_header ph;
int ret;
bs->read_only = 1; // no write support yet
ret = bdrv_pread(bs->file, 0, &ph, sizeof(ph));
if (ret < 0) {
goto fail;
}
if (memcmp(ph.magic, HEADER_MAGIC, 16) ||
(le32_to_cpu(ph.version) != HEADER_VERSION)) {
error_setg(errp, "Image not in Parallels format");
ret = -EINVAL;
goto fail;
}
bs->total_sectors = le32_to_cpu(ph.nb_sectors);
s->tracks = le32_to_cpu(ph.tracks);
s->catalog_size = le32_to_cpu(ph.catalog_entries);
if (s->catalog_size > INT_MAX / 4) {
error_setg(errp, "Catalog too large");
ret = -EFBIG;
goto fail;
}
s->catalog_bitmap = g_malloc(s->catalog_size * 4);
ret = bdrv_pread(bs->file, 64, s->catalog_bitmap, s->catalog_size * 4);
le32_to_cpus(&s->catalog_bitmap[i]);
qemu_co_mutex_init(&s->lock);
return 0;
fail:
g_free(s->catalog_bitmap);
return ret;
}
| 165,410 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline unsigned short ReadPropertyUnsignedShort(const EndianType endian,
const unsigned char *buffer)
{
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) ((buffer[1] << 8) | buffer[0]);
return((unsigned short) (value & 0xffff));
}
value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) |
((unsigned char *) buffer)[1]);
return((unsigned short) (value & 0xffff));
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static inline unsigned short ReadPropertyUnsignedShort(const EndianType endian,
const unsigned char *buffer)
{
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) buffer[1] << 8;
value|=(unsigned short) buffer[0];
return(value & 0xffff);
}
value=(unsigned short) buffer[0] << 8;
value|=(unsigned short) buffer[1];
return(value & 0xffff);
}
| 169,957 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ModuleExport size_t RegisterMPCImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CACHE");
entry->description=ConstantString("Magick Persistent Cache image format");
entry->module=ConstantString("MPC");
entry->seekable_stream=MagickTrue;
entry->stealth=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("MPC");
entry->decoder=(DecodeImageHandler *) ReadMPCImage;
entry->encoder=(EncodeImageHandler *) WriteMPCImage;
entry->magick=(IsImageFormatHandler *) IsMPC;
entry->description=ConstantString("Magick Persistent Cache image format");
entry->seekable_stream=MagickTrue;
entry->module=ConstantString("MPC");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
Commit Message: ...
CWE ID: CWE-20 | ModuleExport size_t RegisterMPCImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CACHE");
entry->description=ConstantString("Magick Persistent Cache image format");
entry->module=ConstantString("MPC");
entry->stealth=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("MPC");
entry->decoder=(DecodeImageHandler *) ReadMPCImage;
entry->encoder=(EncodeImageHandler *) WriteMPCImage;
entry->magick=(IsImageFormatHandler *) IsMPC;
entry->description=ConstantString("Magick Persistent Cache image format");
entry->seekable_stream=MagickTrue;
entry->module=ConstantString("MPC");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
| 170,040 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: chdlc_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p)
{
register u_int length = h->len;
register u_int caplen = h->caplen;
if (caplen < CHDLC_HDRLEN) {
ND_PRINT((ndo, "[|chdlc]"));
return (caplen);
}
return (chdlc_print(ndo, p,length));
}
Commit Message: CVE-2017-13687/CHDLC: Improve bounds and length checks.
Prevent a possible buffer overread in chdlc_print() and replace the
custom check in chdlc_if_print() with a standard check in chdlc_print()
so that the latter certainly does not over-read even when reached via
juniper_chdlc_print(). Add length checks.
CWE ID: CWE-125 | chdlc_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p)
{
return chdlc_print(ndo, p, h->len);
}
| 170,021 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int chacha20_poly1305_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,
void *ptr)
{
EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx);
switch(type) {
case EVP_CTRL_INIT:
if (actx == NULL)
actx = ctx->cipher_data
= OPENSSL_zalloc(sizeof(*actx) + Poly1305_ctx_size());
if (actx == NULL) {
EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_INITIALIZATION_ERROR);
return 0;
}
actx->len.aad = 0;
actx->len.text = 0;
actx->aad = 0;
actx->mac_inited = 0;
actx->tag_len = 0;
actx->nonce_len = 12;
actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH;
return 1;
case EVP_CTRL_COPY:
if (actx) {
EVP_CIPHER_CTX *dst = (EVP_CIPHER_CTX *)ptr;
dst->cipher_data =
OPENSSL_memdup(actx, sizeof(*actx) + Poly1305_ctx_size());
if (dst->cipher_data == NULL) {
EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_COPY_ERROR);
return 0;
}
}
return 1;
case EVP_CTRL_AEAD_SET_IVLEN:
if (arg <= 0 || arg > CHACHA_CTR_SIZE)
return 0;
actx->nonce_len = arg;
return 1;
case EVP_CTRL_AEAD_SET_IV_FIXED:
if (arg != 12)
return 0;
actx->nonce[0] = actx->key.counter[1]
= CHACHA_U8TOU32((unsigned char *)ptr);
actx->nonce[1] = actx->key.counter[2]
= CHACHA_U8TOU32((unsigned char *)ptr+4);
actx->nonce[2] = actx->key.counter[3]
= CHACHA_U8TOU32((unsigned char *)ptr+8);
return 1;
case EVP_CTRL_AEAD_SET_TAG:
if (arg <= 0 || arg > POLY1305_BLOCK_SIZE)
return 0;
if (ptr != NULL) {
memcpy(actx->tag, ptr, arg);
actx->tag_len = arg;
}
return 1;
case EVP_CTRL_AEAD_GET_TAG:
if (arg <= 0 || arg > POLY1305_BLOCK_SIZE || !ctx->encrypt)
return 0;
memcpy(ptr, actx->tag, arg);
return 1;
case EVP_CTRL_AEAD_TLS1_AAD:
if (arg != EVP_AEAD_TLS1_AAD_LEN)
return 0;
{
unsigned int len;
unsigned char *aad = ptr, temp[POLY1305_BLOCK_SIZE];
len = aad[EVP_AEAD_TLS1_AAD_LEN - 2] << 8 |
aad[EVP_AEAD_TLS1_AAD_LEN - 1];
if (!ctx->encrypt) {
len -= POLY1305_BLOCK_SIZE; /* discount attached tag */
memcpy(temp, aad, EVP_AEAD_TLS1_AAD_LEN - 2);
aad = temp;
temp[EVP_AEAD_TLS1_AAD_LEN - 2] = (unsigned char)(len >> 8);
temp[EVP_AEAD_TLS1_AAD_LEN - 1] = (unsigned char)len;
}
actx->tls_payload_length = len;
/*
* merge record sequence number as per
* draft-ietf-tls-chacha20-poly1305-03
*/
actx->key.counter[1] = actx->nonce[0];
actx->key.counter[2] = actx->nonce[1] ^ CHACHA_U8TOU32(aad);
actx->key.counter[3] = actx->nonce[2] ^ CHACHA_U8TOU32(aad+4);
actx->mac_inited = 0;
chacha20_poly1305_cipher(ctx, NULL, aad, EVP_AEAD_TLS1_AAD_LEN);
return POLY1305_BLOCK_SIZE; /* tag length */
}
case EVP_CTRL_AEAD_SET_MAC_KEY:
/* no-op */
return 1;
default:
return -1;
}
}
Commit Message: crypto/evp: harden AEAD ciphers.
Originally a crash in 32-bit build was reported CHACHA20-POLY1305
cipher. The crash is triggered by truncated packet and is result
of excessive hashing to the edge of accessible memory. Since hash
operation is read-only it is not considered to be exploitable
beyond a DoS condition. Other ciphers were hardened.
Thanks to Robert Święcki for report.
CVE-2017-3731
Reviewed-by: Rich Salz <[email protected]>
CWE ID: CWE-125 | static int chacha20_poly1305_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,
void *ptr)
{
EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx);
switch(type) {
case EVP_CTRL_INIT:
if (actx == NULL)
actx = ctx->cipher_data
= OPENSSL_zalloc(sizeof(*actx) + Poly1305_ctx_size());
if (actx == NULL) {
EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_INITIALIZATION_ERROR);
return 0;
}
actx->len.aad = 0;
actx->len.text = 0;
actx->aad = 0;
actx->mac_inited = 0;
actx->tag_len = 0;
actx->nonce_len = 12;
actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH;
return 1;
case EVP_CTRL_COPY:
if (actx) {
EVP_CIPHER_CTX *dst = (EVP_CIPHER_CTX *)ptr;
dst->cipher_data =
OPENSSL_memdup(actx, sizeof(*actx) + Poly1305_ctx_size());
if (dst->cipher_data == NULL) {
EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_COPY_ERROR);
return 0;
}
}
return 1;
case EVP_CTRL_AEAD_SET_IVLEN:
if (arg <= 0 || arg > CHACHA_CTR_SIZE)
return 0;
actx->nonce_len = arg;
return 1;
case EVP_CTRL_AEAD_SET_IV_FIXED:
if (arg != 12)
return 0;
actx->nonce[0] = actx->key.counter[1]
= CHACHA_U8TOU32((unsigned char *)ptr);
actx->nonce[1] = actx->key.counter[2]
= CHACHA_U8TOU32((unsigned char *)ptr+4);
actx->nonce[2] = actx->key.counter[3]
= CHACHA_U8TOU32((unsigned char *)ptr+8);
return 1;
case EVP_CTRL_AEAD_SET_TAG:
if (arg <= 0 || arg > POLY1305_BLOCK_SIZE)
return 0;
if (ptr != NULL) {
memcpy(actx->tag, ptr, arg);
actx->tag_len = arg;
}
return 1;
case EVP_CTRL_AEAD_GET_TAG:
if (arg <= 0 || arg > POLY1305_BLOCK_SIZE || !ctx->encrypt)
return 0;
memcpy(ptr, actx->tag, arg);
return 1;
case EVP_CTRL_AEAD_TLS1_AAD:
if (arg != EVP_AEAD_TLS1_AAD_LEN)
return 0;
{
unsigned int len;
unsigned char *aad = ptr, temp[POLY1305_BLOCK_SIZE];
len = aad[EVP_AEAD_TLS1_AAD_LEN - 2] << 8 |
aad[EVP_AEAD_TLS1_AAD_LEN - 1];
if (!ctx->encrypt) {
if (len < POLY1305_BLOCK_SIZE)
return 0;
len -= POLY1305_BLOCK_SIZE; /* discount attached tag */
memcpy(temp, aad, EVP_AEAD_TLS1_AAD_LEN - 2);
aad = temp;
temp[EVP_AEAD_TLS1_AAD_LEN - 2] = (unsigned char)(len >> 8);
temp[EVP_AEAD_TLS1_AAD_LEN - 1] = (unsigned char)len;
}
actx->tls_payload_length = len;
/*
* merge record sequence number as per RFC7905
*/
actx->key.counter[1] = actx->nonce[0];
actx->key.counter[2] = actx->nonce[1] ^ CHACHA_U8TOU32(aad);
actx->key.counter[3] = actx->nonce[2] ^ CHACHA_U8TOU32(aad+4);
actx->mac_inited = 0;
chacha20_poly1305_cipher(ctx, NULL, aad, EVP_AEAD_TLS1_AAD_LEN);
return POLY1305_BLOCK_SIZE; /* tag length */
}
case EVP_CTRL_AEAD_SET_MAC_KEY:
/* no-op */
return 1;
default:
return -1;
}
}
| 168,432 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftMPEG4Encoder::releaseEncoder() {
if (!mStarted) {
return OMX_ErrorNone;
}
PVCleanUpVideoEncoder(mHandle);
free(mInputFrameData);
mInputFrameData = NULL;
delete mEncParams;
mEncParams = NULL;
delete mHandle;
mHandle = NULL;
mStarted = false;
return OMX_ErrorNone;
}
Commit Message: codecs: handle onReset() for a few encoders
Test: Run PoC binaries
Bug: 34749392
Bug: 34705519
Change-Id: I3356eb615b0e79272d71d72578d363671038c6dd
CWE ID: | OMX_ERRORTYPE SoftMPEG4Encoder::releaseEncoder() {
if (mEncParams) {
delete mEncParams;
mEncParams = NULL;
}
if (mHandle) {
delete mHandle;
mHandle = NULL;
}
return OMX_ErrorNone;
}
| 174,010 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size)
{
bee_t *bee = ic->bee;
bee_user_t *bu = bee_user_by_handle(bee, ic, handle);
if (bee->ui->ft_in_start) {
return bee->ui->ft_in_start(bee, bu, file_name, file_size);
} else {
return NULL;
}
}
Commit Message: imcb_file_send_start: handle ft attempts from non-existing users
CWE ID: CWE-476 | file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size)
{
bee_t *bee = ic->bee;
bee_user_t *bu = bee_user_by_handle(bee, ic, handle);
if (bee->ui->ft_in_start && bu) {
return bee->ui->ft_in_start(bee, bu, file_name, file_size);
} else {
return NULL;
}
}
| 168,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: _PUBLIC_ codepoint_t next_codepoint_handle_ext(
struct smb_iconv_handle *ic,
const char *str, size_t len,
charset_t src_charset,
size_t *bytes_consumed)
{
/* it cannot occupy more than 4 bytes in UTF16 format */
uint8_t buf[4];
smb_iconv_t descriptor;
size_t ilen_orig;
size_t ilen;
size_t olen;
char *outbuf;
if ((str[0] & 0x80) == 0) {
*bytes_consumed = 1;
return (codepoint_t)str[0];
}
* This is OK as we only support codepoints up to 1M (U+100000)
*/
ilen_orig = MIN(len, 5);
ilen = ilen_orig;
descriptor = get_conv_handle(ic, src_charset, CH_UTF16);
if (descriptor == (smb_iconv_t)-1) {
*bytes_consumed = 1;
return INVALID_CODEPOINT;
}
/*
* this looks a little strange, but it is needed to cope with
* codepoints above 64k (U+1000) which are encoded as per RFC2781.
*/
olen = 2;
outbuf = (char *)buf;
smb_iconv(descriptor, &str, &ilen, &outbuf, &olen);
if (olen == 2) {
olen = 4;
outbuf = (char *)buf;
smb_iconv(descriptor, &str, &ilen, &outbuf, &olen);
if (olen == 4) {
/* we didn't convert any bytes */
*bytes_consumed = 1;
return INVALID_CODEPOINT;
}
olen = 4 - olen;
} else {
olen = 2 - olen;
}
*bytes_consumed = ilen_orig - ilen;
if (olen == 2) {
return (codepoint_t)SVAL(buf, 0);
}
if (olen == 4) {
/* decode a 4 byte UTF16 character manually */
return (codepoint_t)0x10000 +
(buf[2] | ((buf[3] & 0x3)<<8) |
(buf[0]<<10) | ((buf[1] & 0x3)<<18));
}
/* no other length is valid */
return INVALID_CODEPOINT;
}
Commit Message:
CWE ID: CWE-200 | _PUBLIC_ codepoint_t next_codepoint_handle_ext(
struct smb_iconv_handle *ic,
const char *str, size_t len,
charset_t src_charset,
size_t *bytes_consumed)
{
/* it cannot occupy more than 4 bytes in UTF16 format */
uint8_t buf[4];
smb_iconv_t descriptor;
size_t ilen_orig;
size_t ilen;
size_t olen;
char *outbuf;
if (((str[0] & 0x80) == 0) && (src_charset == CH_DOS ||
src_charset == CH_UNIX ||
src_charset == CH_UTF8)) {
*bytes_consumed = 1;
return (codepoint_t)str[0];
}
* This is OK as we only support codepoints up to 1M (U+100000)
*/
ilen_orig = MIN(len, 5);
ilen = ilen_orig;
descriptor = get_conv_handle(ic, src_charset, CH_UTF16);
if (descriptor == (smb_iconv_t)-1) {
*bytes_consumed = 1;
return INVALID_CODEPOINT;
}
/*
* this looks a little strange, but it is needed to cope with
* codepoints above 64k (U+1000) which are encoded as per RFC2781.
*/
olen = 2;
outbuf = (char *)buf;
smb_iconv(descriptor, &str, &ilen, &outbuf, &olen);
if (olen == 2) {
olen = 4;
outbuf = (char *)buf;
smb_iconv(descriptor, &str, &ilen, &outbuf, &olen);
if (olen == 4) {
/* we didn't convert any bytes */
*bytes_consumed = 1;
return INVALID_CODEPOINT;
}
olen = 4 - olen;
} else {
olen = 2 - olen;
}
*bytes_consumed = ilen_orig - ilen;
if (olen == 2) {
return (codepoint_t)SVAL(buf, 0);
}
if (olen == 4) {
/* decode a 4 byte UTF16 character manually */
return (codepoint_t)0x10000 +
(buf[2] | ((buf[3] & 0x3)<<8) |
(buf[0]<<10) | ((buf[1] & 0x3)<<18));
}
/* no other length is valid */
return INVALID_CODEPOINT;
}
| 164,667 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GDataFileSystem::AddUploadedFileOnUIThread(
UploadMode upload_mode,
const FilePath& virtual_dir_path,
scoped_ptr<DocumentEntry> entry,
const FilePath& file_content_path,
GDataCache::FileOperationType cache_operation,
const base::Closure& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::ScopedClosureRunner callback_runner(callback);
if (!entry.get()) {
NOTREACHED();
return;
}
GDataEntry* dir_entry = directory_service_->FindEntryByPathSync(
virtual_dir_path);
if (!dir_entry)
return;
GDataDirectory* parent_dir = dir_entry->AsGDataDirectory();
if (!parent_dir)
return;
scoped_ptr<GDataEntry> new_entry(
GDataEntry::FromDocumentEntry(
NULL, entry.get(), directory_service_.get()));
if (!new_entry.get())
return;
if (upload_mode == UPLOAD_EXISTING_FILE) {
const std::string& resource_id = new_entry->resource_id();
directory_service_->GetEntryByResourceIdAsync(resource_id,
base::Bind(&RemoveStaleEntryOnUpload, resource_id, parent_dir));
}
GDataFile* file = new_entry->AsGDataFile();
DCHECK(file);
const std::string& resource_id = file->resource_id();
const std::string& md5 = file->file_md5();
parent_dir->AddEntry(new_entry.release());
OnDirectoryChanged(virtual_dir_path);
if (upload_mode == UPLOAD_NEW_FILE) {
cache_->StoreOnUIThread(resource_id,
md5,
file_content_path,
cache_operation,
base::Bind(&OnCacheUpdatedForAddUploadedFile,
callback_runner.Release()));
} else if (upload_mode == UPLOAD_EXISTING_FILE) {
cache_->ClearDirtyOnUIThread(resource_id,
md5,
base::Bind(&OnCacheUpdatedForAddUploadedFile,
callback_runner.Release()));
} else {
NOTREACHED() << "Unexpected upload mode: " << upload_mode;
}
}
Commit Message: Remove parent* arg from GDataEntry ctor.
* Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry.
* Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry.
* Add GDataDirectoryService::FromDocumentEntry and use this everywhere.
* Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and
CreateGDataDirectory. Make GDataEntry ctor protected.
BUG=141494
TEST=unit tests.
Review URL: https://chromiumcodereview.appspot.com/10854083
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void GDataFileSystem::AddUploadedFileOnUIThread(
UploadMode upload_mode,
const FilePath& virtual_dir_path,
scoped_ptr<DocumentEntry> entry,
const FilePath& file_content_path,
GDataCache::FileOperationType cache_operation,
const base::Closure& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::ScopedClosureRunner callback_runner(callback);
if (!entry.get()) {
NOTREACHED();
return;
}
GDataEntry* dir_entry = directory_service_->FindEntryByPathSync(
virtual_dir_path);
if (!dir_entry)
return;
GDataDirectory* parent_dir = dir_entry->AsGDataDirectory();
if (!parent_dir)
return;
scoped_ptr<GDataEntry> new_entry(
directory_service_->FromDocumentEntry(entry.get()));
if (!new_entry.get())
return;
if (upload_mode == UPLOAD_EXISTING_FILE) {
const std::string& resource_id = new_entry->resource_id();
directory_service_->GetEntryByResourceIdAsync(resource_id,
base::Bind(&RemoveStaleEntryOnUpload, resource_id, parent_dir));
}
GDataFile* file = new_entry->AsGDataFile();
DCHECK(file);
const std::string& resource_id = file->resource_id();
const std::string& md5 = file->file_md5();
parent_dir->AddEntry(new_entry.release());
OnDirectoryChanged(virtual_dir_path);
if (upload_mode == UPLOAD_NEW_FILE) {
cache_->StoreOnUIThread(resource_id,
md5,
file_content_path,
cache_operation,
base::Bind(&OnCacheUpdatedForAddUploadedFile,
callback_runner.Release()));
} else if (upload_mode == UPLOAD_EXISTING_FILE) {
cache_->ClearDirtyOnUIThread(resource_id,
md5,
base::Bind(&OnCacheUpdatedForAddUploadedFile,
callback_runner.Release()));
} else {
NOTREACHED() << "Unexpected upload mode: " << upload_mode;
}
}
| 171,480 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr)
{
u16 offset = sizeof(struct ipv6hdr);
unsigned int packet_len = skb_tail_pointer(skb) -
skb_network_header(skb);
int found_rhdr = 0;
*nexthdr = &ipv6_hdr(skb)->nexthdr;
while (offset <= packet_len) {
struct ipv6_opt_hdr *exthdr;
switch (**nexthdr) {
case NEXTHDR_HOP:
break;
case NEXTHDR_ROUTING:
found_rhdr = 1;
break;
case NEXTHDR_DEST:
#if IS_ENABLED(CONFIG_IPV6_MIP6)
if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0)
break;
#endif
if (found_rhdr)
return offset;
break;
default:
return offset;
}
if (offset + sizeof(struct ipv6_opt_hdr) > packet_len)
return -EINVAL;
exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) +
offset);
offset += ipv6_optlen(exthdr);
*nexthdr = &exthdr->nexthdr;
}
return -EINVAL;
}
Commit Message: ipv6: avoid overflow of offset in ip6_find_1stfragopt
In some cases, offset can overflow and can cause an infinite loop in
ip6_find_1stfragopt(). Make it unsigned int to prevent the overflow, and
cap it at IPV6_MAXPLEN, since packets larger than that should be invalid.
This problem has been here since before the beginning of git history.
Signed-off-by: Sabrina Dubroca <[email protected]>
Acked-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-190 | int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr)
{
unsigned int offset = sizeof(struct ipv6hdr);
unsigned int packet_len = skb_tail_pointer(skb) -
skb_network_header(skb);
int found_rhdr = 0;
*nexthdr = &ipv6_hdr(skb)->nexthdr;
while (offset <= packet_len) {
struct ipv6_opt_hdr *exthdr;
unsigned int len;
switch (**nexthdr) {
case NEXTHDR_HOP:
break;
case NEXTHDR_ROUTING:
found_rhdr = 1;
break;
case NEXTHDR_DEST:
#if IS_ENABLED(CONFIG_IPV6_MIP6)
if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0)
break;
#endif
if (found_rhdr)
return offset;
break;
default:
return offset;
}
if (offset + sizeof(struct ipv6_opt_hdr) > packet_len)
return -EINVAL;
exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) +
offset);
len = ipv6_optlen(exthdr);
if (len + offset >= IPV6_MAXPLEN)
return -EINVAL;
offset += len;
*nexthdr = &exthdr->nexthdr;
}
return -EINVAL;
}
| 168,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 void v9fs_read(void *opaque)
{
int32_t fid;
uint64_t off;
ssize_t err = 0;
int32_t count = 0;
size_t offset = 7;
uint32_t max_count;
V9fsFidState *fidp;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &max_count);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_read(pdu->tag, pdu->id, fid, off, max_count);
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
if (fidp->fid_type == P9_FID_DIR) {
if (off == 0) {
v9fs_co_rewinddir(pdu, fidp);
}
count = v9fs_do_readdir_with_stat(pdu, fidp, max_count);
if (count < 0) {
err = count;
goto out;
}
err = pdu_marshal(pdu, offset, "d", count);
if (err < 0) {
goto out;
}
err += offset + count;
} else if (fidp->fid_type == P9_FID_FILE) {
QEMUIOVector qiov_full;
QEMUIOVector qiov;
int32_t len;
v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset + 4, max_count, false);
qemu_iovec_init(&qiov, qiov_full.niov);
do {
qemu_iovec_reset(&qiov);
qemu_iovec_concat(&qiov, &qiov_full, count, qiov_full.size - count);
if (0) {
print_sg(qiov.iov, qiov.niov);
}
/* Loop in case of EINTR */
do {
len = v9fs_co_preadv(pdu, fidp, qiov.iov, qiov.niov, off);
if (len >= 0) {
off += len;
count += len;
}
} while (len == -EINTR && !pdu->cancelled);
if (len < 0) {
/* IO error return the error */
err = len;
goto out;
}
} while (count < max_count && len > 0);
err = pdu_marshal(pdu, offset, "d", count);
if (err < 0) {
goto out;
}
err += offset + count;
qemu_iovec_destroy(&qiov);
qemu_iovec_destroy(&qiov_full);
} else if (fidp->fid_type == P9_FID_XATTR) {
} else {
err = -EINVAL;
}
trace_v9fs_read_return(pdu->tag, pdu->id, count, err);
out:
put_fid(pdu, fidp);
out_nofid:
pdu_complete(pdu, err);
}
Commit Message:
CWE ID: CWE-399 | static void v9fs_read(void *opaque)
{
int32_t fid;
uint64_t off;
ssize_t err = 0;
int32_t count = 0;
size_t offset = 7;
uint32_t max_count;
V9fsFidState *fidp;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &max_count);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_read(pdu->tag, pdu->id, fid, off, max_count);
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
if (fidp->fid_type == P9_FID_DIR) {
if (off == 0) {
v9fs_co_rewinddir(pdu, fidp);
}
count = v9fs_do_readdir_with_stat(pdu, fidp, max_count);
if (count < 0) {
err = count;
goto out;
}
err = pdu_marshal(pdu, offset, "d", count);
if (err < 0) {
goto out;
}
err += offset + count;
} else if (fidp->fid_type == P9_FID_FILE) {
QEMUIOVector qiov_full;
QEMUIOVector qiov;
int32_t len;
v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset + 4, max_count, false);
qemu_iovec_init(&qiov, qiov_full.niov);
do {
qemu_iovec_reset(&qiov);
qemu_iovec_concat(&qiov, &qiov_full, count, qiov_full.size - count);
if (0) {
print_sg(qiov.iov, qiov.niov);
}
/* Loop in case of EINTR */
do {
len = v9fs_co_preadv(pdu, fidp, qiov.iov, qiov.niov, off);
if (len >= 0) {
off += len;
count += len;
}
} while (len == -EINTR && !pdu->cancelled);
if (len < 0) {
/* IO error return the error */
err = len;
goto out_free_iovec;
}
} while (count < max_count && len > 0);
err = pdu_marshal(pdu, offset, "d", count);
if (err < 0) {
goto out_free_iovec;
}
err += offset + count;
out_free_iovec:
qemu_iovec_destroy(&qiov);
qemu_iovec_destroy(&qiov_full);
} else if (fidp->fid_type == P9_FID_XATTR) {
} else {
err = -EINVAL;
}
trace_v9fs_read_return(pdu->tag, pdu->id, count, err);
out:
put_fid(pdu, fidp);
out_nofid:
pdu_complete(pdu, err);
}
| 164,911 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 NavigationControllerImpl::RendererDidNavigateToExistingPage(
RenderFrameHostImpl* rfh,
const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
bool is_in_page,
bool was_restored,
NavigationHandleImpl* handle) {
DCHECK(!rfh->GetParent());
NavigationEntryImpl* entry;
if (params.intended_as_new_entry) {
entry = GetLastCommittedEntry();
} else if (params.nav_entry_id) {
entry = GetEntryWithUniqueID(params.nav_entry_id);
if (is_in_page) {
NavigationEntryImpl* last_entry = GetLastCommittedEntry();
if (entry->GetURL().GetOrigin() == last_entry->GetURL().GetOrigin() &&
last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
was_restored) {
entry->GetSSL() = last_entry->GetSSL();
}
} else {
entry->GetSSL() = handle->ssl_status();
}
} else {
entry = GetLastCommittedEntry();
if (!is_in_page)
entry->GetSSL() = handle->ssl_status();
}
DCHECK(entry);
entry->set_page_type(params.url_is_unreachable ? PAGE_TYPE_ERROR
: PAGE_TYPE_NORMAL);
entry->SetURL(params.url);
entry->SetReferrer(params.referrer);
if (entry->update_virtual_url_with_url())
UpdateVirtualURLToURL(entry, params.url);
DCHECK(entry->site_instance() == nullptr ||
!entry->GetRedirectChain().empty() ||
entry->site_instance() == rfh->GetSiteInstance());
entry->AddOrUpdateFrameEntry(
rfh->frame_tree_node(), params.item_sequence_number,
params.document_sequence_number, rfh->GetSiteInstance(), nullptr,
params.url, params.referrer, params.redirects, params.page_state,
params.method, params.post_id);
if (ui::PageTransitionIsRedirect(params.transition) && !is_in_page)
entry->GetFavicon() = FaviconStatus();
DiscardNonCommittedEntriesInternal();
last_committed_entry_index_ = GetIndexOfEntry(entry);
}
Commit Message: Add DumpWithoutCrashing in RendererDidNavigateToExistingPage
This is intended to be reverted after investigating the linked bug.
BUG=688425
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2701523004
Cr-Commit-Position: refs/heads/master@{#450900}
CWE ID: CWE-362 | void NavigationControllerImpl::RendererDidNavigateToExistingPage(
RenderFrameHostImpl* rfh,
const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
bool is_in_page,
bool was_restored,
NavigationHandleImpl* handle) {
DCHECK(!rfh->GetParent());
NavigationEntryImpl* entry;
if (params.intended_as_new_entry) {
entry = GetLastCommittedEntry();
MaybeDumpCopiedNonSameOriginEntry("Existing page navigation", params,
is_in_page, entry);
} else if (params.nav_entry_id) {
entry = GetEntryWithUniqueID(params.nav_entry_id);
if (is_in_page) {
NavigationEntryImpl* last_entry = GetLastCommittedEntry();
if (entry->GetURL().GetOrigin() == last_entry->GetURL().GetOrigin() &&
last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
was_restored) {
entry->GetSSL() = last_entry->GetSSL();
}
} else {
entry->GetSSL() = handle->ssl_status();
}
} else {
entry = GetLastCommittedEntry();
if (!is_in_page)
entry->GetSSL() = handle->ssl_status();
}
DCHECK(entry);
entry->set_page_type(params.url_is_unreachable ? PAGE_TYPE_ERROR
: PAGE_TYPE_NORMAL);
entry->SetURL(params.url);
entry->SetReferrer(params.referrer);
if (entry->update_virtual_url_with_url())
UpdateVirtualURLToURL(entry, params.url);
DCHECK(entry->site_instance() == nullptr ||
!entry->GetRedirectChain().empty() ||
entry->site_instance() == rfh->GetSiteInstance());
entry->AddOrUpdateFrameEntry(
rfh->frame_tree_node(), params.item_sequence_number,
params.document_sequence_number, rfh->GetSiteInstance(), nullptr,
params.url, params.referrer, params.redirects, params.page_state,
params.method, params.post_id);
if (ui::PageTransitionIsRedirect(params.transition) && !is_in_page)
entry->GetFavicon() = FaviconStatus();
DiscardNonCommittedEntriesInternal();
last_committed_entry_index_ = GetIndexOfEntry(entry);
}
| 172,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: void ExtensionViewGuest::DidNavigateMainFrame(
const content::LoadCommittedDetails& details,
const content::FrameNavigateParams& params) {
if (attached() && (params.url.GetOrigin() != url_.GetOrigin())) {
bad_message::ReceivedBadMessage(web_contents()->GetRenderProcessHost(),
bad_message::EVG_BAD_ORIGIN);
}
}
Commit Message: Make extensions use a correct same-origin check.
GURL::GetOrigin does not do the right thing for all types of URLs.
BUG=573317
Review URL: https://codereview.chromium.org/1658913002
Cr-Commit-Position: refs/heads/master@{#373381}
CWE ID: CWE-284 | void ExtensionViewGuest::DidNavigateMainFrame(
const content::LoadCommittedDetails& details,
const content::FrameNavigateParams& params) {
if (attached() && !url::IsSameOriginWith(params.url, url_)) {
bad_message::ReceivedBadMessage(web_contents()->GetRenderProcessHost(),
bad_message::EVG_BAD_ORIGIN);
}
}
| 172,283 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MediaControlsProgressView::OnMousePressed(const ui::MouseEvent& event) {
gfx::Point location_in_bar(event.location());
ConvertPointToTarget(this, this->progress_bar_, &location_in_bar);
if (!event.IsOnlyLeftMouseButton() ||
!progress_bar_->GetLocalBounds().Contains(location_in_bar)) {
return false;
}
HandleSeeking(location_in_bar);
return true;
}
Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks
This CL rearranges the different components of the CrOS lock screen
media controls based on the newest mocks. This involves resizing most
of the child views and their spacings. The artwork was also resized
and re-positioned. Additionally, the close button was moved from the
main view to the header row child view.
Artist and title data about the current session will eventually be
placed to the right of the artwork, but right now this space is empty.
See the bug for before and after pictures.
Bug: 991647
Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554
Reviewed-by: Xiyuan Xia <[email protected]>
Reviewed-by: Becca Hughes <[email protected]>
Commit-Queue: Mia Bergeron <[email protected]>
Cr-Commit-Position: refs/heads/master@{#686253}
CWE ID: CWE-200 | bool MediaControlsProgressView::OnMousePressed(const ui::MouseEvent& event) {
if (!event.IsOnlyLeftMouseButton() || event.y() < kMinClickHeight ||
event.y() > kMaxClickHeight) {
return false;
}
HandleSeeking(event.location());
return true;
}
| 172,348 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PageFormAnalyserLogger::Flush() {
std::string text;
for (ConsoleLevel level : {kError, kWarning, kVerbose}) {
for (LogEntry& entry : node_buffer_[level]) {
text.clear();
text += "[DOM] ";
text += entry.message;
for (unsigned i = 0; i < entry.nodes.size(); ++i)
text += " %o";
blink::WebConsoleMessage message(level, blink::WebString::FromUTF8(text));
message.nodes = std::move(entry.nodes); // avoids copying node vectors.
frame_->AddMessageToConsole(message);
}
}
node_buffer_.clear();
}
Commit Message: [AF] Prevent Logging Password Values to Console
Before sending over to be logged by DevTools, filter out DOM nodes that
have a type attribute equal to "password", and that are not empty.
Bug: 934609
Change-Id: I147ad0c2bad13cc50394f4b5ff2f4bfb7293114b
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1506498
Commit-Queue: Sebastien Lalancette <[email protected]>
Reviewed-by: Vadym Doroshenko <[email protected]>
Reviewed-by: Mathieu Perreault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#638615}
CWE ID: CWE-119 | void PageFormAnalyserLogger::Flush() {
std::string text;
for (ConsoleLevel level : {kError, kWarning, kVerbose}) {
for (LogEntry& entry : node_buffer_[level]) {
text.clear();
text += "[DOM] ";
text += entry.message;
std::vector<blink::WebNode> nodesToLog;
for (unsigned i = 0; i < entry.nodes.size(); ++i) {
if (entry.nodes[i].IsElementNode()) {
const blink::WebElement element =
entry.nodes[i].ToConst<blink::WebElement>();
const blink::WebInputElement* webInputElement =
blink::ToWebInputElement(&element);
// Filter out password inputs with values from being logged, as their
// values are also logged.
const bool shouldObfuscate =
webInputElement &&
webInputElement->IsPasswordFieldForAutofill() &&
!webInputElement->Value().IsEmpty();
if (!shouldObfuscate) {
text += " %o";
nodesToLog.push_back(element);
}
}
}
blink::WebConsoleMessage message(level, blink::WebString::FromUTF8(text));
message.nodes = std::move(nodesToLog); // avoids copying node vectors.
frame_->AddMessageToConsole(message);
}
}
node_buffer_.clear();
}
| 172,078 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: write_header( FT_Error error_code )
{
FT_Face face;
const char* basename;
const char* format;
error = FTC_Manager_LookupFace( handle->cache_manager,
handle->scaler.face_id, &face );
if ( error )
Fatal( "can't access font file" );
if ( !status.header )
{
basename = ft_basename( handle->current_font->filepathname );
switch ( error_code )
{
case FT_Err_Ok:
sprintf( status.header_buffer, "%s %s (file `%s')",
face->family_name, face->style_name, basename );
break;
case FT_Err_Invalid_Pixel_Size:
sprintf( status.header_buffer, "Invalid pixel size (file `%s')",
basename );
break;
case FT_Err_Invalid_PPem:
sprintf( status.header_buffer, "Invalid ppem value (file `%s')",
basename );
break;
default:
sprintf( status.header_buffer, "File `%s': error 0x%04x",
basename, (FT_UShort)error_code );
break;
}
status.header = status.header_buffer;
}
grWriteCellString( display->bitmap, 0, 0,
status.header, display->fore_color );
format = status.encoding != FT_ENCODING_NONE
? "at %g points, first char code = 0x%x"
: "at %g points, first glyph index = %d";
snprintf( status.header_buffer, 256, format,
status.ptsize / 64.0, status.Num );
if ( FT_HAS_GLYPH_NAMES( face ) )
{
char* p;
int format_len, gindex, size;
size = strlen( status.header_buffer );
p = status.header_buffer + size;
size = 256 - size;
format = ", name = ";
format_len = strlen( format );
if ( size >= format_len + 2 )
{
gindex = status.Num;
if ( status.encoding != FT_ENCODING_NONE )
gindex = FTDemo_Get_Index( handle, status.Num );
strcpy( p, format );
if ( FT_Get_Glyph_Name( face, gindex,
p + format_len, size - format_len ) )
*p = '\0';
}
}
status.header = status.header_buffer;
grWriteCellString( display->bitmap, 0, HEADER_HEIGHT,
status.header_buffer, display->fore_color );
if ( status.use_custom_lcd_filter )
{
int fwi = status.fw_index;
unsigned char *fw = status.filter_weights;
sprintf( status.header_buffer,
"%s0x%02X%s%s0x%02X%s%s0x%02X%s%s0x%02X%s%s0x%02X%s",
fwi == 0 ? "[" : " ", fw[0], fwi == 0 ? "]" : " ",
fwi == 1 ? "[" : " ", fw[1], fwi == 1 ? "]" : " ",
fwi == 2 ? "[" : " ", fw[2], fwi == 2 ? "]" : " ",
fwi == 3 ? "[" : " ", fw[3], fwi == 3 ? "]" : " ",
fwi == 4 ? "[" : " ", fw[4], fwi == 4 ? "]" : " " );
grWriteCellString( display->bitmap, 0, 2 * HEADER_HEIGHT,
status.header_buffer, display->fore_color );
}
grRefreshSurface( display->surface );
}
Commit Message:
CWE ID: CWE-119 | write_header( FT_Error error_code )
{
FT_Face face;
const char* basename;
const char* format;
error = FTC_Manager_LookupFace( handle->cache_manager,
handle->scaler.face_id, &face );
if ( error )
Fatal( "can't access font file" );
if ( !status.header )
{
basename = ft_basename( handle->current_font->filepathname );
switch ( error_code )
{
case FT_Err_Ok:
sprintf( status.header_buffer, "%.50s %.50s (file `%.100s')",
face->family_name, face->style_name, basename );
break;
case FT_Err_Invalid_Pixel_Size:
sprintf( status.header_buffer, "Invalid pixel size (file `%.100s')",
basename );
break;
case FT_Err_Invalid_PPem:
sprintf( status.header_buffer, "Invalid ppem value (file `%.100s')",
basename );
break;
default:
sprintf( status.header_buffer, "File `%.100s': error 0x%04x",
basename, (FT_UShort)error_code );
break;
}
status.header = status.header_buffer;
}
grWriteCellString( display->bitmap, 0, 0,
status.header, display->fore_color );
format = status.encoding != FT_ENCODING_NONE
? "at %g points, first char code = 0x%x"
: "at %g points, first glyph index = %d";
snprintf( status.header_buffer, 256, format,
status.ptsize / 64.0, status.Num );
if ( FT_HAS_GLYPH_NAMES( face ) )
{
char* p;
int format_len, gindex, size;
size = strlen( status.header_buffer );
p = status.header_buffer + size;
size = 256 - size;
format = ", name = ";
format_len = strlen( format );
if ( size >= format_len + 2 )
{
gindex = status.Num;
if ( status.encoding != FT_ENCODING_NONE )
gindex = FTDemo_Get_Index( handle, status.Num );
strcpy( p, format );
if ( FT_Get_Glyph_Name( face, gindex,
p + format_len, size - format_len ) )
*p = '\0';
}
}
status.header = status.header_buffer;
grWriteCellString( display->bitmap, 0, HEADER_HEIGHT,
status.header_buffer, display->fore_color );
if ( status.use_custom_lcd_filter )
{
int fwi = status.fw_index;
unsigned char *fw = status.filter_weights;
sprintf( status.header_buffer,
"%s0x%02X%s%s0x%02X%s%s0x%02X%s%s0x%02X%s%s0x%02X%s",
fwi == 0 ? "[" : " ", fw[0], fwi == 0 ? "]" : " ",
fwi == 1 ? "[" : " ", fw[1], fwi == 1 ? "]" : " ",
fwi == 2 ? "[" : " ", fw[2], fwi == 2 ? "]" : " ",
fwi == 3 ? "[" : " ", fw[3], fwi == 3 ? "]" : " ",
fwi == 4 ? "[" : " ", fw[4], fwi == 4 ? "]" : " " );
grWriteCellString( display->bitmap, 0, 2 * HEADER_HEIGHT,
status.header_buffer, display->fore_color );
}
grRefreshSurface( display->surface );
}
| 165,001 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderProcessHostImpl::CreateMessageFilters() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
AddFilter(new ResourceSchedulerFilter(GetID()));
MediaInternals* media_internals = MediaInternals::GetInstance();
scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
new BrowserPluginMessageFilter(GetID()));
AddFilter(bp_message_filter.get());
scoped_refptr<net::URLRequestContextGetter> request_context(
storage_partition_impl_->GetURLRequestContext());
scoped_refptr<RenderMessageFilter> render_message_filter(
new RenderMessageFilter(
GetID(), GetBrowserContext(), request_context.get(),
widget_helper_.get(), media_internals,
storage_partition_impl_->GetDOMStorageContext(),
storage_partition_impl_->GetCacheStorageContext()));
AddFilter(render_message_filter.get());
render_frame_message_filter_ = new RenderFrameMessageFilter(
GetID(),
#if BUILDFLAG(ENABLE_PLUGINS)
PluginServiceImpl::GetInstance(),
#else
nullptr,
#endif
GetBrowserContext(),
request_context.get(),
widget_helper_.get());
AddFilter(render_frame_message_filter_.get());
BrowserContext* browser_context = GetBrowserContext();
ResourceContext* resource_context = browser_context->GetResourceContext();
scoped_refptr<net::URLRequestContextGetter> media_request_context(
GetStoragePartition()->GetMediaURLRequestContext());
ResourceMessageFilter::GetContextsCallback get_contexts_callback(
base::Bind(&GetContexts, browser_context->GetResourceContext(),
request_context, media_request_context));
scoped_refptr<ChromeBlobStorageContext> blob_storage_context =
ChromeBlobStorageContext::GetFor(browser_context);
resource_message_filter_ = new ResourceMessageFilter(
GetID(), storage_partition_impl_->GetAppCacheService(),
blob_storage_context.get(),
storage_partition_impl_->GetFileSystemContext(),
storage_partition_impl_->GetServiceWorkerContext(),
get_contexts_callback);
AddFilter(resource_message_filter_.get());
media::AudioManager* audio_manager =
BrowserMainLoop::GetInstance()->audio_manager();
MediaStreamManager* media_stream_manager =
BrowserMainLoop::GetInstance()->media_stream_manager();
audio_input_renderer_host_ = new AudioInputRendererHost(
GetID(), base::GetProcId(GetHandle()), audio_manager,
media_stream_manager, AudioMirroringManager::GetInstance(),
BrowserMainLoop::GetInstance()->user_input_monitor());
AddFilter(audio_input_renderer_host_.get());
audio_renderer_host_ = new AudioRendererHost(
GetID(), audio_manager, AudioMirroringManager::GetInstance(),
media_stream_manager,
browser_context->GetResourceContext()->GetMediaDeviceIDSalt());
AddFilter(audio_renderer_host_.get());
AddFilter(
new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_service()));
AddFilter(new AppCacheDispatcherHost(
storage_partition_impl_->GetAppCacheService(), GetID()));
AddFilter(new ClipboardMessageFilter(blob_storage_context));
AddFilter(new DOMStorageMessageFilter(
storage_partition_impl_->GetDOMStorageContext()));
#if BUILDFLAG(ENABLE_WEBRTC)
peer_connection_tracker_host_ = new PeerConnectionTrackerHost(
GetID(), webrtc_eventlog_host_.GetWeakPtr());
AddFilter(peer_connection_tracker_host_.get());
AddFilter(new MediaStreamDispatcherHost(
GetID(), browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
media_stream_manager));
AddFilter(new MediaStreamTrackMetricsHost());
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
AddFilter(new PepperRendererConnection(GetID()));
#endif
AddFilter(new SpeechRecognitionDispatcherHost(
GetID(), storage_partition_impl_->GetURLRequestContext()));
AddFilter(new FileAPIMessageFilter(
GetID(), storage_partition_impl_->GetURLRequestContext(),
storage_partition_impl_->GetFileSystemContext(),
blob_storage_context.get(), StreamContext::GetFor(browser_context)));
AddFilter(new BlobDispatcherHost(
GetID(), blob_storage_context,
make_scoped_refptr(storage_partition_impl_->GetFileSystemContext())));
AddFilter(new FileUtilitiesMessageFilter(GetID()));
AddFilter(
new DatabaseMessageFilter(storage_partition_impl_->GetDatabaseTracker()));
#if defined(OS_MACOSX)
AddFilter(new TextInputClientMessageFilter());
#elif defined(OS_WIN)
AddFilter(new DWriteFontProxyMessageFilter());
channel_->AddFilter(new FontCacheDispatcher());
#endif
message_port_message_filter_ = new MessagePortMessageFilter(
base::Bind(&RenderWidgetHelper::GetNextRoutingID,
base::Unretained(widget_helper_.get())));
AddFilter(message_port_message_filter_.get());
scoped_refptr<CacheStorageDispatcherHost> cache_storage_filter =
new CacheStorageDispatcherHost();
cache_storage_filter->Init(storage_partition_impl_->GetCacheStorageContext());
AddFilter(cache_storage_filter.get());
scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
new ServiceWorkerDispatcherHost(
GetID(), message_port_message_filter_.get(), resource_context);
service_worker_filter->Init(
storage_partition_impl_->GetServiceWorkerContext());
AddFilter(service_worker_filter.get());
AddFilter(new SharedWorkerMessageFilter(
GetID(), resource_context,
WorkerStoragePartition(
storage_partition_impl_->GetURLRequestContext(),
storage_partition_impl_->GetMediaURLRequestContext(),
storage_partition_impl_->GetAppCacheService(),
storage_partition_impl_->GetQuotaManager(),
storage_partition_impl_->GetFileSystemContext(),
storage_partition_impl_->GetDatabaseTracker(),
storage_partition_impl_->GetIndexedDBContext(),
storage_partition_impl_->GetServiceWorkerContext()),
message_port_message_filter_.get()));
#if BUILDFLAG(ENABLE_WEBRTC)
p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost(
resource_context, request_context.get());
AddFilter(p2p_socket_dispatcher_host_.get());
#endif
AddFilter(new TraceMessageFilter(GetID()));
AddFilter(new ResolveProxyMsgHelper(request_context.get()));
AddFilter(new QuotaDispatcherHost(
GetID(), storage_partition_impl_->GetQuotaManager(),
GetContentClient()->browser()->CreateQuotaPermissionContext()));
scoped_refptr<ServiceWorkerContextWrapper> service_worker_context(
static_cast<ServiceWorkerContextWrapper*>(
storage_partition_impl_->GetServiceWorkerContext()));
notification_message_filter_ = new NotificationMessageFilter(
GetID(), storage_partition_impl_->GetPlatformNotificationContext(),
resource_context, service_worker_context, browser_context);
AddFilter(notification_message_filter_.get());
AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
AddFilter(new HistogramMessageFilter());
AddFilter(new MemoryMessageFilter(this));
AddFilter(new PushMessagingMessageFilter(
GetID(), storage_partition_impl_->GetServiceWorkerContext()));
#if defined(OS_ANDROID)
AddFilter(new ScreenOrientationListenerAndroid());
synchronous_compositor_filter_ =
new SynchronousCompositorBrowserFilter(GetID());
AddFilter(synchronous_compositor_filter_.get());
#endif
}
Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one.
BUG=672468
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Review-Url: https://codereview.chromium.org/2692203003
Cr-Commit-Position: refs/heads/master@{#450939}
CWE ID: | void RenderProcessHostImpl::CreateMessageFilters() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
AddFilter(new ResourceSchedulerFilter(GetID()));
MediaInternals* media_internals = MediaInternals::GetInstance();
scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
new BrowserPluginMessageFilter(GetID()));
AddFilter(bp_message_filter.get());
scoped_refptr<net::URLRequestContextGetter> request_context(
storage_partition_impl_->GetURLRequestContext());
scoped_refptr<RenderMessageFilter> render_message_filter(
new RenderMessageFilter(
GetID(), GetBrowserContext(), request_context.get(),
widget_helper_.get(), media_internals,
storage_partition_impl_->GetDOMStorageContext(),
storage_partition_impl_->GetCacheStorageContext()));
AddFilter(render_message_filter.get());
render_frame_message_filter_ = new RenderFrameMessageFilter(
GetID(),
#if BUILDFLAG(ENABLE_PLUGINS)
PluginServiceImpl::GetInstance(),
#else
nullptr,
#endif
GetBrowserContext(),
request_context.get(),
widget_helper_.get());
AddFilter(render_frame_message_filter_.get());
BrowserContext* browser_context = GetBrowserContext();
ResourceContext* resource_context = browser_context->GetResourceContext();
scoped_refptr<net::URLRequestContextGetter> media_request_context(
GetStoragePartition()->GetMediaURLRequestContext());
ResourceMessageFilter::GetContextsCallback get_contexts_callback(
base::Bind(&GetContexts, browser_context->GetResourceContext(),
request_context, media_request_context));
scoped_refptr<ChromeBlobStorageContext> blob_storage_context =
ChromeBlobStorageContext::GetFor(browser_context);
resource_message_filter_ = new ResourceMessageFilter(
GetID(), storage_partition_impl_->GetAppCacheService(),
blob_storage_context.get(),
storage_partition_impl_->GetFileSystemContext(),
storage_partition_impl_->GetServiceWorkerContext(),
get_contexts_callback);
AddFilter(resource_message_filter_.get());
media::AudioManager* audio_manager =
BrowserMainLoop::GetInstance()->audio_manager();
MediaStreamManager* media_stream_manager =
BrowserMainLoop::GetInstance()->media_stream_manager();
audio_input_renderer_host_ = new AudioInputRendererHost(
GetID(), base::GetProcId(GetHandle()), audio_manager,
media_stream_manager, AudioMirroringManager::GetInstance(),
BrowserMainLoop::GetInstance()->user_input_monitor());
AddFilter(audio_input_renderer_host_.get());
audio_renderer_host_ = new AudioRendererHost(
GetID(), audio_manager, BrowserMainLoop::GetInstance()->audio_system(),
AudioMirroringManager::GetInstance(), media_stream_manager,
browser_context->GetResourceContext()->GetMediaDeviceIDSalt());
AddFilter(audio_renderer_host_.get());
AddFilter(
new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_service()));
AddFilter(new AppCacheDispatcherHost(
storage_partition_impl_->GetAppCacheService(), GetID()));
AddFilter(new ClipboardMessageFilter(blob_storage_context));
AddFilter(new DOMStorageMessageFilter(
storage_partition_impl_->GetDOMStorageContext()));
#if BUILDFLAG(ENABLE_WEBRTC)
peer_connection_tracker_host_ = new PeerConnectionTrackerHost(
GetID(), webrtc_eventlog_host_.GetWeakPtr());
AddFilter(peer_connection_tracker_host_.get());
AddFilter(new MediaStreamDispatcherHost(
GetID(), browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
media_stream_manager));
AddFilter(new MediaStreamTrackMetricsHost());
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
AddFilter(new PepperRendererConnection(GetID()));
#endif
AddFilter(new SpeechRecognitionDispatcherHost(
GetID(), storage_partition_impl_->GetURLRequestContext()));
AddFilter(new FileAPIMessageFilter(
GetID(), storage_partition_impl_->GetURLRequestContext(),
storage_partition_impl_->GetFileSystemContext(),
blob_storage_context.get(), StreamContext::GetFor(browser_context)));
AddFilter(new BlobDispatcherHost(
GetID(), blob_storage_context,
make_scoped_refptr(storage_partition_impl_->GetFileSystemContext())));
AddFilter(new FileUtilitiesMessageFilter(GetID()));
AddFilter(
new DatabaseMessageFilter(storage_partition_impl_->GetDatabaseTracker()));
#if defined(OS_MACOSX)
AddFilter(new TextInputClientMessageFilter());
#elif defined(OS_WIN)
AddFilter(new DWriteFontProxyMessageFilter());
channel_->AddFilter(new FontCacheDispatcher());
#endif
message_port_message_filter_ = new MessagePortMessageFilter(
base::Bind(&RenderWidgetHelper::GetNextRoutingID,
base::Unretained(widget_helper_.get())));
AddFilter(message_port_message_filter_.get());
scoped_refptr<CacheStorageDispatcherHost> cache_storage_filter =
new CacheStorageDispatcherHost();
cache_storage_filter->Init(storage_partition_impl_->GetCacheStorageContext());
AddFilter(cache_storage_filter.get());
scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
new ServiceWorkerDispatcherHost(
GetID(), message_port_message_filter_.get(), resource_context);
service_worker_filter->Init(
storage_partition_impl_->GetServiceWorkerContext());
AddFilter(service_worker_filter.get());
AddFilter(new SharedWorkerMessageFilter(
GetID(), resource_context,
WorkerStoragePartition(
storage_partition_impl_->GetURLRequestContext(),
storage_partition_impl_->GetMediaURLRequestContext(),
storage_partition_impl_->GetAppCacheService(),
storage_partition_impl_->GetQuotaManager(),
storage_partition_impl_->GetFileSystemContext(),
storage_partition_impl_->GetDatabaseTracker(),
storage_partition_impl_->GetIndexedDBContext(),
storage_partition_impl_->GetServiceWorkerContext()),
message_port_message_filter_.get()));
#if BUILDFLAG(ENABLE_WEBRTC)
p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost(
resource_context, request_context.get());
AddFilter(p2p_socket_dispatcher_host_.get());
#endif
AddFilter(new TraceMessageFilter(GetID()));
AddFilter(new ResolveProxyMsgHelper(request_context.get()));
AddFilter(new QuotaDispatcherHost(
GetID(), storage_partition_impl_->GetQuotaManager(),
GetContentClient()->browser()->CreateQuotaPermissionContext()));
scoped_refptr<ServiceWorkerContextWrapper> service_worker_context(
static_cast<ServiceWorkerContextWrapper*>(
storage_partition_impl_->GetServiceWorkerContext()));
notification_message_filter_ = new NotificationMessageFilter(
GetID(), storage_partition_impl_->GetPlatformNotificationContext(),
resource_context, service_worker_context, browser_context);
AddFilter(notification_message_filter_.get());
AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
AddFilter(new HistogramMessageFilter());
AddFilter(new MemoryMessageFilter(this));
AddFilter(new PushMessagingMessageFilter(
GetID(), storage_partition_impl_->GetServiceWorkerContext()));
#if defined(OS_ANDROID)
AddFilter(new ScreenOrientationListenerAndroid());
synchronous_compositor_filter_ =
new SynchronousCompositorBrowserFilter(GetID());
AddFilter(synchronous_compositor_filter_.get());
#endif
}
| 171,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: static enum entity_charset determine_charset(char *charset_hint TSRMLS_DC)
{
int i;
enum entity_charset charset = cs_utf_8;
int len = 0;
const zend_encoding *zenc;
/* Default is now UTF-8 */
if (charset_hint == NULL)
return cs_utf_8;
if ((len = strlen(charset_hint)) != 0) {
goto det_charset;
}
zenc = zend_multibyte_get_internal_encoding(TSRMLS_C);
if (zenc != NULL) {
charset_hint = (char *)zend_multibyte_get_encoding_name(zenc);
if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) {
if ((len == 4) /* sizeof (none|auto|pass) */ &&
(!memcmp("pass", charset_hint, 4) ||
!memcmp("auto", charset_hint, 4) ||
!memcmp("auto", charset_hint, 4))) {
charset_hint = NULL;
len = 0;
} else {
goto det_charset;
}
}
}
charset_hint = SG(default_charset);
if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) {
goto det_charset;
}
/* try to detect the charset for the locale */
#if HAVE_NL_LANGINFO && HAVE_LOCALE_H && defined(CODESET)
charset_hint = nl_langinfo(CODESET);
if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) {
goto det_charset;
}
#endif
#if HAVE_LOCALE_H
/* try to figure out the charset from the locale */
{
char *localename;
char *dot, *at;
/* lang[_territory][.codeset][@modifier] */
localename = setlocale(LC_CTYPE, NULL);
dot = strchr(localename, '.');
if (dot) {
dot++;
/* locale specifies a codeset */
at = strchr(dot, '@');
if (at)
len = at - dot;
else
len = strlen(dot);
charset_hint = dot;
} else {
/* no explicit name; see if the name itself
* is the charset */
charset_hint = localename;
len = strlen(charset_hint);
}
}
#endif
det_charset:
if (charset_hint) {
int found = 0;
/* now walk the charset map and look for the codeset */
for (i = 0; charset_map[i].codeset; i++) {
if (len == strlen(charset_map[i].codeset) && strncasecmp(charset_hint, charset_map[i].codeset, len) == 0) {
charset = charset_map[i].charset;
found = 1;
break;
}
}
if (!found) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "charset `%s' not supported, assuming utf-8",
charset_hint);
}
}
return charset;
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190 | static enum entity_charset determine_charset(char *charset_hint TSRMLS_DC)
{
int i;
enum entity_charset charset = cs_utf_8;
int len = 0;
const zend_encoding *zenc;
/* Default is now UTF-8 */
if (charset_hint == NULL)
return cs_utf_8;
if ((len = strlen(charset_hint)) != 0) {
goto det_charset;
}
zenc = zend_multibyte_get_internal_encoding(TSRMLS_C);
if (zenc != NULL) {
charset_hint = (char *)zend_multibyte_get_encoding_name(zenc);
if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) {
if ((len == 4) /* sizeof (none|auto|pass) */ &&
(!memcmp("pass", charset_hint, 4) ||
!memcmp("auto", charset_hint, 4) ||
!memcmp("auto", charset_hint, 4))) {
charset_hint = NULL;
len = 0;
} else {
goto det_charset;
}
}
}
charset_hint = SG(default_charset);
if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) {
goto det_charset;
}
/* try to detect the charset for the locale */
#if HAVE_NL_LANGINFO && HAVE_LOCALE_H && defined(CODESET)
charset_hint = nl_langinfo(CODESET);
if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) {
goto det_charset;
}
#endif
#if HAVE_LOCALE_H
/* try to figure out the charset from the locale */
{
char *localename;
char *dot, *at;
/* lang[_territory][.codeset][@modifier] */
localename = setlocale(LC_CTYPE, NULL);
dot = strchr(localename, '.');
if (dot) {
dot++;
/* locale specifies a codeset */
at = strchr(dot, '@');
if (at)
len = at - dot;
else
len = strlen(dot);
charset_hint = dot;
} else {
/* no explicit name; see if the name itself
* is the charset */
charset_hint = localename;
len = strlen(charset_hint);
}
}
#endif
det_charset:
if (charset_hint) {
int found = 0;
/* now walk the charset map and look for the codeset */
for (i = 0; charset_map[i].codeset; i++) {
if (len == strlen(charset_map[i].codeset) && strncasecmp(charset_hint, charset_map[i].codeset, len) == 0) {
charset = charset_map[i].charset;
found = 1;
break;
}
}
if (!found) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "charset `%s' not supported, assuming utf-8",
charset_hint);
}
}
return charset;
}
| 167,169 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: sequential_row(standard_display *dp, png_structp pp, png_infop pi,
PNG_CONST int iImage, PNG_CONST int iDisplay)
{
PNG_CONST int npasses = dp->npasses;
PNG_CONST int do_interlace = dp->do_interlace &&
dp->interlace_type == PNG_INTERLACE_ADAM7;
PNG_CONST png_uint_32 height = standard_height(pp, dp->id);
PNG_CONST png_uint_32 width = standard_width(pp, dp->id);
PNG_CONST png_store* ps = dp->ps;
int pass;
for (pass=0; pass<npasses; ++pass)
{
png_uint_32 y;
png_uint_32 wPass = PNG_PASS_COLS(width, pass);
for (y=0; y<height; ++y)
{
if (do_interlace)
{
/* wPass may be zero or this row may not be in this pass.
* png_read_row must not be called in either case.
*/
if (wPass > 0 && PNG_ROW_IN_INTERLACE_PASS(y, pass))
{
/* Read the row into a pair of temporary buffers, then do the
* merge here into the output rows.
*/
png_byte row[STANDARD_ROWMAX], display[STANDARD_ROWMAX];
/* The following aids (to some extent) error detection - we can
* see where png_read_row wrote. Use opposite values in row and
* display to make this easier. Don't use 0xff (which is used in
* the image write code to fill unused bits) or 0 (which is a
* likely value to overwrite unused bits with).
*/
memset(row, 0xc5, sizeof row);
memset(display, 0x5c, sizeof display);
png_read_row(pp, row, display);
if (iImage >= 0)
deinterlace_row(store_image_row(ps, pp, iImage, y), row,
dp->pixel_size, dp->w, pass);
if (iDisplay >= 0)
deinterlace_row(store_image_row(ps, pp, iDisplay, y), display,
dp->pixel_size, dp->w, pass);
}
}
else
png_read_row(pp,
iImage >= 0 ? store_image_row(ps, pp, iImage, y) : NULL,
iDisplay >= 0 ? store_image_row(ps, pp, iDisplay, y) : NULL);
}
}
/* And finish the read operation (only really necessary if the caller wants
* to find additional data in png_info from chunks after the last IDAT.)
*/
png_read_end(pp, pi);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | sequential_row(standard_display *dp, png_structp pp, png_infop pi,
const int iImage, const int iDisplay)
{
const int npasses = dp->npasses;
const int do_interlace = dp->do_interlace &&
dp->interlace_type == PNG_INTERLACE_ADAM7;
const png_uint_32 height = standard_height(pp, dp->id);
const png_uint_32 width = standard_width(pp, dp->id);
const png_store* ps = dp->ps;
int pass;
for (pass=0; pass<npasses; ++pass)
{
png_uint_32 y;
png_uint_32 wPass = PNG_PASS_COLS(width, pass);
for (y=0; y<height; ++y)
{
if (do_interlace)
{
/* wPass may be zero or this row may not be in this pass.
* png_read_row must not be called in either case.
*/
if (wPass > 0 && PNG_ROW_IN_INTERLACE_PASS(y, pass))
{
/* Read the row into a pair of temporary buffers, then do the
* merge here into the output rows.
*/
png_byte row[STANDARD_ROWMAX], display[STANDARD_ROWMAX];
/* The following aids (to some extent) error detection - we can
* see where png_read_row wrote. Use opposite values in row and
* display to make this easier. Don't use 0xff (which is used in
* the image write code to fill unused bits) or 0 (which is a
* likely value to overwrite unused bits with).
*/
memset(row, 0xc5, sizeof row);
memset(display, 0x5c, sizeof display);
png_read_row(pp, row, display);
if (iImage >= 0)
deinterlace_row(store_image_row(ps, pp, iImage, y), row,
dp->pixel_size, dp->w, pass, dp->littleendian);
if (iDisplay >= 0)
deinterlace_row(store_image_row(ps, pp, iDisplay, y), display,
dp->pixel_size, dp->w, pass, dp->littleendian);
}
}
else
png_read_row(pp,
iImage >= 0 ? store_image_row(ps, pp, iImage, y) : NULL,
iDisplay >= 0 ? store_image_row(ps, pp, iDisplay, y) : NULL);
}
}
/* And finish the read operation (only really necessary if the caller wants
* to find additional data in png_info from chunks after the last IDAT.)
*/
png_read_end(pp, pi);
}
| 173,693 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
if (interstitial_page_)
return interstitial_page_->GetView();
if (render_frame_host_)
return render_frame_host_->GetView();
return nullptr;
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20 | RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
if (delegate_->GetInterstitialForRenderManager())
return delegate_->GetInterstitialForRenderManager()->GetView();
if (render_frame_host_)
return render_frame_host_->GetView();
return nullptr;
}
| 172,322 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ShellWindowFrameView::Init(views::Widget* frame) {
frame_ = frame;
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
close_button_ = new views::ImageButton(this);
close_button_->SetImage(views::CustomButton::BS_NORMAL,
rb.GetNativeImageNamed(IDR_CLOSE_BAR).ToImageSkia());
close_button_->SetImage(views::CustomButton::BS_HOT,
rb.GetNativeImageNamed(IDR_CLOSE_BAR_H).ToImageSkia());
close_button_->SetImage(views::CustomButton::BS_PUSHED,
rb.GetNativeImageNamed(IDR_CLOSE_BAR_P).ToImageSkia());
close_button_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_APP_ACCNAME_CLOSE));
AddChildView(close_button_);
#if defined(USE_ASH)
aura::Window* window = frame->GetNativeWindow();
int outside_bounds = ui::GetDisplayLayout() == ui::LAYOUT_TOUCH ?
kResizeOutsideBoundsSizeTouch :
kResizeOutsideBoundsSize;
window->set_hit_test_bounds_override_outer(
gfx::Insets(-outside_bounds, -outside_bounds,
-outside_bounds, -outside_bounds));
window->set_hit_test_bounds_override_inner(
gfx::Insets(kResizeInsideBoundsSize, kResizeInsideBoundsSize,
kResizeInsideBoundsSize, kResizeInsideBoundsSize));
#endif
}
Commit Message: [views] Remove header bar on shell windows created with {frame: none}.
BUG=130182
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10597003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79 | void ShellWindowFrameView::Init(views::Widget* frame) {
frame_ = frame;
if (!is_frameless_) {
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
close_button_ = new views::ImageButton(this);
close_button_->SetImage(views::CustomButton::BS_NORMAL,
rb.GetNativeImageNamed(IDR_CLOSE_BAR).ToImageSkia());
close_button_->SetImage(views::CustomButton::BS_HOT,
rb.GetNativeImageNamed(IDR_CLOSE_BAR_H).ToImageSkia());
close_button_->SetImage(views::CustomButton::BS_PUSHED,
rb.GetNativeImageNamed(IDR_CLOSE_BAR_P).ToImageSkia());
close_button_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_APP_ACCNAME_CLOSE));
AddChildView(close_button_);
}
#if defined(USE_ASH)
aura::Window* window = frame->GetNativeWindow();
int outside_bounds = ui::GetDisplayLayout() == ui::LAYOUT_TOUCH ?
kResizeOutsideBoundsSizeTouch :
kResizeOutsideBoundsSize;
window->set_hit_test_bounds_override_outer(
gfx::Insets(-outside_bounds, -outside_bounds,
-outside_bounds, -outside_bounds));
window->set_hit_test_bounds_override_inner(
gfx::Insets(kResizeInsideBoundsSize, kResizeInsideBoundsSize,
kResizeInsideBoundsSize, kResizeInsideBoundsSize));
#endif
}
| 170,715 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: NetworkChangeNotifierMac::NetworkChangeNotifierMac()
: NetworkChangeNotifier(NetworkChangeCalculatorParamsMac()),
connection_type_(CONNECTION_UNKNOWN),
connection_type_initialized_(false),
initial_connection_type_cv_(&connection_type_lock_),
forwarder_(this),
dns_config_service_thread_(base::MakeUnique<DnsConfigServiceThread>()) {
config_watcher_ = base::MakeUnique<NetworkConfigWatcherMac>(&forwarder_);
dns_config_service_thread_->StartWithOptions(
base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
}
Commit Message: Replace base::MakeUnique with std::make_unique in net/.
base/memory/ptr_util.h includes will be cleaned up later.
Bug: 755727
Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434
Reviewed-on: https://chromium-review.googlesource.com/627300
Commit-Queue: Jeremy Roman <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Bence Béky <[email protected]>
Cr-Commit-Position: refs/heads/master@{#498123}
CWE ID: CWE-311 | NetworkChangeNotifierMac::NetworkChangeNotifierMac()
: NetworkChangeNotifier(NetworkChangeCalculatorParamsMac()),
connection_type_(CONNECTION_UNKNOWN),
connection_type_initialized_(false),
initial_connection_type_cv_(&connection_type_lock_),
forwarder_(this),
dns_config_service_thread_(std::make_unique<DnsConfigServiceThread>()) {
config_watcher_ = std::make_unique<NetworkConfigWatcherMac>(&forwarder_);
dns_config_service_thread_->StartWithOptions(
base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
}
| 173,264 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
{
struct bpf_verifier_env *env;
struct bpf_verifer_log *log;
int ret = -EINVAL;
/* no program is valid */
if (ARRAY_SIZE(bpf_verifier_ops) == 0)
return -EINVAL;
/* 'struct bpf_verifier_env' can be global, but since it's not small,
* allocate/free it every time bpf_check() is called
*/
env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
if (!env)
return -ENOMEM;
log = &env->log;
env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
(*prog)->len);
ret = -ENOMEM;
if (!env->insn_aux_data)
goto err_free_env;
env->prog = *prog;
env->ops = bpf_verifier_ops[env->prog->type];
/* grab the mutex to protect few globals used by verifier */
mutex_lock(&bpf_verifier_lock);
if (attr->log_level || attr->log_buf || attr->log_size) {
/* user requested verbose verifier output
* and supplied buffer to store the verification trace
*/
log->level = attr->log_level;
log->ubuf = (char __user *) (unsigned long) attr->log_buf;
log->len_total = attr->log_size;
ret = -EINVAL;
/* log attributes have to be sane */
if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
!log->level || !log->ubuf)
goto err_unlock;
}
env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
env->strict_alignment = true;
if (env->prog->aux->offload) {
ret = bpf_prog_offload_verifier_prep(env);
if (ret)
goto err_unlock;
}
ret = replace_map_fd_with_map_ptr(env);
if (ret < 0)
goto skip_full_check;
env->explored_states = kcalloc(env->prog->len,
sizeof(struct bpf_verifier_state_list *),
GFP_USER);
ret = -ENOMEM;
if (!env->explored_states)
goto skip_full_check;
ret = check_cfg(env);
if (ret < 0)
goto skip_full_check;
env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
ret = do_check(env);
if (env->cur_state) {
free_verifier_state(env->cur_state, true);
env->cur_state = NULL;
}
skip_full_check:
while (!pop_stack(env, NULL, NULL));
free_states(env);
if (ret == 0)
/* program is valid, convert *(u32*)(ctx + off) accesses */
ret = convert_ctx_accesses(env);
if (ret == 0)
ret = fixup_bpf_calls(env);
if (log->level && bpf_verifier_log_full(log))
ret = -ENOSPC;
if (log->level && !log->ubuf) {
ret = -EFAULT;
goto err_release_maps;
}
if (ret == 0 && env->used_map_cnt) {
/* if program passed verifier, update used_maps in bpf_prog_info */
env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
sizeof(env->used_maps[0]),
GFP_KERNEL);
if (!env->prog->aux->used_maps) {
ret = -ENOMEM;
goto err_release_maps;
}
memcpy(env->prog->aux->used_maps, env->used_maps,
sizeof(env->used_maps[0]) * env->used_map_cnt);
env->prog->aux->used_map_cnt = env->used_map_cnt;
/* program is valid. Convert pseudo bpf_ld_imm64 into generic
* bpf_ld_imm64 instructions
*/
convert_pseudo_ld_imm64(env);
}
err_release_maps:
if (!env->prog->aux->used_maps)
/* if we didn't copy map pointers into bpf_prog_info, release
* them now. Otherwise free_bpf_prog_info() will release them.
*/
release_maps(env);
*prog = env->prog;
err_unlock:
mutex_unlock(&bpf_verifier_lock);
vfree(env->insn_aux_data);
err_free_env:
kfree(env);
return ret;
}
Commit Message: bpf: fix branch pruning logic
when the verifier detects that register contains a runtime constant
and it's compared with another constant it will prune exploration
of the branch that is guaranteed not to be taken at runtime.
This is all correct, but malicious program may be constructed
in such a way that it always has a constant comparison and
the other branch is never taken under any conditions.
In this case such path through the program will not be explored
by the verifier. It won't be taken at run-time either, but since
all instructions are JITed the malicious program may cause JITs
to complain about using reserved fields, etc.
To fix the issue we have to track the instructions explored by
the verifier and sanitize instructions that are dead at run time
with NOPs. We cannot reject such dead code, since llvm generates
it for valid C code, since it doesn't do as much data flow
analysis as the verifier does.
Fixes: 17a5267067f3 ("bpf: verifier (add verifier core)")
Signed-off-by: Alexei Starovoitov <[email protected]>
Acked-by: Daniel Borkmann <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
CWE ID: CWE-20 | int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
{
struct bpf_verifier_env *env;
struct bpf_verifer_log *log;
int ret = -EINVAL;
/* no program is valid */
if (ARRAY_SIZE(bpf_verifier_ops) == 0)
return -EINVAL;
/* 'struct bpf_verifier_env' can be global, but since it's not small,
* allocate/free it every time bpf_check() is called
*/
env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
if (!env)
return -ENOMEM;
log = &env->log;
env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
(*prog)->len);
ret = -ENOMEM;
if (!env->insn_aux_data)
goto err_free_env;
env->prog = *prog;
env->ops = bpf_verifier_ops[env->prog->type];
/* grab the mutex to protect few globals used by verifier */
mutex_lock(&bpf_verifier_lock);
if (attr->log_level || attr->log_buf || attr->log_size) {
/* user requested verbose verifier output
* and supplied buffer to store the verification trace
*/
log->level = attr->log_level;
log->ubuf = (char __user *) (unsigned long) attr->log_buf;
log->len_total = attr->log_size;
ret = -EINVAL;
/* log attributes have to be sane */
if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
!log->level || !log->ubuf)
goto err_unlock;
}
env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
env->strict_alignment = true;
if (env->prog->aux->offload) {
ret = bpf_prog_offload_verifier_prep(env);
if (ret)
goto err_unlock;
}
ret = replace_map_fd_with_map_ptr(env);
if (ret < 0)
goto skip_full_check;
env->explored_states = kcalloc(env->prog->len,
sizeof(struct bpf_verifier_state_list *),
GFP_USER);
ret = -ENOMEM;
if (!env->explored_states)
goto skip_full_check;
ret = check_cfg(env);
if (ret < 0)
goto skip_full_check;
env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
ret = do_check(env);
if (env->cur_state) {
free_verifier_state(env->cur_state, true);
env->cur_state = NULL;
}
skip_full_check:
while (!pop_stack(env, NULL, NULL));
free_states(env);
if (ret == 0)
sanitize_dead_code(env);
if (ret == 0)
/* program is valid, convert *(u32*)(ctx + off) accesses */
ret = convert_ctx_accesses(env);
if (ret == 0)
ret = fixup_bpf_calls(env);
if (log->level && bpf_verifier_log_full(log))
ret = -ENOSPC;
if (log->level && !log->ubuf) {
ret = -EFAULT;
goto err_release_maps;
}
if (ret == 0 && env->used_map_cnt) {
/* if program passed verifier, update used_maps in bpf_prog_info */
env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
sizeof(env->used_maps[0]),
GFP_KERNEL);
if (!env->prog->aux->used_maps) {
ret = -ENOMEM;
goto err_release_maps;
}
memcpy(env->prog->aux->used_maps, env->used_maps,
sizeof(env->used_maps[0]) * env->used_map_cnt);
env->prog->aux->used_map_cnt = env->used_map_cnt;
/* program is valid. Convert pseudo bpf_ld_imm64 into generic
* bpf_ld_imm64 instructions
*/
convert_pseudo_ld_imm64(env);
}
err_release_maps:
if (!env->prog->aux->used_maps)
/* if we didn't copy map pointers into bpf_prog_info, release
* them now. Otherwise free_bpf_prog_info() will release them.
*/
release_maps(env);
*prog = env->prog;
err_unlock:
mutex_unlock(&bpf_verifier_lock);
vfree(env->insn_aux_data);
err_free_env:
kfree(env);
return ret;
}
| 167,638 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Response ServiceWorkerHandler::DeliverPushMessage(
const std::string& origin,
const std::string& registration_id,
const std::string& data) {
if (!enabled_)
return CreateDomainNotEnabledErrorResponse();
if (!process_)
return CreateContextErrorResponse();
int64_t id = 0;
if (!base::StringToInt64(registration_id, &id))
return CreateInvalidVersionIdErrorResponse();
PushEventPayload payload;
if (data.size() > 0)
payload.setData(data);
BrowserContext::DeliverPushMessage(process_->GetBrowserContext(),
GURL(origin), id, payload,
base::Bind(&PushDeliveryNoOp));
return Response::OK();
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | Response ServiceWorkerHandler::DeliverPushMessage(
const std::string& origin,
const std::string& registration_id,
const std::string& data) {
if (!enabled_)
return CreateDomainNotEnabledErrorResponse();
if (!browser_context_)
return CreateContextErrorResponse();
int64_t id = 0;
if (!base::StringToInt64(registration_id, &id))
return CreateInvalidVersionIdErrorResponse();
PushEventPayload payload;
if (data.size() > 0)
payload.setData(data);
BrowserContext::DeliverPushMessage(
browser_context_, GURL(origin), id, payload,
base::BindRepeating([](mojom::PushDeliveryStatus status) {}));
return Response::OK();
}
| 172,766 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: t42_parse_font_matrix( T42_Face face,
T42_Loader loader )
{
T42_Parser parser = &loader->parser;
FT_Matrix* matrix = &face->type1.font_matrix;
FT_Vector* offset = &face->type1.font_offset;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
(void)T1_ToFixedArray( parser, 6, temp, 3 );
temp_scale = FT_ABS( temp[3] );
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
/* note that the offsets must be expressed in integer font units */
offset->x = temp[4] >> 16;
offset->y = temp[5] >> 16;
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = 0x10000L;
}
Commit Message:
CWE ID: CWE-20 | t42_parse_font_matrix( T42_Face face,
T42_Loader loader )
{
T42_Parser parser = &loader->parser;
FT_Matrix* matrix = &face->type1.font_matrix;
FT_Vector* offset = &face->type1.font_offset;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
FT_Int result;
result = T1_ToFixedArray( parser, 6, temp, 3 );
if ( result < 6 )
{
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
temp_scale = FT_ABS( temp[3] );
if ( temp_scale == 0 )
{
FT_ERROR(( "t1_parse_font_matrix: invalid font matrix\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
/* note that the offsets must be expressed in integer font units */
offset->x = temp[4] >> 16;
offset->y = temp[5] >> 16;
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L;
}
| 165,343 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 _our_safe_pcap_next_ex(pcap_t *pcap, struct pcap_pkthdr **pkthdr,
const u_char **pktdata, const char *funcname,
const int line, const char *file)
{
int res = pcap_next_ex(pcap, pkthdr, pktdata);
if (*pktdata && *pkthdr) {
if ((*pkthdr)->len > MAXPACKET) {
fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n",
file, funcname, line, (*pkthdr)->len, MAXPACKET);
exit(-1);
}
if ((*pkthdr)->len < (*pkthdr)->caplen) {
fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: packet length %u is less than capture length %u\n",
file, funcname, line, (*pkthdr)->len, (*pkthdr)->caplen);
exit(-1);
}
}
return res;
}
Commit Message: Bug #520 Fix heap overflow on zero or 0xFFFF packet length
Add check for packets that report zero packet length. Example
of fix:
src/tcpprep --auto=bridge --pcap=poc16-get_l2len-heapoverflow --cachefile=/dev/null
Warning: poc16-get_l2len-heapoverflow was captured using a snaplen of 17 bytes. This may mean you have truncated packets.
safe_pcap_next ERROR: Invalid packet length in tcpprep.c:process_raw_packets() line 334: packet length=0 capture length=0
CWE ID: CWE-125 | int _our_safe_pcap_next_ex(pcap_t *pcap, struct pcap_pkthdr **pkthdr,
const u_char **pktdata, const char *funcname,
const int line, const char *file)
{
int res = pcap_next_ex(pcap, pkthdr, pktdata);
if (*pktdata && *pkthdr) {
if ((*pkthdr)->len > MAXPACKET) {
fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n",
file, funcname, line, (*pkthdr)->len, MAXPACKET);
exit(-1);
}
if (!(*pkthdr)->len || (*pkthdr)->len < (*pkthdr)->caplen) {
fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: packet length=%u capture length=%u\n",
file, funcname, line, (*pkthdr)->len, (*pkthdr)->caplen);
exit(-1);
}
}
return res;
}
| 168,947 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MessageLoop::RunTask(PendingTask* pending_task) {
DCHECK(nestable_tasks_allowed_);
current_pending_task_ = pending_task;
#if defined(OS_WIN)
DecrementHighResTaskCountIfNeeded(*pending_task);
#endif
nestable_tasks_allowed_ = false;
TRACE_TASK_EXECUTION("MessageLoop::RunTask", *pending_task);
for (auto& observer : task_observers_)
observer.WillProcessTask(*pending_task);
task_annotator_.RunTask("MessageLoop::PostTask", pending_task);
for (auto& observer : task_observers_)
observer.DidProcessTask(*pending_task);
nestable_tasks_allowed_ = true;
current_pending_task_ = nullptr;
}
Commit Message: Introduce RunLoop::Type::NESTABLE_TASKS_ALLOWED to replace MessageLoop::ScopedNestableTaskAllower.
(as well as MessageLoop::SetNestableTasksAllowed())
Surveying usage: the scoped object is always instantiated right before
RunLoop().Run(). The intent is really to allow nestable tasks in that
RunLoop so it's better to explicitly label that RunLoop as such and it
allows us to break the last dependency that forced some RunLoop users
to use MessageLoop APIs.
There's also the odd case of allowing nestable tasks for loops that are
reentrant from a native task (without going through RunLoop), these
are the minority but will have to be handled (after cleaning up the
majority of cases that are RunLoop induced).
As highlighted by robliao@ in https://chromium-review.googlesource.com/c/600517
(which was merged in this CL).
[email protected]
Bug: 750779
Change-Id: I43d122c93ec903cff3a6fe7b77ec461ea0656448
Reviewed-on: https://chromium-review.googlesource.com/594713
Commit-Queue: Gabriel Charette <[email protected]>
Reviewed-by: Robert Liao <[email protected]>
Reviewed-by: danakj <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492263}
CWE ID: | void MessageLoop::RunTask(PendingTask* pending_task) {
DCHECK(NestableTasksAllowed());
current_pending_task_ = pending_task;
#if defined(OS_WIN)
DecrementHighResTaskCountIfNeeded(*pending_task);
#endif
nestable_tasks_allowed_ = false;
TRACE_TASK_EXECUTION("MessageLoop::RunTask", *pending_task);
for (auto& observer : task_observers_)
observer.WillProcessTask(*pending_task);
task_annotator_.RunTask("MessageLoop::PostTask", pending_task);
for (auto& observer : task_observers_)
observer.DidProcessTask(*pending_task);
nestable_tasks_allowed_ = true;
current_pending_task_ = nullptr;
}
| 171,866 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: _rsvg_io_get_file_path (const gchar * filename,
const gchar * base_uri)
{
gchar *absolute_filename;
if (g_file_test (filename, G_FILE_TEST_EXISTS) || g_path_is_absolute (filename)) {
absolute_filename = g_strdup (filename);
} else {
gchar *tmpcdir;
gchar *base_filename;
if (base_uri) {
base_filename = g_filename_from_uri (base_uri, NULL, NULL);
if (base_filename != NULL) {
tmpcdir = g_path_get_dirname (base_filename);
g_free (base_filename);
} else
return NULL;
} else
tmpcdir = g_get_current_dir ();
absolute_filename = g_build_filename (tmpcdir, filename, NULL);
g_free (tmpcdir);
}
return absolute_filename;
}
Commit Message: Fixed possible credentials leaking reported by Alex Birsan.
CWE ID: | _rsvg_io_get_file_path (const gchar * filename,
const gchar * base_uri)
{
gchar *absolute_filename;
if (g_path_is_absolute (filename)) {
absolute_filename = g_strdup (filename);
} else {
gchar *tmpcdir;
gchar *base_filename;
if (base_uri) {
base_filename = g_filename_from_uri (base_uri, NULL, NULL);
if (base_filename != NULL) {
tmpcdir = g_path_get_dirname (base_filename);
g_free (base_filename);
} else
return NULL;
} else
tmpcdir = g_get_current_dir ();
absolute_filename = g_build_filename (tmpcdir, filename, NULL);
g_free (tmpcdir);
}
return absolute_filename;
}
| 170,157 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 NaClProcessHost::OnMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg)
IPC_MESSAGE_HANDLER(NaClProcessMsg_QueryKnownToValidate,
OnQueryKnownToValidate)
IPC_MESSAGE_HANDLER(NaClProcessMsg_SetKnownToValidate,
OnSetKnownToValidate)
#if defined(OS_WIN)
IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClProcessMsg_AttachDebugExceptionHandler,
OnAttachDebugExceptionHandler)
#endif
IPC_MESSAGE_HANDLER(NaClProcessHostMsg_PpapiChannelCreated,
OnPpapiChannelCreated)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg)
IPC_MESSAGE_HANDLER(NaClProcessMsg_QueryKnownToValidate,
OnQueryKnownToValidate)
IPC_MESSAGE_HANDLER(NaClProcessMsg_SetKnownToValidate,
OnSetKnownToValidate)
#if defined(OS_WIN)
IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClProcessMsg_AttachDebugExceptionHandler,
OnAttachDebugExceptionHandler)
#endif
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
| 170,725 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *nlmsg_reserve(struct nl_msg *n, size_t len, int pad)
{
void *buf = n->nm_nlh;
size_t nlmsg_len = n->nm_nlh->nlmsg_len;
size_t tlen;
tlen = pad ? ((len + (pad - 1)) & ~(pad - 1)) : len;
if ((tlen + nlmsg_len) > n->nm_size)
n->nm_nlh->nlmsg_len += tlen;
if (tlen > len)
memset(buf + len, 0, tlen - len);
NL_DBG(2, "msg %p: Reserved %zu (%zu) bytes, pad=%d, nlmsg_len=%d\n",
n, tlen, len, pad, n->nm_nlh->nlmsg_len);
return buf;
}
Commit Message:
CWE ID: CWE-190 | void *nlmsg_reserve(struct nl_msg *n, size_t len, int pad)
{
void *buf = n->nm_nlh;
size_t nlmsg_len = n->nm_nlh->nlmsg_len;
size_t tlen;
if (len > n->nm_size)
return NULL;
tlen = pad ? ((len + (pad - 1)) & ~(pad - 1)) : len;
if ((tlen + nlmsg_len) > n->nm_size)
n->nm_nlh->nlmsg_len += tlen;
if (tlen > len)
memset(buf + len, 0, tlen - len);
NL_DBG(2, "msg %p: Reserved %zu (%zu) bytes, pad=%d, nlmsg_len=%d\n",
n, tlen, len, pad, n->nm_nlh->nlmsg_len);
return buf;
}
| 165,218 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 nr_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name;
size_t copied;
struct sk_buff *skb;
int er;
/*
* This works for seqpacket too. The receiver has ordered the queue for
* us! We do one quick check first though
*/
lock_sock(sk);
if (sk->sk_state != TCP_ESTABLISHED) {
release_sock(sk);
return -ENOTCONN;
}
/* Now we can treat all alike */
if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) {
release_sock(sk);
return er;
}
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
er = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (er < 0) {
skb_free_datagram(sk, skb);
release_sock(sk);
return er;
}
if (sax != NULL) {
memset(sax, 0, sizeof(sax));
sax->sax25_family = AF_NETROM;
skb_copy_from_linear_data_offset(skb, 7, sax->sax25_call.ax25_call,
AX25_ADDR_LEN);
}
msg->msg_namelen = sizeof(*sax);
skb_free_datagram(sk, skb);
release_sock(sk);
return copied;
}
Commit Message: netrom: fix invalid use of sizeof in nr_recvmsg()
sizeof() when applied to a pointer typed expression gives the size of the
pointer, not that of the pointed data.
Introduced by commit 3ce5ef(netrom: fix info leak via msg_name in nr_recvmsg)
Signed-off-by: Wei Yongjun <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int nr_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name;
size_t copied;
struct sk_buff *skb;
int er;
/*
* This works for seqpacket too. The receiver has ordered the queue for
* us! We do one quick check first though
*/
lock_sock(sk);
if (sk->sk_state != TCP_ESTABLISHED) {
release_sock(sk);
return -ENOTCONN;
}
/* Now we can treat all alike */
if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) {
release_sock(sk);
return er;
}
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
er = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (er < 0) {
skb_free_datagram(sk, skb);
release_sock(sk);
return er;
}
if (sax != NULL) {
memset(sax, 0, sizeof(*sax));
sax->sax25_family = AF_NETROM;
skb_copy_from_linear_data_offset(skb, 7, sax->sax25_call.ax25_call,
AX25_ADDR_LEN);
}
msg->msg_namelen = sizeof(*sax);
skb_free_datagram(sk, skb);
release_sock(sk);
return copied;
}
| 169,894 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DirectoryEntrySync* DirectoryEntrySync::getDirectory(const String& path, const Dictionary& options, ExceptionState& exceptionState)
{
FileSystemFlags flags(options);
RefPtr<EntrySyncCallbackHelper> helper = EntrySyncCallbackHelper::create();
m_fileSystem->getDirectory(this, path, flags, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return static_cast<DirectoryEntrySync*>(helper->getResult(exceptionState));
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | DirectoryEntrySync* DirectoryEntrySync::getDirectory(const String& path, const Dictionary& options, ExceptionState& exceptionState)
{
FileSystemFlags flags(options);
EntrySyncCallbackHelper* helper = EntrySyncCallbackHelper::create();
m_fileSystem->getDirectory(this, path, flags, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return static_cast<DirectoryEntrySync*>(helper->getResult(exceptionState));
}
| 171,417 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LinkChangeSerializerMarkupAccumulator::appendElement(StringBuilder& result, Element& element, Namespaces* namespaces)
{
if (element.hasTagName(HTMLNames::htmlTag)) {
result.append('\n');
MarkupFormatter::appendComment(result, String::format(" saved from url=(%04d)%s ",
static_cast<int>(document().url().string().utf8().length()),
document().url().string().utf8().data()));
result.append('\n');
}
if (element.hasTagName(HTMLNames::baseTag)) {
result.appendLiteral("<base href=\".\"");
if (!document().baseTarget().isEmpty()) {
result.appendLiteral(" target=\"");
MarkupFormatter::appendAttributeValue(result, document().baseTarget(), document().isHTMLDocument());
result.append('"');
}
if (document().isXHTMLDocument())
result.appendLiteral(" />");
else
result.appendLiteral(">");
} else {
SerializerMarkupAccumulator::appendElement(result, element, namespaces);
}
}
Commit Message: Escape "--" in the page URL at page serialization
This patch makes page serializer to escape the page URL embed into a HTML
comment of result HTML[1] to avoid inserting text as HTML from URL by
introducing a static member function |PageSerialzier::markOfTheWebDeclaration()|
for sharing it between |PageSerialzier| and |WebPageSerialzier| classes.
[1] We use following format for serialized HTML:
saved from url=(${lengthOfURL})${URL}
BUG=503217
TEST=webkit_unit_tests --gtest_filter=PageSerializerTest.markOfTheWebDeclaration
TEST=webkit_unit_tests --gtest_filter=WebPageSerializerTest.fromUrlWithMinusMinu
Review URL: https://codereview.chromium.org/1371323003
Cr-Commit-Position: refs/heads/master@{#351736}
CWE ID: CWE-20 | void LinkChangeSerializerMarkupAccumulator::appendElement(StringBuilder& result, Element& element, Namespaces* namespaces)
{
if (element.hasTagName(HTMLNames::htmlTag)) {
result.append('\n');
MarkupFormatter::appendComment(result, PageSerializer::markOfTheWebDeclaration(document().url()));
result.append('\n');
}
if (element.hasTagName(HTMLNames::baseTag)) {
result.appendLiteral("<base href=\".\"");
if (!document().baseTarget().isEmpty()) {
result.appendLiteral(" target=\"");
MarkupFormatter::appendAttributeValue(result, document().baseTarget(), document().isHTMLDocument());
result.append('"');
}
if (document().isXHTMLDocument())
result.appendLiteral(" />");
else
result.appendLiteral(">");
} else {
SerializerMarkupAccumulator::appendElement(result, element, namespaces);
}
}
| 171,785 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DeviceTokenFetcher::StopAutoRetry() {
scheduler_->CancelDelayedWork();
backend_.reset();
}
Commit Message: Reset the device policy machinery upon retrying enrollment.
BUG=chromium-os:18208
TEST=See bug description
Review URL: http://codereview.chromium.org/7676005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void DeviceTokenFetcher::StopAutoRetry() {
void DeviceTokenFetcher::Reset() {
SetState(STATE_INACTIVE);
}
| 170,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: void ScriptLoader::executeScript(const ScriptSourceCode& sourceCode)
{
ASSERT(m_alreadyStarted);
if (sourceCode.isEmpty())
return;
RefPtr<Document> elementDocument(m_element->document());
RefPtr<Document> contextDocument = elementDocument->contextDocument().get();
if (!contextDocument)
return;
LocalFrame* frame = contextDocument->frame();
bool shouldBypassMainWorldContentSecurityPolicy = (frame && frame->script().shouldBypassMainWorldContentSecurityPolicy()) || elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr)) || elementDocument->contentSecurityPolicy()->allowScriptHash(sourceCode.source());
if (!m_isExternalScript && (!shouldBypassMainWorldContentSecurityPolicy && !elementDocument->contentSecurityPolicy()->allowInlineScript(elementDocument->url(), m_startLineNumber)))
return;
if (m_isExternalScript && m_resource && !m_resource->mimeTypeAllowedByNosniff()) {
contextDocument->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Refused to execute script from '" + m_resource->url().elidedString() + "' because its MIME type ('" + m_resource->mimeType() + "') is not executable, and strict MIME type checking is enabled.");
return;
}
if (frame) {
const bool isImportedScript = contextDocument != elementDocument;
IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_isExternalScript || isImportedScript ? contextDocument.get() : 0);
if (isHTMLScriptLoader(m_element))
contextDocument->pushCurrentScript(toHTMLScriptElement(m_element));
AccessControlStatus corsCheck = NotSharableCrossOrigin;
if (sourceCode.resource() && sourceCode.resource()->passesAccessControlCheck(m_element->document().securityOrigin()))
corsCheck = SharableCrossOrigin;
frame->script().executeScriptInMainWorld(sourceCode, corsCheck);
if (isHTMLScriptLoader(m_element)) {
ASSERT(contextDocument->currentScript() == m_element);
contextDocument->popCurrentScript();
}
}
}
Commit Message: Apply 'x-content-type-options' check to dynamically inserted script.
BUG=348581
Review URL: https://codereview.chromium.org/185593011
git-svn-id: svn://svn.chromium.org/blink/trunk@168570 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-362 | void ScriptLoader::executeScript(const ScriptSourceCode& sourceCode)
{
ASSERT(m_alreadyStarted);
if (sourceCode.isEmpty())
return;
RefPtr<Document> elementDocument(m_element->document());
RefPtr<Document> contextDocument = elementDocument->contextDocument().get();
if (!contextDocument)
return;
LocalFrame* frame = contextDocument->frame();
bool shouldBypassMainWorldContentSecurityPolicy = (frame && frame->script().shouldBypassMainWorldContentSecurityPolicy()) || elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr)) || elementDocument->contentSecurityPolicy()->allowScriptHash(sourceCode.source());
if (!m_isExternalScript && (!shouldBypassMainWorldContentSecurityPolicy && !elementDocument->contentSecurityPolicy()->allowInlineScript(elementDocument->url(), m_startLineNumber)))
return;
if (m_isExternalScript) {
ScriptResource* resource = m_resource ? m_resource.get() : sourceCode.resource();
if (resource && !resource->mimeTypeAllowedByNosniff()) {
contextDocument->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Refused to execute script from '" + resource->url().elidedString() + "' because its MIME type ('" + resource->mimeType() + "') is not executable, and strict MIME type checking is enabled.");
return;
}
}
if (frame) {
const bool isImportedScript = contextDocument != elementDocument;
IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_isExternalScript || isImportedScript ? contextDocument.get() : 0);
if (isHTMLScriptLoader(m_element))
contextDocument->pushCurrentScript(toHTMLScriptElement(m_element));
AccessControlStatus corsCheck = NotSharableCrossOrigin;
if (sourceCode.resource() && sourceCode.resource()->passesAccessControlCheck(m_element->document().securityOrigin()))
corsCheck = SharableCrossOrigin;
frame->script().executeScriptInMainWorld(sourceCode, corsCheck);
if (isHTMLScriptLoader(m_element)) {
ASSERT(contextDocument->currentScript() == m_element);
contextDocument->popCurrentScript();
}
}
}
| 171,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: CURLcode Curl_urldecode(struct SessionHandle *data,
const char *string, size_t length,
char **ostring, size_t *olen,
bool reject_ctrl)
{
size_t alloc = (length?length:strlen(string))+1;
char *ns = malloc(alloc);
unsigned char in;
size_t strindex=0;
unsigned long hex;
CURLcode res;
if(!ns)
return CURLE_OUT_OF_MEMORY;
while(--alloc > 0) {
in = *string;
if(('%' == in) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) {
/* this is two hexadecimal digits following a '%' */
char hexstr[3];
char *ptr;
hexstr[0] = string[1];
hexstr[1] = string[2];
hexstr[2] = 0;
hex = strtoul(hexstr, &ptr, 16);
in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */
res = Curl_convert_from_network(data, &in, 1);
if(res) {
/* Curl_convert_from_network calls failf if unsuccessful */
free(ns);
return res;
}
string+=2;
alloc-=2;
}
if(reject_ctrl && (in < 0x20)) {
free(ns);
return CURLE_URL_MALFORMAT;
}
ns[strindex++] = in;
string++;
}
ns[strindex]=0; /* terminate it */
if(olen)
/* store output size */
*olen = strindex;
if(ostring)
/* store output string */
*ostring = ns;
return CURLE_OK;
}
Commit Message: Curl_urldecode: no peeking beyond end of input buffer
Security problem: CVE-2013-2174
If a program would give a string like "%FF" to curl_easy_unescape() but
ask for it to decode only the first byte, it would still parse and
decode the full hex sequence. The function then not only read beyond the
allowed buffer but it would also deduct the *unsigned* counter variable
for how many more bytes there's left to read in the buffer by two,
making the counter wrap. Continuing this, the function would go on
reading beyond the buffer and soon writing beyond the allocated target
buffer...
Bug: http://curl.haxx.se/docs/adv_20130622.html
Reported-by: Timo Sirainen
CWE ID: CWE-119 | CURLcode Curl_urldecode(struct SessionHandle *data,
const char *string, size_t length,
char **ostring, size_t *olen,
bool reject_ctrl)
{
size_t alloc = (length?length:strlen(string))+1;
char *ns = malloc(alloc);
unsigned char in;
size_t strindex=0;
unsigned long hex;
CURLcode res;
if(!ns)
return CURLE_OUT_OF_MEMORY;
while(--alloc > 0) {
in = *string;
if(('%' == in) && (alloc > 2) &&
ISXDIGIT(string[1]) && ISXDIGIT(string[2])) {
/* this is two hexadecimal digits following a '%' */
char hexstr[3];
char *ptr;
hexstr[0] = string[1];
hexstr[1] = string[2];
hexstr[2] = 0;
hex = strtoul(hexstr, &ptr, 16);
in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */
res = Curl_convert_from_network(data, &in, 1);
if(res) {
/* Curl_convert_from_network calls failf if unsuccessful */
free(ns);
return res;
}
string+=2;
alloc-=2;
}
if(reject_ctrl && (in < 0x20)) {
free(ns);
return CURLE_URL_MALFORMAT;
}
ns[strindex++] = in;
string++;
}
ns[strindex]=0; /* terminate it */
if(olen)
/* store output size */
*olen = strindex;
if(ostring)
/* store output string */
*ostring = ns;
return CURLE_OK;
}
| 166,080 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Maybe<bool> IncludesValueImpl(Isolate* isolate,
Handle<JSObject> receiver,
Handle<Object> value,
uint32_t start_from, uint32_t length) {
DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));
bool search_for_hole = value->IsUndefined(isolate);
if (!search_for_hole) {
Maybe<bool> result = Nothing<bool>();
if (DictionaryElementsAccessor::IncludesValueFastPath(
isolate, receiver, value, start_from, length, &result)) {
return result;
}
}
Handle<SeededNumberDictionary> dictionary(
SeededNumberDictionary::cast(receiver->elements()), isolate);
for (uint32_t k = start_from; k < length; ++k) {
int entry = dictionary->FindEntry(isolate, k);
if (entry == SeededNumberDictionary::kNotFound) {
if (search_for_hole) return Just(true);
continue;
}
PropertyDetails details = GetDetailsImpl(*dictionary, entry);
switch (details.kind()) {
case kData: {
Object* element_k = dictionary->ValueAt(entry);
if (value->SameValueZero(element_k)) return Just(true);
break;
}
case kAccessor: {
LookupIterator it(isolate, receiver, k,
LookupIterator::OWN_SKIP_INTERCEPTOR);
DCHECK(it.IsFound());
DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
Handle<Object> element_k;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate, element_k, JSObject::GetPropertyWithAccessor(&it),
Nothing<bool>());
if (value->SameValueZero(*element_k)) return Just(true);
if (!JSObject::PrototypeHasNoElements(isolate, *receiver)) {
return IncludesValueSlowPath(isolate, receiver, value, k + 1,
length);
}
if (*dictionary == receiver->elements()) continue;
if (receiver->GetElementsKind() != DICTIONARY_ELEMENTS) {
if (receiver->map()->GetInitialElements() == receiver->elements()) {
return Just(search_for_hole);
}
return IncludesValueSlowPath(isolate, receiver, value, k + 1,
length);
}
dictionary = handle(
SeededNumberDictionary::cast(receiver->elements()), isolate);
break;
}
}
}
return Just(false);
}
Commit Message: Backport: Fix Object.entries/values with changing elements
Bug: 111274046
Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \
/data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest
Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb
(cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99)
CWE ID: CWE-704 | static Maybe<bool> IncludesValueImpl(Isolate* isolate,
Handle<JSObject> receiver,
Handle<Object> value,
uint32_t start_from, uint32_t length) {
DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));
bool search_for_hole = value->IsUndefined(isolate);
if (!search_for_hole) {
Maybe<bool> result = Nothing<bool>();
if (DictionaryElementsAccessor::IncludesValueFastPath(
isolate, receiver, value, start_from, length, &result)) {
return result;
}
}
Handle<Map> original_map(receiver->map(), isolate);
Handle<SeededNumberDictionary> dictionary(
SeededNumberDictionary::cast(receiver->elements()), isolate);
for (uint32_t k = start_from; k < length; ++k) {
DCHECK_EQ(receiver->map(), *original_map);
int entry = dictionary->FindEntry(isolate, k);
if (entry == SeededNumberDictionary::kNotFound) {
if (search_for_hole) return Just(true);
continue;
}
PropertyDetails details = GetDetailsImpl(*dictionary, entry);
switch (details.kind()) {
case kData: {
Object* element_k = dictionary->ValueAt(entry);
if (value->SameValueZero(element_k)) return Just(true);
break;
}
case kAccessor: {
LookupIterator it(isolate, receiver, k,
LookupIterator::OWN_SKIP_INTERCEPTOR);
DCHECK(it.IsFound());
DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
Handle<Object> element_k;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate, element_k, JSObject::GetPropertyWithAccessor(&it),
Nothing<bool>());
if (value->SameValueZero(*element_k)) return Just(true);
if (!JSObject::PrototypeHasNoElements(isolate, *receiver)) {
return IncludesValueSlowPath(isolate, receiver, value, k + 1,
length);
}
if (*dictionary == receiver->elements()) continue;
if (receiver->GetElementsKind() != DICTIONARY_ELEMENTS) {
if (receiver->map()->GetInitialElements() == receiver->elements()) {
return Just(search_for_hole);
}
return IncludesValueSlowPath(isolate, receiver, value, k + 1,
length);
}
dictionary = handle(
SeededNumberDictionary::cast(receiver->elements()), isolate);
break;
}
}
}
return Just(false);
}
| 174,096 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: CSSStyleSheet* CSSStyleSheet::CreateInline(Node& owner_node,
const KURL& base_url,
const TextPosition& start_position,
const WTF::TextEncoding& encoding) {
CSSParserContext* parser_context = CSSParserContext::Create(
owner_node.GetDocument(), owner_node.GetDocument().BaseURL(),
owner_node.GetDocument().GetReferrerPolicy(), encoding);
StyleSheetContents* sheet =
StyleSheetContents::Create(base_url.GetString(), parser_context);
return new CSSStyleSheet(sheet, owner_node, true, start_position);
}
Commit Message: Disallow access to opaque CSS responses.
Bug: 848786
Change-Id: Ie53fbf644afdd76d7c65649a05c939c63d89b4ec
Reviewed-on: https://chromium-review.googlesource.com/1088335
Reviewed-by: Kouhei Ueno <[email protected]>
Commit-Queue: Matt Falkenhagen <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565537}
CWE ID: CWE-200 | CSSStyleSheet* CSSStyleSheet::CreateInline(Node& owner_node,
const KURL& base_url,
const TextPosition& start_position,
const WTF::TextEncoding& encoding) {
CSSParserContext* parser_context = CSSParserContext::Create(
owner_node.GetDocument(), owner_node.GetDocument().BaseURL(),
false /* is_opaque_response_from_service_worker */,
owner_node.GetDocument().GetReferrerPolicy(), encoding);
StyleSheetContents* sheet =
StyleSheetContents::Create(base_url.GetString(), parser_context);
return new CSSStyleSheet(sheet, owner_node, true, start_position);
}
| 173,154 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct r_bin_dyldcache_obj_t* r_bin_dyldcache_from_bytes_new(const ut8* buf, ut64 size) {
struct r_bin_dyldcache_obj_t *bin;
if (!(bin = malloc (sizeof (struct r_bin_dyldcache_obj_t)))) {
return NULL;
}
memset (bin, 0, sizeof (struct r_bin_dyldcache_obj_t));
if (!buf) {
return r_bin_dyldcache_free (bin);
}
bin->b = r_buf_new();
if (!r_buf_set_bytes (bin->b, buf, size)) {
return r_bin_dyldcache_free (bin);
}
if (!r_bin_dyldcache_init (bin)) {
return r_bin_dyldcache_free (bin);
}
bin->size = size;
return bin;
}
Commit Message: Fix #12374 - oobread crash in truncated dyldcache ##bin
CWE ID: CWE-125 | struct r_bin_dyldcache_obj_t* r_bin_dyldcache_from_bytes_new(const ut8* buf, ut64 size) {
struct r_bin_dyldcache_obj_t *bin = R_NEW0 (struct r_bin_dyldcache_obj_t);
if (!bin) {
return NULL;
}
if (!buf) {
return r_bin_dyldcache_free (bin);
}
bin->b = r_buf_new ();
if (!bin->b || !r_buf_set_bytes (bin->b, buf, size)) {
return r_bin_dyldcache_free (bin);
}
if (!r_bin_dyldcache_init (bin)) {
return r_bin_dyldcache_free (bin);
}
bin->size = size;
return bin;
}
| 168,955 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_filter_matches)
{
char* lang_tag = NULL;
int lang_tag_len = 0;
const char* loc_range = NULL;
int loc_range_len = 0;
int result = 0;
char* token = 0;
char* chrcheck = NULL;
char* can_lang_tag = NULL;
char* can_loc_range = NULL;
char* cur_lang_tag = NULL;
char* cur_loc_range = NULL;
zend_bool boolCanonical = 0;
UErrorCode status = U_ZERO_ERROR;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "ss|b",
&lang_tag, &lang_tag_len , &loc_range , &loc_range_len ,
&boolCanonical) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_filter_matches: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
if(loc_range_len == 0) {
loc_range = intl_locale_get_default(TSRMLS_C);
}
if( strcmp(loc_range,"*")==0){
RETURN_TRUE;
}
if( boolCanonical ){
/* canonicalize loc_range */
can_loc_range=get_icu_value_internal( loc_range , LOC_CANONICALIZE_TAG , &result , 0);
if( result ==0) {
intl_error_set( NULL, status,
"locale_filter_matches : unable to canonicalize loc_range" , 0 TSRMLS_CC );
RETURN_FALSE;
}
/* canonicalize lang_tag */
can_lang_tag = get_icu_value_internal( lang_tag , LOC_CANONICALIZE_TAG , &result , 0);
if( result ==0) {
intl_error_set( NULL, status,
"locale_filter_matches : unable to canonicalize lang_tag" , 0 TSRMLS_CC );
RETURN_FALSE;
}
/* Convert to lower case for case-insensitive comparison */
cur_lang_tag = ecalloc( 1, strlen(can_lang_tag) + 1);
/* Convert to lower case for case-insensitive comparison */
result = strToMatch( can_lang_tag , cur_lang_tag);
if( result == 0) {
efree( cur_lang_tag );
efree( can_lang_tag );
RETURN_FALSE;
}
cur_loc_range = ecalloc( 1, strlen(can_loc_range) + 1);
result = strToMatch( can_loc_range , cur_loc_range );
if( result == 0) {
efree( cur_lang_tag );
efree( can_lang_tag );
efree( cur_loc_range );
efree( can_loc_range );
RETURN_FALSE;
}
/* check if prefix */
token = strstr( cur_lang_tag , cur_loc_range );
if( token && (token==cur_lang_tag) ){
/* check if the char. after match is SEPARATOR */
chrcheck = token + (strlen(cur_loc_range));
if( isIDSeparator(*chrcheck) || isEndOfTag(*chrcheck) ){
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
if( can_lang_tag){
efree( can_lang_tag );
}
if( can_loc_range){
efree( can_loc_range );
}
RETURN_TRUE;
}
}
/* No prefix as loc_range */
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
if( can_lang_tag){
efree( can_lang_tag );
}
if( can_loc_range){
efree( can_loc_range );
}
RETURN_FALSE;
} /* end of if isCanonical */
else{
/* Convert to lower case for case-insensitive comparison */
cur_lang_tag = ecalloc( 1, strlen(lang_tag ) + 1);
result = strToMatch( lang_tag , cur_lang_tag);
if( result == 0) {
efree( cur_lang_tag );
RETURN_FALSE;
}
cur_loc_range = ecalloc( 1, strlen(loc_range ) + 1);
result = strToMatch( loc_range , cur_loc_range );
if( result == 0) {
efree( cur_lang_tag );
efree( cur_loc_range );
RETURN_FALSE;
}
/* check if prefix */
token = strstr( cur_lang_tag , cur_loc_range );
if( token && (token==cur_lang_tag) ){
/* check if the char. after match is SEPARATOR */
chrcheck = token + (strlen(cur_loc_range));
if( isIDSeparator(*chrcheck) || isEndOfTag(*chrcheck) ){
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
RETURN_TRUE;
}
}
/* No prefix as loc_range */
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
RETURN_FALSE;
}
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | PHP_FUNCTION(locale_filter_matches)
{
char* lang_tag = NULL;
int lang_tag_len = 0;
const char* loc_range = NULL;
int loc_range_len = 0;
int result = 0;
char* token = 0;
char* chrcheck = NULL;
char* can_lang_tag = NULL;
char* can_loc_range = NULL;
char* cur_lang_tag = NULL;
char* cur_loc_range = NULL;
zend_bool boolCanonical = 0;
UErrorCode status = U_ZERO_ERROR;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "ss|b",
&lang_tag, &lang_tag_len , &loc_range , &loc_range_len ,
&boolCanonical) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_filter_matches: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
if(loc_range_len == 0) {
loc_range = intl_locale_get_default(TSRMLS_C);
}
if( strcmp(loc_range,"*")==0){
RETURN_TRUE;
}
if( boolCanonical ){
/* canonicalize loc_range */
can_loc_range=get_icu_value_internal( loc_range , LOC_CANONICALIZE_TAG , &result , 0);
if( result ==0) {
intl_error_set( NULL, status,
"locale_filter_matches : unable to canonicalize loc_range" , 0 TSRMLS_CC );
RETURN_FALSE;
}
/* canonicalize lang_tag */
can_lang_tag = get_icu_value_internal( lang_tag , LOC_CANONICALIZE_TAG , &result , 0);
if( result ==0) {
intl_error_set( NULL, status,
"locale_filter_matches : unable to canonicalize lang_tag" , 0 TSRMLS_CC );
RETURN_FALSE;
}
/* Convert to lower case for case-insensitive comparison */
cur_lang_tag = ecalloc( 1, strlen(can_lang_tag) + 1);
/* Convert to lower case for case-insensitive comparison */
result = strToMatch( can_lang_tag , cur_lang_tag);
if( result == 0) {
efree( cur_lang_tag );
efree( can_lang_tag );
RETURN_FALSE;
}
cur_loc_range = ecalloc( 1, strlen(can_loc_range) + 1);
result = strToMatch( can_loc_range , cur_loc_range );
if( result == 0) {
efree( cur_lang_tag );
efree( can_lang_tag );
efree( cur_loc_range );
efree( can_loc_range );
RETURN_FALSE;
}
/* check if prefix */
token = strstr( cur_lang_tag , cur_loc_range );
if( token && (token==cur_lang_tag) ){
/* check if the char. after match is SEPARATOR */
chrcheck = token + (strlen(cur_loc_range));
if( isIDSeparator(*chrcheck) || isEndOfTag(*chrcheck) ){
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
if( can_lang_tag){
efree( can_lang_tag );
}
if( can_loc_range){
efree( can_loc_range );
}
RETURN_TRUE;
}
}
/* No prefix as loc_range */
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
if( can_lang_tag){
efree( can_lang_tag );
}
if( can_loc_range){
efree( can_loc_range );
}
RETURN_FALSE;
} /* end of if isCanonical */
else{
/* Convert to lower case for case-insensitive comparison */
cur_lang_tag = ecalloc( 1, strlen(lang_tag ) + 1);
result = strToMatch( lang_tag , cur_lang_tag);
if( result == 0) {
efree( cur_lang_tag );
RETURN_FALSE;
}
cur_loc_range = ecalloc( 1, strlen(loc_range ) + 1);
result = strToMatch( loc_range , cur_loc_range );
if( result == 0) {
efree( cur_lang_tag );
efree( cur_loc_range );
RETURN_FALSE;
}
/* check if prefix */
token = strstr( cur_lang_tag , cur_loc_range );
if( token && (token==cur_lang_tag) ){
/* check if the char. after match is SEPARATOR */
chrcheck = token + (strlen(cur_loc_range));
if( isIDSeparator(*chrcheck) || isEndOfTag(*chrcheck) ){
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
RETURN_TRUE;
}
}
/* No prefix as loc_range */
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
RETURN_FALSE;
}
}
| 167,193 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: nvmet_fc_find_target_queue(struct nvmet_fc_tgtport *tgtport,
u64 connection_id)
{
struct nvmet_fc_tgt_assoc *assoc;
struct nvmet_fc_tgt_queue *queue;
u64 association_id = nvmet_fc_getassociationid(connection_id);
u16 qid = nvmet_fc_getqueueid(connection_id);
unsigned long flags;
spin_lock_irqsave(&tgtport->lock, flags);
list_for_each_entry(assoc, &tgtport->assoc_list, a_list) {
if (association_id == assoc->association_id) {
queue = assoc->queues[qid];
if (queue &&
(!atomic_read(&queue->connected) ||
!nvmet_fc_tgt_q_get(queue)))
queue = NULL;
spin_unlock_irqrestore(&tgtport->lock, flags);
return queue;
}
}
spin_unlock_irqrestore(&tgtport->lock, flags);
return NULL;
}
Commit Message: nvmet-fc: ensure target queue id within range.
When searching for queue id's ensure they are within the expected range.
Signed-off-by: James Smart <[email protected]>
Signed-off-by: Christoph Hellwig <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-119 | nvmet_fc_find_target_queue(struct nvmet_fc_tgtport *tgtport,
u64 connection_id)
{
struct nvmet_fc_tgt_assoc *assoc;
struct nvmet_fc_tgt_queue *queue;
u64 association_id = nvmet_fc_getassociationid(connection_id);
u16 qid = nvmet_fc_getqueueid(connection_id);
unsigned long flags;
if (qid > NVMET_NR_QUEUES)
return NULL;
spin_lock_irqsave(&tgtport->lock, flags);
list_for_each_entry(assoc, &tgtport->assoc_list, a_list) {
if (association_id == assoc->association_id) {
queue = assoc->queues[qid];
if (queue &&
(!atomic_read(&queue->connected) ||
!nvmet_fc_tgt_q_get(queue)))
queue = NULL;
spin_unlock_irqrestore(&tgtport->lock, flags);
return queue;
}
}
spin_unlock_irqrestore(&tgtport->lock, flags);
return NULL;
}
| 169,859 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BnSoundTriggerHwService::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch(code) {
case LIST_MODULES: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
unsigned int numModulesReq = data.readInt32();
unsigned int numModules = numModulesReq;
struct sound_trigger_module_descriptor *modules =
(struct sound_trigger_module_descriptor *)calloc(numModulesReq,
sizeof(struct sound_trigger_module_descriptor));
status_t status = listModules(modules, &numModules);
reply->writeInt32(status);
reply->writeInt32(numModules);
ALOGV("LIST_MODULES status %d got numModules %d", status, numModules);
if (status == NO_ERROR) {
if (numModulesReq > numModules) {
numModulesReq = numModules;
}
reply->write(modules,
numModulesReq * sizeof(struct sound_trigger_module_descriptor));
}
free(modules);
return NO_ERROR;
}
case ATTACH: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
sound_trigger_module_handle_t handle;
data.read(&handle, sizeof(sound_trigger_module_handle_t));
sp<ISoundTriggerClient> client =
interface_cast<ISoundTriggerClient>(data.readStrongBinder());
sp<ISoundTrigger> module;
status_t status = attach(handle, client, module);
reply->writeInt32(status);
if (module != 0) {
reply->writeInt32(1);
reply->writeStrongBinder(IInterface::asBinder(module));
} else {
reply->writeInt32(0);
}
return NO_ERROR;
} break;
case SET_CAPTURE_STATE: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
reply->writeInt32(setCaptureState((bool)data.readInt32()));
return NO_ERROR;
} break;
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
Commit Message: Check memory allocation in ISoundTriggerHwService
Add memory allocation check in ISoundTriggerHwService::listModules().
Bug: 19385640.
Change-Id: Iaf74b6f154c3437e1bfc9da78b773d64b16a7604
CWE ID: CWE-190 | status_t BnSoundTriggerHwService::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch(code) {
case LIST_MODULES: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
unsigned int numModulesReq = data.readInt32();
if (numModulesReq > MAX_ITEMS_PER_LIST) {
numModulesReq = MAX_ITEMS_PER_LIST;
}
unsigned int numModules = numModulesReq;
struct sound_trigger_module_descriptor *modules =
(struct sound_trigger_module_descriptor *)calloc(numModulesReq,
sizeof(struct sound_trigger_module_descriptor));
if (modules == NULL) {
reply->writeInt32(NO_MEMORY);
reply->writeInt32(0);
return NO_ERROR;
}
status_t status = listModules(modules, &numModules);
reply->writeInt32(status);
reply->writeInt32(numModules);
ALOGV("LIST_MODULES status %d got numModules %d", status, numModules);
if (status == NO_ERROR) {
if (numModulesReq > numModules) {
numModulesReq = numModules;
}
reply->write(modules,
numModulesReq * sizeof(struct sound_trigger_module_descriptor));
}
free(modules);
return NO_ERROR;
}
case ATTACH: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
sound_trigger_module_handle_t handle;
data.read(&handle, sizeof(sound_trigger_module_handle_t));
sp<ISoundTriggerClient> client =
interface_cast<ISoundTriggerClient>(data.readStrongBinder());
sp<ISoundTrigger> module;
status_t status = attach(handle, client, module);
reply->writeInt32(status);
if (module != 0) {
reply->writeInt32(1);
reply->writeStrongBinder(IInterface::asBinder(module));
} else {
reply->writeInt32(0);
}
return NO_ERROR;
} break;
case SET_CAPTURE_STATE: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
reply->writeInt32(setCaptureState((bool)data.readInt32()));
return NO_ERROR;
} break;
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
| 174,072 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sctp_rcv(struct sk_buff *skb)
{
struct sock *sk;
struct sctp_association *asoc;
struct sctp_endpoint *ep = NULL;
struct sctp_ep_common *rcvr;
struct sctp_transport *transport = NULL;
struct sctp_chunk *chunk;
struct sctphdr *sh;
union sctp_addr src;
union sctp_addr dest;
int family;
struct sctp_af *af;
if (skb->pkt_type!=PACKET_HOST)
goto discard_it;
SCTP_INC_STATS_BH(SCTP_MIB_INSCTPPACKS);
if (skb_linearize(skb))
goto discard_it;
sh = sctp_hdr(skb);
/* Pull up the IP and SCTP headers. */
__skb_pull(skb, skb_transport_offset(skb));
if (skb->len < sizeof(struct sctphdr))
goto discard_it;
if (!skb_csum_unnecessary(skb) && sctp_rcv_checksum(skb) < 0)
goto discard_it;
skb_pull(skb, sizeof(struct sctphdr));
/* Make sure we at least have chunk headers worth of data left. */
if (skb->len < sizeof(struct sctp_chunkhdr))
goto discard_it;
family = ipver2af(ip_hdr(skb)->version);
af = sctp_get_af_specific(family);
if (unlikely(!af))
goto discard_it;
/* Initialize local addresses for lookups. */
af->from_skb(&src, skb, 1);
af->from_skb(&dest, skb, 0);
/* If the packet is to or from a non-unicast address,
* silently discard the packet.
*
* This is not clearly defined in the RFC except in section
* 8.4 - OOTB handling. However, based on the book "Stream Control
* Transmission Protocol" 2.1, "It is important to note that the
* IP address of an SCTP transport address must be a routable
* unicast address. In other words, IP multicast addresses and
* IP broadcast addresses cannot be used in an SCTP transport
* address."
*/
if (!af->addr_valid(&src, NULL, skb) ||
!af->addr_valid(&dest, NULL, skb))
goto discard_it;
asoc = __sctp_rcv_lookup(skb, &src, &dest, &transport);
if (!asoc)
ep = __sctp_rcv_lookup_endpoint(&dest);
/* Retrieve the common input handling substructure. */
rcvr = asoc ? &asoc->base : &ep->base;
sk = rcvr->sk;
/*
* If a frame arrives on an interface and the receiving socket is
* bound to another interface, via SO_BINDTODEVICE, treat it as OOTB
*/
if (sk->sk_bound_dev_if && (sk->sk_bound_dev_if != af->skb_iif(skb)))
{
if (asoc) {
sctp_association_put(asoc);
asoc = NULL;
} else {
sctp_endpoint_put(ep);
ep = NULL;
}
sk = sctp_get_ctl_sock();
ep = sctp_sk(sk)->ep;
sctp_endpoint_hold(ep);
rcvr = &ep->base;
}
/*
* RFC 2960, 8.4 - Handle "Out of the blue" Packets.
* An SCTP packet is called an "out of the blue" (OOTB)
* packet if it is correctly formed, i.e., passed the
* receiver's checksum check, but the receiver is not
* able to identify the association to which this
* packet belongs.
*/
if (!asoc) {
if (sctp_rcv_ootb(skb)) {
SCTP_INC_STATS_BH(SCTP_MIB_OUTOFBLUES);
goto discard_release;
}
}
if (!xfrm_policy_check(sk, XFRM_POLICY_IN, skb, family))
goto discard_release;
nf_reset(skb);
if (sk_filter(sk, skb))
goto discard_release;
/* Create an SCTP packet structure. */
chunk = sctp_chunkify(skb, asoc, sk);
if (!chunk)
goto discard_release;
SCTP_INPUT_CB(skb)->chunk = chunk;
/* Remember what endpoint is to handle this packet. */
chunk->rcvr = rcvr;
/* Remember the SCTP header. */
chunk->sctp_hdr = sh;
/* Set the source and destination addresses of the incoming chunk. */
sctp_init_addrs(chunk, &src, &dest);
/* Remember where we came from. */
chunk->transport = transport;
/* Acquire access to the sock lock. Note: We are safe from other
* bottom halves on this lock, but a user may be in the lock too,
* so check if it is busy.
*/
sctp_bh_lock_sock(sk);
if (sock_owned_by_user(sk)) {
SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_BACKLOG);
sctp_add_backlog(sk, skb);
} else {
SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_SOFTIRQ);
sctp_inq_push(&chunk->rcvr->inqueue, chunk);
}
sctp_bh_unlock_sock(sk);
/* Release the asoc/ep ref we took in the lookup calls. */
if (asoc)
sctp_association_put(asoc);
else
sctp_endpoint_put(ep);
return 0;
discard_it:
SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_DISCARDS);
kfree_skb(skb);
return 0;
discard_release:
/* Release the asoc/ep ref we took in the lookup calls. */
if (asoc)
sctp_association_put(asoc);
else
sctp_endpoint_put(ep);
goto discard_it;
}
Commit Message: sctp: Fix another socket race during accept/peeloff
There is a race between sctp_rcv() and sctp_accept() where we
have moved the association from the listening socket to the
accepted socket, but sctp_rcv() processing cached the old
socket and continues to use it.
The easy solution is to check for the socket mismatch once we've
grabed the socket lock. If we hit a mis-match, that means
that were are currently holding the lock on the listening socket,
but the association is refrencing a newly accepted socket. We need
to drop the lock on the old socket and grab the lock on the new one.
A more proper solution might be to create accepted sockets when
the new association is established, similar to TCP. That would
eliminate the race for 1-to-1 style sockets, but it would still
existing for 1-to-many sockets where a user wished to peeloff an
association. For now, we'll live with this easy solution as
it addresses the problem.
Reported-by: Michal Hocko <[email protected]>
Reported-by: Karsten Keil <[email protected]>
Signed-off-by: Vlad Yasevich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | int sctp_rcv(struct sk_buff *skb)
{
struct sock *sk;
struct sctp_association *asoc;
struct sctp_endpoint *ep = NULL;
struct sctp_ep_common *rcvr;
struct sctp_transport *transport = NULL;
struct sctp_chunk *chunk;
struct sctphdr *sh;
union sctp_addr src;
union sctp_addr dest;
int family;
struct sctp_af *af;
if (skb->pkt_type!=PACKET_HOST)
goto discard_it;
SCTP_INC_STATS_BH(SCTP_MIB_INSCTPPACKS);
if (skb_linearize(skb))
goto discard_it;
sh = sctp_hdr(skb);
/* Pull up the IP and SCTP headers. */
__skb_pull(skb, skb_transport_offset(skb));
if (skb->len < sizeof(struct sctphdr))
goto discard_it;
if (!skb_csum_unnecessary(skb) && sctp_rcv_checksum(skb) < 0)
goto discard_it;
skb_pull(skb, sizeof(struct sctphdr));
/* Make sure we at least have chunk headers worth of data left. */
if (skb->len < sizeof(struct sctp_chunkhdr))
goto discard_it;
family = ipver2af(ip_hdr(skb)->version);
af = sctp_get_af_specific(family);
if (unlikely(!af))
goto discard_it;
/* Initialize local addresses for lookups. */
af->from_skb(&src, skb, 1);
af->from_skb(&dest, skb, 0);
/* If the packet is to or from a non-unicast address,
* silently discard the packet.
*
* This is not clearly defined in the RFC except in section
* 8.4 - OOTB handling. However, based on the book "Stream Control
* Transmission Protocol" 2.1, "It is important to note that the
* IP address of an SCTP transport address must be a routable
* unicast address. In other words, IP multicast addresses and
* IP broadcast addresses cannot be used in an SCTP transport
* address."
*/
if (!af->addr_valid(&src, NULL, skb) ||
!af->addr_valid(&dest, NULL, skb))
goto discard_it;
asoc = __sctp_rcv_lookup(skb, &src, &dest, &transport);
if (!asoc)
ep = __sctp_rcv_lookup_endpoint(&dest);
/* Retrieve the common input handling substructure. */
rcvr = asoc ? &asoc->base : &ep->base;
sk = rcvr->sk;
/*
* If a frame arrives on an interface and the receiving socket is
* bound to another interface, via SO_BINDTODEVICE, treat it as OOTB
*/
if (sk->sk_bound_dev_if && (sk->sk_bound_dev_if != af->skb_iif(skb)))
{
if (asoc) {
sctp_association_put(asoc);
asoc = NULL;
} else {
sctp_endpoint_put(ep);
ep = NULL;
}
sk = sctp_get_ctl_sock();
ep = sctp_sk(sk)->ep;
sctp_endpoint_hold(ep);
rcvr = &ep->base;
}
/*
* RFC 2960, 8.4 - Handle "Out of the blue" Packets.
* An SCTP packet is called an "out of the blue" (OOTB)
* packet if it is correctly formed, i.e., passed the
* receiver's checksum check, but the receiver is not
* able to identify the association to which this
* packet belongs.
*/
if (!asoc) {
if (sctp_rcv_ootb(skb)) {
SCTP_INC_STATS_BH(SCTP_MIB_OUTOFBLUES);
goto discard_release;
}
}
if (!xfrm_policy_check(sk, XFRM_POLICY_IN, skb, family))
goto discard_release;
nf_reset(skb);
if (sk_filter(sk, skb))
goto discard_release;
/* Create an SCTP packet structure. */
chunk = sctp_chunkify(skb, asoc, sk);
if (!chunk)
goto discard_release;
SCTP_INPUT_CB(skb)->chunk = chunk;
/* Remember what endpoint is to handle this packet. */
chunk->rcvr = rcvr;
/* Remember the SCTP header. */
chunk->sctp_hdr = sh;
/* Set the source and destination addresses of the incoming chunk. */
sctp_init_addrs(chunk, &src, &dest);
/* Remember where we came from. */
chunk->transport = transport;
/* Acquire access to the sock lock. Note: We are safe from other
* bottom halves on this lock, but a user may be in the lock too,
* so check if it is busy.
*/
sctp_bh_lock_sock(sk);
if (sk != rcvr->sk) {
/* Our cached sk is different from the rcvr->sk. This is
* because migrate()/accept() may have moved the association
* to a new socket and released all the sockets. So now we
* are holding a lock on the old socket while the user may
* be doing something with the new socket. Switch our veiw
* of the current sk.
*/
sctp_bh_unlock_sock(sk);
sk = rcvr->sk;
sctp_bh_lock_sock(sk);
}
if (sock_owned_by_user(sk)) {
SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_BACKLOG);
sctp_add_backlog(sk, skb);
} else {
SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_SOFTIRQ);
sctp_inq_push(&chunk->rcvr->inqueue, chunk);
}
sctp_bh_unlock_sock(sk);
/* Release the asoc/ep ref we took in the lookup calls. */
if (asoc)
sctp_association_put(asoc);
else
sctp_endpoint_put(ep);
return 0;
discard_it:
SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_DISCARDS);
kfree_skb(skb);
return 0;
discard_release:
/* Release the asoc/ep ref we took in the lookup calls. */
if (asoc)
sctp_association_put(asoc);
else
sctp_endpoint_put(ep);
goto discard_it;
}
| 166,208 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftAMR::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (mMode == MODE_NARROW) {
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.amrnb",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
} else {
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.amrwb",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAmr:
{
const OMX_AUDIO_PARAM_AMRTYPE *aacParams =
(const OMX_AUDIO_PARAM_AMRTYPE *)params;
if (aacParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftAMR::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (mMode == MODE_NARROW) {
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.amrnb",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
} else {
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.amrwb",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAmr:
{
const OMX_AUDIO_PARAM_AMRTYPE *aacParams =
(const OMX_AUDIO_PARAM_AMRTYPE *)params;
if (!isValidOMXParam(aacParams)) {
return OMX_ErrorBadParameter;
}
if (aacParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,193 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParseNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *other) {
register const xmlChar *cmp = other;
register const xmlChar *in;
const xmlChar *ret;
GROW;
in = ctxt->input->cur;
while (*in != 0 && *in == *cmp) {
++in;
++cmp;
ctxt->input->col++;
}
if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) {
/* success */
ctxt->input->cur = in;
return (const xmlChar*) 1;
}
/* failure (or end of input buffer), check with full function */
ret = xmlParseName (ctxt);
/* strings coming from the dictionnary direct compare possible */
if (ret == other) {
return (const xmlChar*) 1;
}
return ret;
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *other) {
register const xmlChar *cmp = other;
register const xmlChar *in;
const xmlChar *ret;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
in = ctxt->input->cur;
while (*in != 0 && *in == *cmp) {
++in;
++cmp;
ctxt->input->col++;
}
if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) {
/* success */
ctxt->input->cur = in;
return (const xmlChar*) 1;
}
/* failure (or end of input buffer), check with full function */
ret = xmlParseName (ctxt);
/* strings coming from the dictionnary direct compare possible */
if (ret == other) {
return (const xmlChar*) 1;
}
return ret;
}
| 171,296 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MakeUsernameForAccount(const base::DictionaryValue* result,
base::string16* gaia_id,
wchar_t* username,
DWORD username_length,
wchar_t* domain,
DWORD domain_length,
wchar_t* sid,
DWORD sid_length) {
DCHECK(gaia_id);
DCHECK(username);
DCHECK(domain);
DCHECK(sid);
*gaia_id = GetDictString(result, kKeyId);
HRESULT hr = GetSidFromId(*gaia_id, sid, sid_length);
if (SUCCEEDED(hr)) {
hr = OSUserManager::Get()->FindUserBySID(sid, username, username_length,
domain, domain_length);
if (SUCCEEDED(hr))
return;
}
LOGFN(INFO) << "No existing user found associated to gaia id:" << *gaia_id;
wcscpy_s(domain, domain_length, OSUserManager::GetLocalDomain().c_str());
username[0] = 0;
sid[0] = 0;
base::string16 os_username = GetDictString(result, kKeyEmail);
std::transform(os_username.begin(), os_username.end(), os_username.begin(),
::tolower);
base::string16::size_type at = os_username.find(L"@gmail.com");
if (at == base::string16::npos)
at = os_username.find(L"@googlemail.com");
if (at != base::string16::npos) {
os_username.resize(at);
} else {
std::string username_utf8 =
gaia::SanitizeEmail(base::UTF16ToUTF8(os_username));
size_t tld_length =
net::registry_controlled_domains::GetCanonicalHostRegistryLength(
gaia::ExtractDomainName(username_utf8),
net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
if (tld_length > 0) {
username_utf8.resize(username_utf8.length() - tld_length - 1);
os_username = base::UTF8ToUTF16(username_utf8);
}
}
if (os_username.size() > kWindowsUsernameBufferLength - 1)
os_username.resize(kWindowsUsernameBufferLength - 1);
for (auto& c : os_username) {
if (wcschr(L"@\\[]:|<>+=;?*", c) != nullptr || c < 32)
c = L'_';
}
wcscpy_s(username, username_length, os_username.c_str());
}
Commit Message: [GCPW] Disallow sign in of consumer accounts when mdm is enabled.
Unless the registry key "mdm_aca" is explicitly set to 1, always
fail sign in of consumer accounts when mdm enrollment is enabled.
Consumer accounts are defined as accounts with gmail.com or
googlemail.com domain.
Bug: 944049
Change-Id: Icb822f3737d90931de16a8d3317616dd2b159edd
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1532903
Commit-Queue: Tien Mai <[email protected]>
Reviewed-by: Roger Tawa <[email protected]>
Cr-Commit-Position: refs/heads/master@{#646278}
CWE ID: CWE-284 | void MakeUsernameForAccount(const base::DictionaryValue* result,
base::string16* gaia_id,
wchar_t* username,
DWORD username_length,
wchar_t* domain,
DWORD domain_length,
wchar_t* sid,
DWORD sid_length,
bool* is_consumer_account) {
DCHECK(gaia_id);
DCHECK(username);
DCHECK(domain);
DCHECK(sid);
DCHECK(is_consumer_account);
// Determine if the email is a consumer domain (gmail.com or googlemail.com).
base::string16 email = GetDictString(result, kKeyEmail);
std::transform(email.begin(), email.end(), email.begin(), ::tolower);
base::string16::size_type consumer_domain_pos = email.find(L"@gmail.com");
if (consumer_domain_pos == base::string16::npos)
consumer_domain_pos = email.find(L"@googlemail.com");
*is_consumer_account = consumer_domain_pos != base::string16::npos;
*gaia_id = GetDictString(result, kKeyId);
HRESULT hr = GetSidFromId(*gaia_id, sid, sid_length);
if (SUCCEEDED(hr)) {
hr = OSUserManager::Get()->FindUserBySID(sid, username, username_length,
domain, domain_length);
if (SUCCEEDED(hr))
return;
}
LOGFN(INFO) << "No existing user found associated to gaia id:" << *gaia_id;
wcscpy_s(domain, domain_length, OSUserManager::GetLocalDomain().c_str());
username[0] = 0;
sid[0] = 0;
base::string16 os_username = email;
// If the email is a consumer domain, strip it.
if (consumer_domain_pos != base::string16::npos) {
os_username.resize(consumer_domain_pos);
} else {
std::string username_utf8 =
gaia::SanitizeEmail(base::UTF16ToUTF8(os_username));
size_t tld_length =
net::registry_controlled_domains::GetCanonicalHostRegistryLength(
gaia::ExtractDomainName(username_utf8),
net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
if (tld_length > 0) {
username_utf8.resize(username_utf8.length() - tld_length - 1);
os_username = base::UTF8ToUTF16(username_utf8);
}
}
if (os_username.size() > kWindowsUsernameBufferLength - 1)
os_username.resize(kWindowsUsernameBufferLength - 1);
for (auto& c : os_username) {
if (wcschr(L"@\\[]:|<>+=;?*", c) != nullptr || c < 32)
c = L'_';
}
wcscpy_s(username, username_length, os_username.c_str());
}
| 172,100 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Initialize(bool can_respond_to_crypto_handshake = true) {
clock_.AdvanceTime(quic::QuicTime::Delta::FromMilliseconds(1000));
runner_ = new net::test::TestTaskRunner(&clock_);
net::QuicChromiumAlarmFactory* alarm_factory =
new net::QuicChromiumAlarmFactory(runner_.get(), &clock_);
quic_transport_factory_ = std::make_unique<P2PQuicTransportFactoryImpl>(
&clock_, std::unique_ptr<net::QuicChromiumAlarmFactory>(alarm_factory));
auto client_packet_transport =
std::make_unique<FakePacketTransport>(alarm_factory, &clock_);
auto server_packet_transport =
std::make_unique<FakePacketTransport>(alarm_factory, &clock_);
client_packet_transport->ConnectPeerTransport(
server_packet_transport.get());
server_packet_transport->ConnectPeerTransport(
client_packet_transport.get());
rtc::scoped_refptr<rtc::RTCCertificate> client_cert =
CreateTestCertificate();
auto client_quic_transport_delegate =
std::make_unique<MockP2PQuicTransportDelegate>();
std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> client_certificates;
client_certificates.push_back(client_cert);
P2PQuicTransportConfig client_config(client_quic_transport_delegate.get(),
client_packet_transport.get(),
client_certificates);
client_config.is_server = false;
client_config.can_respond_to_crypto_handshake =
can_respond_to_crypto_handshake;
P2PQuicTransportImpl* client_quic_transport_ptr =
static_cast<P2PQuicTransportImpl*>(
quic_transport_factory_
->CreateQuicTransport(std::move(client_config))
.release());
std::unique_ptr<P2PQuicTransportImpl> client_quic_transport =
std::unique_ptr<P2PQuicTransportImpl>(client_quic_transport_ptr);
client_peer_ = std::make_unique<QuicPeerForTest>(
std::move(client_packet_transport),
std::move(client_quic_transport_delegate),
std::move(client_quic_transport), client_cert);
auto server_quic_transport_delegate =
std::make_unique<MockP2PQuicTransportDelegate>();
rtc::scoped_refptr<rtc::RTCCertificate> server_cert =
CreateTestCertificate();
std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> server_certificates;
server_certificates.push_back(server_cert);
P2PQuicTransportConfig server_config(server_quic_transport_delegate.get(),
server_packet_transport.get(),
server_certificates);
server_config.is_server = true;
server_config.can_respond_to_crypto_handshake =
can_respond_to_crypto_handshake;
P2PQuicTransportImpl* server_quic_transport_ptr =
static_cast<P2PQuicTransportImpl*>(
quic_transport_factory_
->CreateQuicTransport(std::move(server_config))
.release());
std::unique_ptr<P2PQuicTransportImpl> server_quic_transport =
std::unique_ptr<P2PQuicTransportImpl>(server_quic_transport_ptr);
server_peer_ = std::make_unique<QuicPeerForTest>(
std::move(server_packet_transport),
std::move(server_quic_transport_delegate),
std::move(server_quic_transport), server_cert);
}
Commit Message: P2PQuicStream write functionality.
This adds the P2PQuicStream::WriteData function and adds tests. It also
adds the concept of a write buffered amount, enforcing this at the
P2PQuicStreamImpl.
Bug: 874296
Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131
Reviewed-on: https://chromium-review.googlesource.com/c/1315534
Commit-Queue: Seth Hampson <[email protected]>
Reviewed-by: Henrik Boström <[email protected]>
Cr-Commit-Position: refs/heads/master@{#605766}
CWE ID: CWE-284 | void Initialize(bool can_respond_to_crypto_handshake = true) {
clock_.AdvanceTime(quic::QuicTime::Delta::FromMilliseconds(1000));
runner_ = new net::test::TestTaskRunner(&clock_);
net::QuicChromiumAlarmFactory* alarm_factory =
new net::QuicChromiumAlarmFactory(runner_.get(), &clock_);
quic_transport_factory_ = std::make_unique<P2PQuicTransportFactoryImpl>(
&clock_, std::unique_ptr<net::QuicChromiumAlarmFactory>(alarm_factory));
auto client_packet_transport =
std::make_unique<FakePacketTransport>(alarm_factory, &clock_);
auto server_packet_transport =
std::make_unique<FakePacketTransport>(alarm_factory, &clock_);
client_packet_transport->ConnectPeerTransport(
server_packet_transport.get());
server_packet_transport->ConnectPeerTransport(
client_packet_transport.get());
rtc::scoped_refptr<rtc::RTCCertificate> client_cert =
CreateTestCertificate();
auto client_quic_transport_delegate =
std::make_unique<MockP2PQuicTransportDelegate>();
std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> client_certificates;
client_certificates.push_back(client_cert);
P2PQuicTransportConfig client_config(client_quic_transport_delegate.get(),
client_packet_transport.get(),
client_certificates, kWriteBufferSize);
client_config.is_server = false;
client_config.can_respond_to_crypto_handshake =
can_respond_to_crypto_handshake;
P2PQuicTransportImpl* client_quic_transport_ptr =
static_cast<P2PQuicTransportImpl*>(
quic_transport_factory_
->CreateQuicTransport(std::move(client_config))
.release());
std::unique_ptr<P2PQuicTransportImpl> client_quic_transport =
std::unique_ptr<P2PQuicTransportImpl>(client_quic_transport_ptr);
client_peer_ = std::make_unique<QuicPeerForTest>(
std::move(client_packet_transport),
std::move(client_quic_transport_delegate),
std::move(client_quic_transport), client_cert);
auto server_quic_transport_delegate =
std::make_unique<MockP2PQuicTransportDelegate>();
rtc::scoped_refptr<rtc::RTCCertificate> server_cert =
CreateTestCertificate();
std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> server_certificates;
server_certificates.push_back(server_cert);
P2PQuicTransportConfig server_config(server_quic_transport_delegate.get(),
server_packet_transport.get(),
server_certificates, kWriteBufferSize);
server_config.is_server = true;
server_config.can_respond_to_crypto_handshake =
can_respond_to_crypto_handshake;
P2PQuicTransportImpl* server_quic_transport_ptr =
static_cast<P2PQuicTransportImpl*>(
quic_transport_factory_
->CreateQuicTransport(std::move(server_config))
.release());
std::unique_ptr<P2PQuicTransportImpl> server_quic_transport =
std::unique_ptr<P2PQuicTransportImpl>(server_quic_transport_ptr);
server_peer_ = std::make_unique<QuicPeerForTest>(
std::move(server_packet_transport),
std::move(server_quic_transport_delegate),
std::move(server_quic_transport), server_cert);
}
| 172,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 em_fxsave(struct x86_emulate_ctxt *ctxt)
{
struct fxregs_state fx_state;
size_t size;
int rc;
rc = check_fxsr(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->ops->get_fpu(ctxt);
rc = asm_safe("fxsave %[fx]", , [fx] "+m"(fx_state));
ctxt->ops->put_fpu(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
if (ctxt->ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR)
size = offsetof(struct fxregs_state, xmm_space[8 * 16/4]);
else
size = offsetof(struct fxregs_state, xmm_space[0]);
return segmented_write(ctxt, ctxt->memop.addr.mem, &fx_state, size);
}
Commit Message: KVM: x86: Introduce segmented_write_std
Introduces segemented_write_std.
Switches from emulated reads/writes to standard read/writes in fxsave,
fxrstor, sgdt, and sidt. This fixes CVE-2017-2584, a longstanding
kernel memory leak.
Since commit 283c95d0e389 ("KVM: x86: emulate FXSAVE and FXRSTOR",
2016-11-09), which is luckily not yet in any final release, this would
also be an exploitable kernel memory *write*!
Reported-by: Dmitry Vyukov <[email protected]>
Cc: [email protected]
Fixes: 96051572c819194c37a8367624b285be10297eca
Fixes: 283c95d0e3891b64087706b344a4b545d04a6e62
Suggested-by: Paolo Bonzini <[email protected]>
Signed-off-by: Steve Rutherford <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-416 | static int em_fxsave(struct x86_emulate_ctxt *ctxt)
{
struct fxregs_state fx_state;
size_t size;
int rc;
rc = check_fxsr(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->ops->get_fpu(ctxt);
rc = asm_safe("fxsave %[fx]", , [fx] "+m"(fx_state));
ctxt->ops->put_fpu(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
if (ctxt->ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR)
size = offsetof(struct fxregs_state, xmm_space[8 * 16/4]);
else
size = offsetof(struct fxregs_state, xmm_space[0]);
return segmented_write_std(ctxt, ctxt->memop.addr.mem, &fx_state, size);
}
| 168,445 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
X509 **pissuer, int *pscore, unsigned int *preasons,
STACK_OF(X509_CRL) *crls)
{
int i, crl_score, best_score = *pscore;
unsigned int reasons, best_reasons = 0;
X509 *x = ctx->current_cert;
X509_CRL *crl, *best_crl = NULL;
X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
for (i = 0; i < sk_X509_CRL_num(crls); i++) {
crl = sk_X509_CRL_value(crls, i);
reasons = *preasons;
crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
if (crl_score < best_score)
continue;
/* If current CRL is equivalent use it if it is newer */
if (crl_score == best_score) {
int day, sec;
if (ASN1_TIME_diff(&day, &sec, X509_CRL_get_lastUpdate(best_crl),
X509_CRL_get_lastUpdate(crl)) == 0)
continue;
/*
* ASN1_TIME_diff never returns inconsistent signs for |day|
* and |sec|.
*/
if (day <= 0 && sec <= 0)
continue;
}
best_crl = crl;
best_crl_issuer = crl_issuer;
best_score = crl_score;
best_reasons = reasons;
}
if (best_crl) {
if (*pcrl)
X509_CRL_free(*pcrl);
*pcrl = best_crl;
*pissuer = best_crl_issuer;
*pscore = best_score;
*preasons = best_reasons;
CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL);
if (*pdcrl) {
X509_CRL_free(*pdcrl);
*pdcrl = NULL;
}
get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
}
if (best_score >= CRL_SCORE_VALID)
return 1;
return 0;
}
Commit Message:
CWE ID: CWE-476 | static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
X509 **pissuer, int *pscore, unsigned int *preasons,
STACK_OF(X509_CRL) *crls)
{
int i, crl_score, best_score = *pscore;
unsigned int reasons, best_reasons = 0;
X509 *x = ctx->current_cert;
X509_CRL *crl, *best_crl = NULL;
X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
for (i = 0; i < sk_X509_CRL_num(crls); i++) {
crl = sk_X509_CRL_value(crls, i);
reasons = *preasons;
crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
if (crl_score < best_score || crl_score == 0)
continue;
/* If current CRL is equivalent use it if it is newer */
if (crl_score == best_score && best_crl != NULL) {
int day, sec;
if (ASN1_TIME_diff(&day, &sec, X509_CRL_get_lastUpdate(best_crl),
X509_CRL_get_lastUpdate(crl)) == 0)
continue;
/*
* ASN1_TIME_diff never returns inconsistent signs for |day|
* and |sec|.
*/
if (day <= 0 && sec <= 0)
continue;
}
best_crl = crl;
best_crl_issuer = crl_issuer;
best_score = crl_score;
best_reasons = reasons;
}
if (best_crl) {
if (*pcrl)
X509_CRL_free(*pcrl);
*pcrl = best_crl;
*pissuer = best_crl_issuer;
*pscore = best_score;
*preasons = best_reasons;
CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL);
if (*pdcrl) {
X509_CRL_free(*pdcrl);
*pdcrl = NULL;
}
get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
}
if (best_score >= CRL_SCORE_VALID)
return 1;
return 0;
}
| 164,940 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: log2vis_utf8 (PyObject * string, int unicode_length,
FriBidiParType base_direction, int clean, int reordernsm)
{
FriBidiChar *logical = NULL; /* input fribidi unicode buffer */
FriBidiChar *visual = NULL; /* output fribidi unicode buffer */
char *visual_utf8 = NULL; /* output fribidi UTF-8 buffer */
FriBidiStrIndex new_len = 0; /* length of the UTF-8 buffer */
PyObject *result = NULL; /* failure */
/* Allocate fribidi unicode buffers */
logical = PyMem_New (FriBidiChar, unicode_length + 1);
if (logical == NULL)
{
PyErr_SetString (PyExc_MemoryError,
"failed to allocate unicode buffer");
goto cleanup;
}
visual = PyMem_New (FriBidiChar, unicode_length + 1);
if (visual == NULL)
{
PyErr_SetString (PyExc_MemoryError,
"failed to allocate unicode buffer");
goto cleanup;
}
/* Convert to unicode and order visually */
fribidi_set_reorder_nsm(reordernsm);
fribidi_utf8_to_unicode (PyString_AS_STRING (string),
PyString_GET_SIZE (string), logical);
if (!fribidi_log2vis (logical, unicode_length, &base_direction, visual,
NULL, NULL, NULL))
{
PyErr_SetString (PyExc_RuntimeError,
"fribidi failed to order string");
goto cleanup;
}
/* Cleanup the string if requested */
if (clean)
fribidi_remove_bidi_marks (visual, unicode_length, NULL, NULL, NULL);
/* Allocate fribidi UTF-8 buffer */
visual_utf8 = PyMem_New(char, (unicode_length * 4)+1);
if (visual_utf8 == NULL)
{
PyErr_SetString (PyExc_MemoryError,
"failed to allocate UTF-8 buffer");
goto cleanup;
}
/* Encode the reordered string and create result string */
new_len = fribidi_unicode_to_utf8 (visual, unicode_length, visual_utf8);
result = PyString_FromStringAndSize (visual_utf8, new_len);
if (result == NULL)
/* XXX does it raise any error? */
goto cleanup;
cleanup:
/* Delete unicode buffers */
PyMem_Del (logical);
PyMem_Del (visual);
PyMem_Del (visual_utf8);
return result;
}
Commit Message: refactor pyfribidi.c module
pyfribidi.c is now compiled as _pyfribidi. This module only handles
unicode internally and doesn't use the fribidi_utf8_to_unicode
function (which can't handle 4 byte utf-8 sequences). This fixes the
buffer overflow in issue #2.
The code is now also much simpler: pyfribidi.c is down from 280 to 130
lines of code.
We now ship a pure python pyfribidi that handles the case when
non-unicode strings are passed in.
We now also adapt the size of the output string if clean=True is
passed.
CWE ID: CWE-119 | log2vis_utf8 (PyObject * string, int unicode_length,
| 165,642 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BluetoothDeviceChromeOS::SetPasskey(uint32 passkey) {
if (!agent_.get() || passkey_callback_.is_null())
return;
passkey_callback_.Run(SUCCESS, passkey);
passkey_callback_.Reset();
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void BluetoothDeviceChromeOS::SetPasskey(uint32 passkey) {
if (!pairing_context_.get())
return;
pairing_context_->SetPasskey(passkey);
}
| 171,239 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC)
{
zend_lex_state original_lex_state;
zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array));
zend_op_array *original_active_op_array = CG(active_op_array);
zend_op_array *retval=NULL;
int compiler_result;
zend_bool compilation_successful=0;
znode retval_znode;
zend_bool original_in_compilation = CG(in_compilation);
retval_znode.op_type = IS_CONST;
retval_znode.u.constant.type = IS_LONG;
retval_znode.u.constant.value.lval = 1;
Z_UNSET_ISREF(retval_znode.u.constant);
Z_SET_REFCOUNT(retval_znode.u.constant, 1);
zend_save_lexical_state(&original_lex_state TSRMLS_CC);
retval = op_array; /* success oriented */
if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) {
if (type==ZEND_REQUIRE) {
zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC);
zend_bailout();
} else {
zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC);
}
compilation_successful=0;
} else {
init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC);
CG(in_compilation) = 1;
CG(active_op_array) = op_array;
zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context)));
zend_init_compiler_context(TSRMLS_C);
compiler_result = zendparse(TSRMLS_C);
zend_do_return(&retval_znode, 0 TSRMLS_CC);
CG(in_compilation) = original_in_compilation;
if (compiler_result==1) { /* parser error */
zend_bailout();
}
compilation_successful=1;
}
if (retval) {
CG(active_op_array) = original_active_op_array;
if (compilation_successful) {
pass_two(op_array TSRMLS_CC);
zend_release_labels(0 TSRMLS_CC);
} else {
efree(op_array);
retval = NULL;
}
}
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
return retval;
}
Commit Message: fix bug #64660 - yyparse can return 2, not only 1
CWE ID: CWE-20 | ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC)
{
zend_lex_state original_lex_state;
zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array));
zend_op_array *original_active_op_array = CG(active_op_array);
zend_op_array *retval=NULL;
int compiler_result;
zend_bool compilation_successful=0;
znode retval_znode;
zend_bool original_in_compilation = CG(in_compilation);
retval_znode.op_type = IS_CONST;
retval_znode.u.constant.type = IS_LONG;
retval_znode.u.constant.value.lval = 1;
Z_UNSET_ISREF(retval_znode.u.constant);
Z_SET_REFCOUNT(retval_znode.u.constant, 1);
zend_save_lexical_state(&original_lex_state TSRMLS_CC);
retval = op_array; /* success oriented */
if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) {
if (type==ZEND_REQUIRE) {
zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC);
zend_bailout();
} else {
zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC);
}
compilation_successful=0;
} else {
init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC);
CG(in_compilation) = 1;
CG(active_op_array) = op_array;
zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context)));
zend_init_compiler_context(TSRMLS_C);
compiler_result = zendparse(TSRMLS_C);
zend_do_return(&retval_znode, 0 TSRMLS_CC);
CG(in_compilation) = original_in_compilation;
if (compiler_result != 0) { /* parser error */
zend_bailout();
}
compilation_successful=1;
}
if (retval) {
CG(active_op_array) = original_active_op_array;
if (compilation_successful) {
pass_two(op_array TSRMLS_CC);
zend_release_labels(0 TSRMLS_CC);
} else {
efree(op_array);
retval = NULL;
}
}
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
return retval;
}
| 166,023 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: set_value(png_bytep row, size_t rowbytes, png_uint_32 x, unsigned int bit_depth,
png_uint_32 value, png_const_bytep gamma_table, double conv)
{
unsigned int mask = (1U << bit_depth)-1;
x *= bit_depth; /* Maximum x is 4*1024, maximum bit_depth is 16 */
if (value <= mask)
{
png_uint_32 offset = x >> 3;
if (offset < rowbytes && (bit_depth < 16 || offset+1 < rowbytes))
{
row += offset;
switch (bit_depth)
{
case 1:
case 2:
case 4:
/* Don't gamma correct - values get smashed */
{
unsigned int shift = (8 - bit_depth) - (x & 0x7U);
mask <<= shift;
value = (value << shift) & mask;
*row = (png_byte)((*row & ~mask) | value);
}
return;
default:
fprintf(stderr, "makepng: bad bit depth (internal error)\n");
exit(1);
case 16:
value = (unsigned int)floor(65535*pow(value/65535.,conv)+.5);
*row++ = (png_byte)(value >> 8);
*row = (png_byte)value;
return;
case 8:
*row = gamma_table[value];
return;
}
}
else
{
fprintf(stderr, "makepng: row buffer overflow (internal error)\n");
exit(1);
}
}
else
{
fprintf(stderr, "makepng: component overflow (internal error)\n");
exit(1);
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | set_value(png_bytep row, size_t rowbytes, png_uint_32 x, unsigned int bit_depth,
png_uint_32 value, png_const_bytep gamma_table, double conv)
{
unsigned int mask = (1U << bit_depth)-1;
x *= bit_depth; /* Maximum x is 4*1024, maximum bit_depth is 16 */
if (value <= mask)
{
png_uint_32 offset = x >> 3;
if (offset < rowbytes && (bit_depth < 16 || offset+1 < rowbytes))
{
row += offset;
switch (bit_depth)
{
case 1:
case 2:
case 4:
/* Don't gamma correct - values get smashed */
{
unsigned int shift = (8 - bit_depth) - (x & 0x7U);
mask <<= shift;
value = (value << shift) & mask;
*row = (png_byte)((*row & ~mask) | value);
}
return;
default:
fprintf(stderr, "makepng: bad bit depth (internal error)\n");
exit(1);
case 16:
value = flooru(65535*pow(value/65535.,conv)+.5);
*row++ = (png_byte)(value >> 8);
*row = (png_byte)value;
return;
case 8:
*row = gamma_table[value];
return;
}
}
else
{
fprintf(stderr, "makepng: row buffer overflow (internal error)\n");
exit(1);
}
}
else
{
fprintf(stderr, "makepng: component overflow (internal error)\n");
exit(1);
}
}
| 173,585 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SessionRestoreImpl(Profile* profile,
Browser* browser,
bool synchronous,
bool clobber_existing_tab,
bool always_create_tabbed_browser,
const std::vector<GURL>& urls_to_open)
: profile_(profile),
browser_(browser),
synchronous_(synchronous),
clobber_existing_tab_(clobber_existing_tab),
always_create_tabbed_browser_(always_create_tabbed_browser),
urls_to_open_(urls_to_open),
restore_started_(base::TimeTicks::Now()),
browser_shown_(false) {
if (profiles_getting_restored == NULL)
profiles_getting_restored = new std::set<const Profile*>();
CHECK(profiles_getting_restored->find(profile) ==
profiles_getting_restored->end());
profiles_getting_restored->insert(profile);
g_browser_process->AddRefModule();
}
Commit Message: Lands http://codereview.chromium.org/9316065/ for Marja. I reviewed
this, so I'm using TBR to land it.
Don't crash if multiple SessionRestoreImpl:s refer to the same
Profile.
It shouldn't ever happen but it seems to happen anyway.
BUG=111238
TEST=NONE
[email protected]
[email protected]
Review URL: https://chromiumcodereview.appspot.com/9343005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@120648 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | SessionRestoreImpl(Profile* profile,
Browser* browser,
bool synchronous,
bool clobber_existing_tab,
bool always_create_tabbed_browser,
const std::vector<GURL>& urls_to_open)
: profile_(profile),
browser_(browser),
synchronous_(synchronous),
clobber_existing_tab_(clobber_existing_tab),
always_create_tabbed_browser_(always_create_tabbed_browser),
urls_to_open_(urls_to_open),
restore_started_(base::TimeTicks::Now()),
browser_shown_(false) {
// Iterate the active session restorers to find if there is a
// SessionRestoreImpl referring the same profile. This should not happen but
// for some reason it happens still. TODO(marja): figure out why.
if (active_session_restorers == NULL)
active_session_restorers = new std::set<SessionRestoreImpl*>();
std::set<SessionRestoreImpl*>::const_iterator it;
for (it = active_session_restorers->begin();
it != active_session_restorers->end(); ++it) {
if ((*it)->profile_ == profile)
break;
}
DCHECK(it == active_session_restorers->end());
active_session_restorers->insert(this);
g_browser_process->AddRefModule();
}
| 171,037 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: _ksba_name_new_from_der (ksba_name_t *r_name,
const unsigned char *image, size_t imagelen)
{
gpg_error_t err;
ksba_name_t name;
struct tag_info ti;
const unsigned char *der;
size_t derlen;
int n;
char *p;
if (!r_name || !image)
return gpg_error (GPG_ERR_INV_VALUE);
*r_name = NULL;
/* count and check for encoding errors - we won;t do this again
during the second pass */
der = image;
derlen = imagelen;
n = 0;
while (derlen)
{
err = _ksba_ber_parse_tl (&der, &derlen, &ti);
if (err)
return err;
if (ti.class != CLASS_CONTEXT)
return gpg_error (GPG_ERR_INV_CERT_OBJ); /* we expected a tag */
if (ti.ndef)
return gpg_error (GPG_ERR_NOT_DER_ENCODED);
if (derlen < ti.length)
return gpg_error (GPG_ERR_BAD_BER);
switch (ti.tag)
{
case 1: /* rfc822Name - this is an imlicit IA5_STRING */
case 4: /* Name */
case 6: /* URI */
n++;
break;
default:
break;
}
/* advance pointer */
der += ti.length;
derlen -= ti.length;
}
/* allocate array and set all slots to NULL for easier error recovery */
err = ksba_name_new (&name);
if (err)
return err;
if (!n)
return 0; /* empty GeneralNames */
name->names = xtrycalloc (n, sizeof *name->names);
if (!name->names)
{
ksba_name_release (name);
return gpg_error (GPG_ERR_ENOMEM);
}
name->n_names = n;
/* start the second pass */
der = image;
derlen = imagelen;
n = 0;
while (derlen)
{
char numbuf[21];
err = _ksba_ber_parse_tl (&der, &derlen, &ti);
assert (!err);
switch (ti.tag)
{
case 1: /* rfc822Name - this is an imlicit IA5_STRING */
p = name->names[n] = xtrymalloc (ti.length+3);
if (!p)
{
ksba_name_release (name);
return gpg_error (GPG_ERR_ENOMEM);
}
*p++ = '<';
memcpy (p, der, ti.length);
p += ti.length;
*p++ = '>';
*p = 0;
n++;
break;
case 4: /* Name */
err = _ksba_derdn_to_str (der, ti.length, &p);
if (err)
return err; /* FIXME: we need to release some of the memory */
name->names[n++] = p;
break;
case 6: /* URI */
sprintf (numbuf, "%u:", (unsigned int)ti.length);
p = name->names[n] = xtrymalloc (1+5+strlen (numbuf)
+ ti.length +1+1);
if (!p)
{
ksba_name_release (name);
return gpg_error (GPG_ERR_ENOMEM);
}
p = stpcpy (p, "(3:uri");
p = stpcpy (p, numbuf);
memcpy (p, der, ti.length);
p += ti.length;
*p++ = ')';
*p = 0; /* extra safeguard null */
n++;
break;
default:
break;
}
/* advance pointer */
der += ti.length;
derlen -= ti.length;
}
*r_name = name;
return 0;
}
Commit Message:
CWE ID: CWE-20 | _ksba_name_new_from_der (ksba_name_t *r_name,
const unsigned char *image, size_t imagelen)
{
gpg_error_t err;
ksba_name_t name;
struct tag_info ti;
const unsigned char *der;
size_t derlen;
int n;
char *p;
if (!r_name || !image)
return gpg_error (GPG_ERR_INV_VALUE);
*r_name = NULL;
/* Count and check for encoding errors - we won't do this again
during the second pass */
der = image;
derlen = imagelen;
n = 0;
while (derlen)
{
err = _ksba_ber_parse_tl (&der, &derlen, &ti);
if (err)
return err;
if (ti.class != CLASS_CONTEXT)
return gpg_error (GPG_ERR_INV_CERT_OBJ); /* we expected a tag */
if (ti.ndef)
return gpg_error (GPG_ERR_NOT_DER_ENCODED);
if (derlen < ti.length)
return gpg_error (GPG_ERR_BAD_BER);
switch (ti.tag)
{
case 1: /* rfc822Name - this is an imlicit IA5_STRING */
case 4: /* Name */
case 6: /* URI */
n++;
break;
default:
break;
}
/* advance pointer */
der += ti.length;
derlen -= ti.length;
}
/* allocate array and set all slots to NULL for easier error recovery */
err = ksba_name_new (&name);
if (err)
return err;
if (!n)
return 0; /* empty GeneralNames */
name->names = xtrycalloc (n, sizeof *name->names);
if (!name->names)
{
ksba_name_release (name);
return gpg_error (GPG_ERR_ENOMEM);
}
name->n_names = n;
/* start the second pass */
der = image;
derlen = imagelen;
n = 0;
while (derlen)
{
char numbuf[21];
err = _ksba_ber_parse_tl (&der, &derlen, &ti);
assert (!err);
switch (ti.tag)
{
case 1: /* rfc822Name - this is an imlicit IA5_STRING */
p = name->names[n] = xtrymalloc (ti.length+3);
if (!p)
{
ksba_name_release (name);
return gpg_error (GPG_ERR_ENOMEM);
}
*p++ = '<';
memcpy (p, der, ti.length);
p += ti.length;
*p++ = '>';
*p = 0;
n++;
break;
case 4: /* Name */
err = _ksba_derdn_to_str (der, ti.length, &p);
if (err)
return err; /* FIXME: we need to release some of the memory */
name->names[n++] = p;
break;
case 6: /* URI */
sprintf (numbuf, "%u:", (unsigned int)ti.length);
p = name->names[n] = xtrymalloc (1+5+strlen (numbuf)
+ ti.length +1+1);
if (!p)
{
ksba_name_release (name);
return gpg_error (GPG_ERR_ENOMEM);
}
p = stpcpy (p, "(3:uri");
p = stpcpy (p, numbuf);
memcpy (p, der, ti.length);
p += ti.length;
*p++ = ')';
*p = 0; /* extra safeguard null */
n++;
break;
default:
break;
}
/* advance pointer */
der += ti.length;
derlen -= ti.length;
}
*r_name = name;
return 0;
}
| 165,029 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 http_RecvPostMessage(
/*! HTTP Parser object. */
http_parser_t *parser,
/*! [in] Socket Information object. */
SOCKINFO *info,
/*! File where received data is copied to. */
char *filename,
/*! Send Instruction object which gives information whether the file
* is a virtual file or not. */
struct SendInstruction *Instr)
{
size_t Data_Buf_Size = 1024;
char Buf[1024];
int Timeout = -1;
FILE *Fp;
parse_status_t status = PARSE_OK;
int ok_on_close = FALSE;
size_t entity_offset = 0;
int num_read = 0;
int ret_code = HTTP_OK;
if (Instr && Instr->IsVirtualFile) {
Fp = (virtualDirCallback.open) (filename, UPNP_WRITE);
if (Fp == NULL)
return HTTP_INTERNAL_SERVER_ERROR;
} else {
Fp = fopen(filename, "wb");
if (Fp == NULL)
return HTTP_UNAUTHORIZED;
}
parser->position = POS_ENTITY;
do {
/* first parse what has already been gotten */
if (parser->position != POS_COMPLETE)
status = parser_parse_entity(parser);
if (status == PARSE_INCOMPLETE_ENTITY) {
/* read until close */
ok_on_close = TRUE;
} else if ((status != PARSE_SUCCESS)
&& (status != PARSE_CONTINUE_1)
&& (status != PARSE_INCOMPLETE)) {
/* error */
ret_code = HTTP_BAD_REQUEST;
goto ExitFunction;
}
/* read more if necessary entity */
while (entity_offset + Data_Buf_Size > parser->msg.entity.length &&
parser->position != POS_COMPLETE) {
num_read = sock_read(info, Buf, sizeof(Buf), &Timeout);
if (num_read > 0) {
/* append data to buffer */
if (membuffer_append(&parser->msg.msg,
Buf, (size_t)num_read) != 0) {
/* set failure status */
parser->http_error_code =
HTTP_INTERNAL_SERVER_ERROR;
ret_code = HTTP_INTERNAL_SERVER_ERROR;
goto ExitFunction;
}
status = parser_parse_entity(parser);
if (status == PARSE_INCOMPLETE_ENTITY) {
/* read until close */
ok_on_close = TRUE;
} else if ((status != PARSE_SUCCESS)
&& (status != PARSE_CONTINUE_1)
&& (status != PARSE_INCOMPLETE)) {
ret_code = HTTP_BAD_REQUEST;
goto ExitFunction;
}
} else if (num_read == 0) {
if (ok_on_close) {
UpnpPrintf(UPNP_INFO, HTTP, __FILE__, __LINE__,
"<<< (RECVD) <<<\n%s\n-----------------\n",
parser->msg.msg.buf);
print_http_headers(&parser->msg);
parser->position = POS_COMPLETE;
} else {
/* partial msg or response */
parser->http_error_code = HTTP_BAD_REQUEST;
ret_code = HTTP_BAD_REQUEST;
goto ExitFunction;
}
} else {
ret_code = HTTP_SERVICE_UNAVAILABLE;
goto ExitFunction;
}
}
if ((entity_offset + Data_Buf_Size) > parser->msg.entity.length) {
Data_Buf_Size =
parser->msg.entity.length - entity_offset;
}
memcpy(Buf,
&parser->msg.msg.buf[parser->entity_start_position + entity_offset],
Data_Buf_Size);
entity_offset += Data_Buf_Size;
if (Instr && Instr->IsVirtualFile) {
int n = virtualDirCallback.write(Fp, Buf, Data_Buf_Size);
if (n < 0) {
ret_code = HTTP_INTERNAL_SERVER_ERROR;
goto ExitFunction;
}
} else {
size_t n = fwrite(Buf, 1, Data_Buf_Size, Fp);
if (n != Data_Buf_Size) {
ret_code = HTTP_INTERNAL_SERVER_ERROR;
goto ExitFunction;
}
}
} while (parser->position != POS_COMPLETE ||
entity_offset != parser->msg.entity.length);
ExitFunction:
if (Instr && Instr->IsVirtualFile) {
virtualDirCallback.close(Fp);
} else {
fclose(Fp);
}
return ret_code;
}
Commit Message: Don't allow unhandled POSTs to write to the filesystem by default
If there's no registered handler for a POST request, the default behaviour
is to write it to the filesystem. Several million deployed devices appear
to have this behaviour, making it possible to (at least) store arbitrary
data on them. Add a configure option that enables this behaviour, and change
the default to just drop POSTs that aren't directly handled.
CWE ID: CWE-284 | static int http_RecvPostMessage(
/*! HTTP Parser object. */
http_parser_t *parser,
/*! [in] Socket Information object. */
SOCKINFO *info,
/*! File where received data is copied to. */
char *filename,
/*! Send Instruction object which gives information whether the file
* is a virtual file or not. */
struct SendInstruction *Instr)
{
size_t Data_Buf_Size = 1024;
char Buf[1024];
int Timeout = -1;
FILE *Fp;
parse_status_t status = PARSE_OK;
int ok_on_close = FALSE;
size_t entity_offset = 0;
int num_read = 0;
int ret_code = HTTP_OK;
if (Instr && Instr->IsVirtualFile) {
Fp = (virtualDirCallback.open) (filename, UPNP_WRITE);
if (Fp == NULL)
return HTTP_INTERNAL_SERVER_ERROR;
} else {
#ifdef UPNP_ENABLE_POST_WRITE
Fp = fopen(filename, "wb");
if (Fp == NULL)
return HTTP_UNAUTHORIZED;
#else
return HTTP_NOT_FOUND;
#endif
}
parser->position = POS_ENTITY;
do {
/* first parse what has already been gotten */
if (parser->position != POS_COMPLETE)
status = parser_parse_entity(parser);
if (status == PARSE_INCOMPLETE_ENTITY) {
/* read until close */
ok_on_close = TRUE;
} else if ((status != PARSE_SUCCESS)
&& (status != PARSE_CONTINUE_1)
&& (status != PARSE_INCOMPLETE)) {
/* error */
ret_code = HTTP_BAD_REQUEST;
goto ExitFunction;
}
/* read more if necessary entity */
while (entity_offset + Data_Buf_Size > parser->msg.entity.length &&
parser->position != POS_COMPLETE) {
num_read = sock_read(info, Buf, sizeof(Buf), &Timeout);
if (num_read > 0) {
/* append data to buffer */
if (membuffer_append(&parser->msg.msg,
Buf, (size_t)num_read) != 0) {
/* set failure status */
parser->http_error_code =
HTTP_INTERNAL_SERVER_ERROR;
ret_code = HTTP_INTERNAL_SERVER_ERROR;
goto ExitFunction;
}
status = parser_parse_entity(parser);
if (status == PARSE_INCOMPLETE_ENTITY) {
/* read until close */
ok_on_close = TRUE;
} else if ((status != PARSE_SUCCESS)
&& (status != PARSE_CONTINUE_1)
&& (status != PARSE_INCOMPLETE)) {
ret_code = HTTP_BAD_REQUEST;
goto ExitFunction;
}
} else if (num_read == 0) {
if (ok_on_close) {
UpnpPrintf(UPNP_INFO, HTTP, __FILE__, __LINE__,
"<<< (RECVD) <<<\n%s\n-----------------\n",
parser->msg.msg.buf);
print_http_headers(&parser->msg);
parser->position = POS_COMPLETE;
} else {
/* partial msg or response */
parser->http_error_code = HTTP_BAD_REQUEST;
ret_code = HTTP_BAD_REQUEST;
goto ExitFunction;
}
} else {
ret_code = HTTP_SERVICE_UNAVAILABLE;
goto ExitFunction;
}
}
if ((entity_offset + Data_Buf_Size) > parser->msg.entity.length) {
Data_Buf_Size =
parser->msg.entity.length - entity_offset;
}
memcpy(Buf,
&parser->msg.msg.buf[parser->entity_start_position + entity_offset],
Data_Buf_Size);
entity_offset += Data_Buf_Size;
if (Instr && Instr->IsVirtualFile) {
int n = virtualDirCallback.write(Fp, Buf, Data_Buf_Size);
if (n < 0) {
ret_code = HTTP_INTERNAL_SERVER_ERROR;
goto ExitFunction;
}
} else {
size_t n = fwrite(Buf, 1, Data_Buf_Size, Fp);
if (n != Data_Buf_Size) {
ret_code = HTTP_INTERNAL_SERVER_ERROR;
goto ExitFunction;
}
}
} while (parser->position != POS_COMPLETE ||
entity_offset != parser->msg.entity.length);
ExitFunction:
if (Instr && Instr->IsVirtualFile) {
virtualDirCallback.close(Fp);
} else {
fclose(Fp);
}
return ret_code;
}
| 168,831 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: isakmp_rfc3948_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2)
{
if(length == 1 && bp[0]==0xff) {
ND_PRINT((ndo, "isakmp-nat-keep-alive"));
return;
}
if(length < 4) {
goto trunc;
}
/*
* see if this is an IKE packet
*/
if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) {
ND_PRINT((ndo, "NONESP-encap: "));
isakmp_print(ndo, bp+4, length-4, bp2);
return;
}
/* must be an ESP packet */
{
int nh, enh, padlen;
int advance;
ND_PRINT((ndo, "UDP-encap: "));
advance = esp_print(ndo, bp, length, bp2, &enh, &padlen);
if(advance <= 0)
return;
bp += advance;
length -= advance + padlen;
nh = enh & 0xff;
ip_print_inner(ndo, bp, length, nh, bp2);
return;
}
trunc:
ND_PRINT((ndo,"[|isakmp]"));
return;
}
Commit Message: CVE-2017-12896/ISAKMP: Do bounds checks in isakmp_rfc3948_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | isakmp_rfc3948_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2)
{
ND_TCHECK(bp[0]);
if(length == 1 && bp[0]==0xff) {
ND_PRINT((ndo, "isakmp-nat-keep-alive"));
return;
}
if(length < 4) {
goto trunc;
}
ND_TCHECK(bp[3]);
/*
* see if this is an IKE packet
*/
if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) {
ND_PRINT((ndo, "NONESP-encap: "));
isakmp_print(ndo, bp+4, length-4, bp2);
return;
}
/* must be an ESP packet */
{
int nh, enh, padlen;
int advance;
ND_PRINT((ndo, "UDP-encap: "));
advance = esp_print(ndo, bp, length, bp2, &enh, &padlen);
if(advance <= 0)
return;
bp += advance;
length -= advance + padlen;
nh = enh & 0xff;
ip_print_inner(ndo, bp, length, nh, bp2);
return;
}
trunc:
ND_PRINT((ndo,"[|isakmp]"));
return;
}
| 170,035 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_vdec::~omx_vdec()
{
m_pmem_info = NULL;
struct v4l2_decoder_cmd dec;
DEBUG_PRINT_HIGH("In OMX vdec Destructor");
if (m_pipe_in) close(m_pipe_in);
if (m_pipe_out) close(m_pipe_out);
m_pipe_in = -1;
m_pipe_out = -1;
DEBUG_PRINT_HIGH("Waiting on OMX Msg Thread exit");
if (msg_thread_created)
pthread_join(msg_thread_id,NULL);
DEBUG_PRINT_HIGH("Waiting on OMX Async Thread exit");
dec.cmd = V4L2_DEC_CMD_STOP;
if (drv_ctx.video_driver_fd >=0 ) {
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_DECODER_CMD, &dec))
DEBUG_PRINT_ERROR("STOP Command failed");
}
if (async_thread_created)
pthread_join(async_thread_id,NULL);
unsubscribe_to_events(drv_ctx.video_driver_fd);
close(drv_ctx.video_driver_fd);
pthread_mutex_destroy(&m_lock);
pthread_mutex_destroy(&c_lock);
sem_destroy(&m_cmd_lock);
if (perf_flag) {
DEBUG_PRINT_HIGH("--> TOTAL PROCESSING TIME");
dec_time.end();
}
DEBUG_PRINT_INFO("Exit OMX vdec Destructor: fd=%d",drv_ctx.video_driver_fd);
}
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27890802
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVdec problem #6)
CRs-Fixed: 1008882
Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e
CWE ID: | omx_vdec::~omx_vdec()
{
m_pmem_info = NULL;
struct v4l2_decoder_cmd dec;
DEBUG_PRINT_HIGH("In OMX vdec Destructor");
if (m_pipe_in) close(m_pipe_in);
if (m_pipe_out) close(m_pipe_out);
m_pipe_in = -1;
m_pipe_out = -1;
DEBUG_PRINT_HIGH("Waiting on OMX Msg Thread exit");
if (msg_thread_created)
pthread_join(msg_thread_id,NULL);
DEBUG_PRINT_HIGH("Waiting on OMX Async Thread exit");
dec.cmd = V4L2_DEC_CMD_STOP;
if (drv_ctx.video_driver_fd >=0 ) {
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_DECODER_CMD, &dec))
DEBUG_PRINT_ERROR("STOP Command failed");
}
if (async_thread_created)
pthread_join(async_thread_id,NULL);
unsubscribe_to_events(drv_ctx.video_driver_fd);
close(drv_ctx.video_driver_fd);
pthread_mutex_destroy(&m_lock);
pthread_mutex_destroy(&c_lock);
pthread_mutex_destroy(&buf_lock);
sem_destroy(&m_cmd_lock);
if (perf_flag) {
DEBUG_PRINT_HIGH("--> TOTAL PROCESSING TIME");
dec_time.end();
}
DEBUG_PRINT_INFO("Exit OMX vdec Destructor: fd=%d",drv_ctx.video_driver_fd);
}
| 173,754 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int dnxhd_find_frame_end(DNXHDParserContext *dctx,
const uint8_t *buf, int buf_size)
{
ParseContext *pc = &dctx->pc;
uint64_t state = pc->state64;
int pic_found = pc->frame_start_found;
int i = 0;
if (!pic_found) {
for (i = 0; i < buf_size; i++) {
state = (state << 8) | buf[i];
if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {
i++;
pic_found = 1;
dctx->cur_byte = 0;
dctx->remaining = 0;
break;
}
}
}
if (pic_found && !dctx->remaining) {
if (!buf_size) /* EOF considered as end of frame */
return 0;
for (; i < buf_size; i++) {
dctx->cur_byte++;
state = (state << 8) | buf[i];
if (dctx->cur_byte == 24) {
dctx->h = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 26) {
dctx->w = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 42) {
int cid = (state >> 32) & 0xFFFFFFFF;
if (cid <= 0)
continue;
dctx->remaining = avpriv_dnxhd_get_frame_size(cid);
if (dctx->remaining <= 0) {
dctx->remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);
if (dctx->remaining <= 0)
return dctx->remaining;
}
if (buf_size - i + 47 >= dctx->remaining) {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
} else {
dctx->remaining -= buf_size;
}
}
}
} else if (pic_found) {
if (dctx->remaining > buf_size) {
dctx->remaining -= buf_size;
} else {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
}
}
pc->frame_start_found = pic_found;
pc->state64 = state;
return END_NOT_FOUND;
}
Commit Message: avcodec/dnxhd_parser: Do not return invalid value from dnxhd_find_frame_end() on error
Fixes: Null pointer dereference
Fixes: CVE-2017-9608
Found-by: Yihan Lian
Signed-off-by: Michael Niedermayer <[email protected]>
(cherry picked from commit 611b35627488a8d0763e75c25ee0875c5b7987dd)
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-476 | static int dnxhd_find_frame_end(DNXHDParserContext *dctx,
const uint8_t *buf, int buf_size)
{
ParseContext *pc = &dctx->pc;
uint64_t state = pc->state64;
int pic_found = pc->frame_start_found;
int i = 0;
if (!pic_found) {
for (i = 0; i < buf_size; i++) {
state = (state << 8) | buf[i];
if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {
i++;
pic_found = 1;
dctx->cur_byte = 0;
dctx->remaining = 0;
break;
}
}
}
if (pic_found && !dctx->remaining) {
if (!buf_size) /* EOF considered as end of frame */
return 0;
for (; i < buf_size; i++) {
dctx->cur_byte++;
state = (state << 8) | buf[i];
if (dctx->cur_byte == 24) {
dctx->h = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 26) {
dctx->w = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 42) {
int cid = (state >> 32) & 0xFFFFFFFF;
int remaining;
if (cid <= 0)
continue;
remaining = avpriv_dnxhd_get_frame_size(cid);
if (remaining <= 0) {
remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);
if (remaining <= 0)
continue;
}
dctx->remaining = remaining;
if (buf_size - i + 47 >= dctx->remaining) {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
} else {
dctx->remaining -= buf_size;
}
}
}
} else if (pic_found) {
if (dctx->remaining > buf_size) {
dctx->remaining -= buf_size;
} else {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
}
}
pc->frame_start_found = pic_found;
pc->state64 = state;
return END_NOT_FOUND;
}
| 170,046 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: id3_skip (SF_PRIVATE * psf)
{ unsigned char buf [10] ;
memset (buf, 0, sizeof (buf)) ;
psf_binheader_readf (psf, "pb", 0, buf, 10) ;
if (buf [0] == 'I' && buf [1] == 'D' && buf [2] == '3')
{ int offset = buf [6] & 0x7f ;
offset = (offset << 7) | (buf [7] & 0x7f) ;
offset = (offset << 7) | (buf [8] & 0x7f) ;
offset = (offset << 7) | (buf [9] & 0x7f) ;
psf_log_printf (psf, "ID3 length : %d\n--------------------\n", offset) ;
/* Never want to jump backwards in a file. */
if (offset < 0)
return 0 ;
/* Calculate new file offset and position ourselves there. */
psf->fileoffset += offset + 10 ;
psf_binheader_readf (psf, "p", psf->fileoffset) ;
return 1 ;
} ;
return 0 ;
} /* id3_skip */
Commit Message: src/id3.c : Improve error handling
CWE ID: CWE-119 | id3_skip (SF_PRIVATE * psf)
{ unsigned char buf [10] ;
memset (buf, 0, sizeof (buf)) ;
psf_binheader_readf (psf, "pb", 0, buf, 10) ;
if (buf [0] == 'I' && buf [1] == 'D' && buf [2] == '3')
{ int offset = buf [6] & 0x7f ;
offset = (offset << 7) | (buf [7] & 0x7f) ;
offset = (offset << 7) | (buf [8] & 0x7f) ;
offset = (offset << 7) | (buf [9] & 0x7f) ;
psf_log_printf (psf, "ID3 length : %d\n--------------------\n", offset) ;
/* Never want to jump backwards in a file. */
if (offset < 0)
return 0 ;
/* Calculate new file offset and position ourselves there. */
psf->fileoffset += offset + 10 ;
if (psf->fileoffset < psf->filelength)
{ psf_binheader_readf (psf, "p", psf->fileoffset) ;
return 1 ;
} ;
} ;
return 0 ;
} /* id3_skip */
| 168,259 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PHP_FUNCTION(gzopen)
{
char *filename;
char *mode;
int filename_len, mode_len;
int flags = REPORT_ERRORS;
php_stream *stream;
long use_include_path = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", &filename, &filename_len, &mode, &mode_len, &use_include_path) == FAILURE) {
return;
}
if (use_include_path) {
flags |= USE_PATH;
}
stream = php_stream_gzopen(NULL, filename, mode, flags, NULL, NULL STREAMS_CC TSRMLS_CC);
if (!stream) {
RETURN_FALSE;
}
php_stream_to_zval(stream, return_value);
}
Commit Message:
CWE ID: CWE-254 | static PHP_FUNCTION(gzopen)
{
char *filename;
char *mode;
int filename_len, mode_len;
int flags = REPORT_ERRORS;
php_stream *stream;
long use_include_path = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ps|l", &filename, &filename_len, &mode, &mode_len, &use_include_path) == FAILURE) {
return;
}
if (use_include_path) {
flags |= USE_PATH;
}
stream = php_stream_gzopen(NULL, filename, mode, flags, NULL, NULL STREAMS_CC TSRMLS_CC);
if (!stream) {
RETURN_FALSE;
}
php_stream_to_zval(stream, return_value);
}
| 165,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: int prepare_binprm(struct linux_binprm *bprm)
{
struct inode *inode = file_inode(bprm->file);
umode_t mode = inode->i_mode;
int retval;
/* clear any previous set[ug]id data from a previous binary */
bprm->cred->euid = current_euid();
bprm->cred->egid = current_egid();
if (!(bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID) &&
!task_no_new_privs(current) &&
kuid_has_mapping(bprm->cred->user_ns, inode->i_uid) &&
kgid_has_mapping(bprm->cred->user_ns, inode->i_gid)) {
/* Set-uid? */
if (mode & S_ISUID) {
bprm->per_clear |= PER_CLEAR_ON_SETID;
bprm->cred->euid = inode->i_uid;
}
/* Set-gid? */
/*
* If setgid is set but no group execute bit then this
* is a candidate for mandatory locking, not a setgid
* executable.
*/
if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
bprm->per_clear |= PER_CLEAR_ON_SETID;
bprm->cred->egid = inode->i_gid;
}
}
/* fill in binprm security blob */
retval = security_bprm_set_creds(bprm);
if (retval)
return retval;
bprm->cred_prepared = 1;
memset(bprm->buf, 0, BINPRM_BUF_SIZE);
return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE);
}
Commit Message: fs: take i_mutex during prepare_binprm for set[ug]id executables
This prevents a race between chown() and execve(), where chowning a
setuid-user binary to root would momentarily make the binary setuid
root.
This patch was mostly written by Linus Torvalds.
Signed-off-by: Jann Horn <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362 | int prepare_binprm(struct linux_binprm *bprm)
{
int retval;
bprm_fill_uid(bprm);
/* fill in binprm security blob */
retval = security_bprm_set_creds(bprm);
if (retval)
return retval;
bprm->cred_prepared = 1;
memset(bprm->buf, 0, BINPRM_BUF_SIZE);
return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE);
}
| 166,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: void fslib_copy_libs(const char *full_path) {
assert(full_path);
if (arg_debug || arg_debug_private_lib)
printf(" fslib_copy_libs %s\n", full_path);
if (access(full_path, R_OK)) {
if (arg_debug || arg_debug_private_lib)
printf("cannot find %s for private-lib, skipping...\n", full_path);
return;
}
unlink(RUN_LIB_FILE); // in case is there
create_empty_file_as_root(RUN_LIB_FILE, 0644);
if (chown(RUN_LIB_FILE, getuid(), getgid()))
errExit("chown");
if (arg_debug || arg_debug_private_lib)
printf(" running fldd %s\n", full_path);
sbox_run(SBOX_USER | SBOX_SECCOMP | SBOX_CAPS_NONE, 3, PATH_FLDD, full_path, RUN_LIB_FILE);
FILE *fp = fopen(RUN_LIB_FILE, "r");
if (!fp)
errExit("fopen");
char buf[MAXBUF];
while (fgets(buf, MAXBUF, fp)) {
char *ptr = strchr(buf, '\n');
if (ptr)
*ptr = '\0';
fslib_duplicate(buf);
}
fclose(fp);
}
Commit Message: mount runtime seccomp files read-only (#2602)
avoid creating locations in the file system that are both writable and
executable (in this case for processes with euid of the user).
for the same reason also remove user owned libfiles
when it is not needed any more
CWE ID: CWE-284 | void fslib_copy_libs(const char *full_path) {
assert(full_path);
if (arg_debug || arg_debug_private_lib)
printf(" fslib_copy_libs %s\n", full_path);
if (access(full_path, R_OK)) {
if (arg_debug || arg_debug_private_lib)
printf("cannot find %s for private-lib, skipping...\n", full_path);
return;
}
unlink(RUN_LIB_FILE); // in case is there
create_empty_file_as_root(RUN_LIB_FILE, 0644);
if (chown(RUN_LIB_FILE, getuid(), getgid()))
errExit("chown");
if (arg_debug || arg_debug_private_lib)
printf(" running fldd %s\n", full_path);
sbox_run(SBOX_USER | SBOX_SECCOMP | SBOX_CAPS_NONE, 3, PATH_FLDD, full_path, RUN_LIB_FILE);
FILE *fp = fopen(RUN_LIB_FILE, "r");
if (!fp)
errExit("fopen");
char buf[MAXBUF];
while (fgets(buf, MAXBUF, fp)) {
char *ptr = strchr(buf, '\n');
if (ptr)
*ptr = '\0';
fslib_duplicate(buf);
}
fclose(fp);
unlink(RUN_LIB_FILE);
}
| 169,657 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 git_pkt_parse_line(
git_pkt **head, const char *line, const char **out, size_t bufflen)
{
int ret;
int32_t len;
/* Not even enough for the length */
if (bufflen > 0 && bufflen < PKT_LEN_SIZE)
return GIT_EBUFS;
len = parse_len(line);
if (len < 0) {
/*
* If we fail to parse the length, it might be because the
* server is trying to send us the packfile already.
*/
if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) {
giterr_clear();
*out = line;
return pack_pkt(head);
}
return (int)len;
}
/*
* If we were given a buffer length, then make sure there is
* enough in the buffer to satisfy this line
*/
if (bufflen > 0 && bufflen < (size_t)len)
return GIT_EBUFS;
/*
* The length has to be exactly 0 in case of a flush
* packet or greater than PKT_LEN_SIZE, as the decoded
* length includes its own encoded length of four bytes.
*/
if (len != 0 && len < PKT_LEN_SIZE)
return GIT_ERROR;
line += PKT_LEN_SIZE;
/*
* TODO: How do we deal with empty lines? Try again? with the next
* line?
*/
if (len == PKT_LEN_SIZE) {
*head = NULL;
*out = line;
return 0;
}
if (len == 0) { /* Flush pkt */
*out = line;
return flush_pkt(head);
}
len -= PKT_LEN_SIZE; /* the encoded length includes its own size */
if (*line == GIT_SIDE_BAND_DATA)
ret = data_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_PROGRESS)
ret = sideband_progress_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_ERROR)
ret = sideband_error_pkt(head, line, len);
else if (!git__prefixcmp(line, "ACK"))
ret = ack_pkt(head, line, len);
else if (!git__prefixcmp(line, "NAK"))
ret = nak_pkt(head);
else if (!git__prefixcmp(line, "ERR "))
ret = err_pkt(head, line, len);
else if (*line == '#')
ret = comment_pkt(head, line, len);
else if (!git__prefixcmp(line, "ok"))
ret = ok_pkt(head, line, len);
else if (!git__prefixcmp(line, "ng"))
ret = ng_pkt(head, line, len);
else if (!git__prefixcmp(line, "unpack"))
ret = unpack_pkt(head, line, len);
else
ret = ref_pkt(head, line, len);
*out = line + len;
return ret;
}
Commit Message: smart_pkt: treat empty packet lines as error
The Git protocol does not specify what should happen in the case
of an empty packet line (that is a packet line "0004"). We
currently indicate success, but do not return a packet in the
case where we hit an empty line. The smart protocol was not
prepared to handle such packets in all cases, though, resulting
in a `NULL` pointer dereference.
Fix the issue by returning an error instead. As such kind of
packets is not even specified by upstream, this is the right
thing to do.
CWE ID: CWE-476 | int git_pkt_parse_line(
git_pkt **head, const char *line, const char **out, size_t bufflen)
{
int ret;
int32_t len;
/* Not even enough for the length */
if (bufflen > 0 && bufflen < PKT_LEN_SIZE)
return GIT_EBUFS;
len = parse_len(line);
if (len < 0) {
/*
* If we fail to parse the length, it might be because the
* server is trying to send us the packfile already.
*/
if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) {
giterr_clear();
*out = line;
return pack_pkt(head);
}
return (int)len;
}
/*
* If we were given a buffer length, then make sure there is
* enough in the buffer to satisfy this line
*/
if (bufflen > 0 && bufflen < (size_t)len)
return GIT_EBUFS;
/*
* The length has to be exactly 0 in case of a flush
* packet or greater than PKT_LEN_SIZE, as the decoded
* length includes its own encoded length of four bytes.
*/
if (len != 0 && len < PKT_LEN_SIZE)
return GIT_ERROR;
line += PKT_LEN_SIZE;
/*
* The Git protocol does not specify empty lines as part
* of the protocol. Not knowing what to do with an empty
* line, we should return an error upon hitting one.
*/
if (len == PKT_LEN_SIZE) {
giterr_set_str(GITERR_NET, "Invalid empty packet");
return GIT_ERROR;
}
if (len == 0) { /* Flush pkt */
*out = line;
return flush_pkt(head);
}
len -= PKT_LEN_SIZE; /* the encoded length includes its own size */
if (*line == GIT_SIDE_BAND_DATA)
ret = data_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_PROGRESS)
ret = sideband_progress_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_ERROR)
ret = sideband_error_pkt(head, line, len);
else if (!git__prefixcmp(line, "ACK"))
ret = ack_pkt(head, line, len);
else if (!git__prefixcmp(line, "NAK"))
ret = nak_pkt(head);
else if (!git__prefixcmp(line, "ERR "))
ret = err_pkt(head, line, len);
else if (*line == '#')
ret = comment_pkt(head, line, len);
else if (!git__prefixcmp(line, "ok"))
ret = ok_pkt(head, line, len);
else if (!git__prefixcmp(line, "ng"))
ret = ng_pkt(head, line, len);
else if (!git__prefixcmp(line, "unpack"))
ret = unpack_pkt(head, line, len);
else
ret = ref_pkt(head, line, len);
*out = line + len;
return ret;
}
| 168,527 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GLboolean WebGLRenderingContextBase::isFramebuffer(
WebGLFramebuffer* framebuffer) {
if (!framebuffer || isContextLost())
return 0;
if (!framebuffer->HasEverBeenBound())
return 0;
if (framebuffer->IsDeleted())
return 0;
return ContextGL()->IsFramebuffer(framebuffer->Object());
}
Commit Message: Validate all incoming WebGLObjects.
A few entry points were missing the correct validation.
Tested with improved conformance tests in
https://github.com/KhronosGroup/WebGL/pull/2654 .
Bug: 848914
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008
Reviewed-on: https://chromium-review.googlesource.com/1086718
Reviewed-by: Kai Ninomiya <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Commit-Queue: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565016}
CWE ID: CWE-119 | GLboolean WebGLRenderingContextBase::isFramebuffer(
WebGLFramebuffer* framebuffer) {
if (!framebuffer || isContextLost() ||
!framebuffer->Validate(ContextGroup(), this))
return 0;
if (!framebuffer->HasEverBeenBound())
return 0;
if (framebuffer->IsDeleted())
return 0;
return ContextGL()->IsFramebuffer(framebuffer->Object());
}
| 173,129 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType Get8BIMProperty(const Image *image,const char *key,
ExceptionInfo *exception)
{
char
*attribute,
format[MagickPathExtent],
name[MagickPathExtent],
*resource;
const StringInfo
*profile;
const unsigned char
*info;
long
start,
stop;
MagickBooleanType
status;
register ssize_t
i;
size_t
length;
ssize_t
count,
id,
sub_number;
/*
There are no newlines in path names, so it's safe as terminator.
*/
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
count=(ssize_t) sscanf(key,"8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]",&start,&stop,
name,format);
if ((count != 2) && (count != 3) && (count != 4))
return(MagickFalse);
if (count < 4)
(void) CopyMagickString(format,"SVG",MagickPathExtent);
if (count < 3)
*name='\0';
sub_number=1;
if (*name == '#')
sub_number=(ssize_t) StringToLong(&name[1]);
sub_number=MagickMax(sub_number,1L);
resource=(char *) NULL;
status=MagickFalse;
length=GetStringInfoLength(profile);
info=GetStringInfoDatum(profile);
while ((length > 0) && (status == MagickFalse))
{
if (ReadPropertyByte(&info,&length) != (unsigned char) '8')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'B')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'I')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'M')
continue;
id=(ssize_t) ReadPropertyMSBShort(&info,&length);
if (id < (ssize_t) start)
continue;
if (id > (ssize_t) stop)
continue;
if (resource != (char *) NULL)
resource=DestroyString(resource);
count=(ssize_t) ReadPropertyByte(&info,&length);
if ((count != 0) && ((size_t) count <= length))
{
resource=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
resource=(char *) AcquireQuantumMemory((size_t) count+
MagickPathExtent,sizeof(*resource));
if (resource != (char *) NULL)
{
for (i=0; i < (ssize_t) count; i++)
resource[i]=(char) ReadPropertyByte(&info,&length);
resource[count]='\0';
}
}
if ((count & 0x01) == 0)
(void) ReadPropertyByte(&info,&length);
count=(ssize_t) ReadPropertyMSBLong(&info,&length);
if ((*name != '\0') && (*name != '#'))
if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0))
{
/*
No name match, scroll forward and try next.
*/
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
if ((*name == '#') && (sub_number != 1))
{
/*
No numbered match, scroll forward and try next.
*/
sub_number--;
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
/*
We have the resource of interest.
*/
attribute=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent,
sizeof(*attribute));
if (attribute != (char *) NULL)
{
(void) CopyMagickMemory(attribute,(char *) info,(size_t) count);
attribute[count]='\0';
info+=count;
length-=MagickMin(count,(ssize_t) length);
if ((id <= 1999) || (id >= 2999))
(void) SetImageProperty((Image *) image,key,(const char *)
attribute,exception);
else
{
char
*path;
if (LocaleCompare(format,"svg") == 0)
path=TraceSVGClippath((unsigned char *) attribute,(size_t) count,
image->columns,image->rows);
else
path=TracePSClippath((unsigned char *) attribute,(size_t) count);
(void) SetImageProperty((Image *) image,key,(const char *) path,
exception);
path=DestroyString(path);
}
attribute=DestroyString(attribute);
status=MagickTrue;
}
}
if (resource != (char *) NULL)
resource=DestroyString(resource);
return(status);
}
Commit Message: Prevent buffer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static MagickBooleanType Get8BIMProperty(const Image *image,const char *key,
ExceptionInfo *exception)
{
char
*attribute,
format[MagickPathExtent],
name[MagickPathExtent],
*resource;
const StringInfo
*profile;
const unsigned char
*info;
long
start,
stop;
MagickBooleanType
status;
register ssize_t
i;
size_t
length;
ssize_t
count,
id,
sub_number;
/*
There are no newlines in path names, so it's safe as terminator.
*/
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
count=(ssize_t) sscanf(key,"8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]",&start,&stop,
name,format);
if ((count != 2) && (count != 3) && (count != 4))
return(MagickFalse);
if (count < 4)
(void) CopyMagickString(format,"SVG",MagickPathExtent);
if (count < 3)
*name='\0';
sub_number=1;
if (*name == '#')
sub_number=(ssize_t) StringToLong(&name[1]);
sub_number=MagickMax(sub_number,1L);
resource=(char *) NULL;
status=MagickFalse;
length=GetStringInfoLength(profile);
info=GetStringInfoDatum(profile);
while ((length > 0) && (status == MagickFalse))
{
if (ReadPropertyByte(&info,&length) != (unsigned char) '8')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'B')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'I')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'M')
continue;
id=(ssize_t) ReadPropertyMSBShort(&info,&length);
if (id < (ssize_t) start)
continue;
if (id > (ssize_t) stop)
continue;
if (resource != (char *) NULL)
resource=DestroyString(resource);
count=(ssize_t) ReadPropertyByte(&info,&length);
if ((count != 0) && ((size_t) count <= length))
{
resource=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
resource=(char *) AcquireQuantumMemory((size_t) count+
MagickPathExtent,sizeof(*resource));
if (resource != (char *) NULL)
{
for (i=0; i < (ssize_t) count; i++)
resource[i]=(char) ReadPropertyByte(&info,&length);
resource[count]='\0';
}
}
if ((count & 0x01) == 0)
(void) ReadPropertyByte(&info,&length);
count=(ssize_t) ReadPropertyMSBLong(&info,&length);
if ((count < 0) || ((size_t) count > length))
{
length=0;
continue;
}
if ((*name != '\0') && (*name != '#'))
if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0))
{
/*
No name match, scroll forward and try next.
*/
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
if ((*name == '#') && (sub_number != 1))
{
/*
No numbered match, scroll forward and try next.
*/
sub_number--;
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
/*
We have the resource of interest.
*/
attribute=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent,
sizeof(*attribute));
if (attribute != (char *) NULL)
{
(void) CopyMagickMemory(attribute,(char *) info,(size_t) count);
attribute[count]='\0';
info+=count;
length-=MagickMin(count,(ssize_t) length);
if ((id <= 1999) || (id >= 2999))
(void) SetImageProperty((Image *) image,key,(const char *)
attribute,exception);
else
{
char
*path;
if (LocaleCompare(format,"svg") == 0)
path=TraceSVGClippath((unsigned char *) attribute,(size_t) count,
image->columns,image->rows);
else
path=TracePSClippath((unsigned char *) attribute,(size_t) count);
(void) SetImageProperty((Image *) image,key,(const char *) path,
exception);
path=DestroyString(path);
}
attribute=DestroyString(attribute);
status=MagickTrue;
}
}
if (resource != (char *) NULL)
resource=DestroyString(resource);
return(status);
}
| 166,999 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 queue_push(register Queue *qp, size_t extra_length, char const *info)
{
register char *cp;
size_t memory_length;
size_t available_length;
size_t begin_length;
size_t n_begin;
size_t q_length;
if (!extra_length)
return;
memory_length = qp->d_memory_end - qp->d_memory;
q_length =
qp->d_read <= qp->d_write ?
(size_t)(qp->d_write - qp->d_read)
:
memory_length - (qp->d_read - qp->d_write);
available_length = memory_length - q_length - 1;
/* -1, as the Q cannot completely fill up all */
/* available memory in the buffer */
if (message_show(MSG_INFO))
message("push_front %u bytes in `%s'", (unsigned)extra_length, info);
if (extra_length > available_length)
{
/* enlarge the buffer: */
memory_length += extra_length - available_length + BLOCK_QUEUE;
cp = new_memory(memory_length, sizeof(char));
if (message_show(MSG_INFO))
message("Reallocating queue at %p to %p", qp->d_memory, cp);
if (qp->d_read > qp->d_write) /* q wraps around end */
{
size_t tail_len = qp->d_memory_end - qp->d_read;
memcpy(cp, qp->d_read, tail_len); /* first part -> begin */
/* 2nd part beyond */
memcpy(cp + tail_len, qp->d_memory,
(size_t)(qp->d_write - qp->d_memory));
qp->d_write = cp + q_length;
qp->d_read = cp;
}
else /* q as one block */
{
memcpy(cp, qp->d_memory, memory_length);/* cp existing buffer */
qp->d_read = cp + (qp->d_read - qp->d_memory);
qp->d_write = cp + (qp->d_write - qp->d_memory);
}
free(qp->d_memory); /* free old memory */
qp->d_memory_end = cp + memory_length; /* update d_memory_end */
qp->d_memory = cp; /* update d_memory */
}
/*
Write as much as possible at the begin of the buffer, then write
the remaining chars at the end.
q_length is increased by the length of the info string
The first chars to write are at the end of info, and the 2nd part to
write are the initial chars of info, since the initial part of info
is then read first.
*/
/* # chars available at the */
begin_length = qp->d_read - qp->d_memory; /* begin of the buffer */
n_begin = extra_length <= begin_length ? /* determine # to write at */
extra_length /* the begin of the buffer */
:
begin_length;
memcpy /* write trailing part of */
( /* info first */
qp->d_read -= n_begin,
info + extra_length - n_begin,
n_begin
);
if (extra_length > begin_length) /* not yet all chars written*/
{
/* continue with the remaining number of characters. Insert these at*/
/* the end of the buffer */
extra_length -= begin_length; /* reduce # to write */
memcpy /* d_read wraps to the end */
( /* write info's rest */
qp->d_read = qp->d_memory_end - extra_length,
info,
extra_length
);
}
}
Commit Message: fixed invalid memory reads detected by the address sanitizer
CWE ID: CWE-119 | void queue_push(register Queue *qp, size_t extra_length, char const *info)
{
register char *cp;
size_t memory_length;
size_t available_length;
size_t begin_length;
size_t n_begin;
size_t q_length;
if (!extra_length)
return;
memory_length = qp->d_memory_end - qp->d_memory;
q_length =
qp->d_read <= qp->d_write ?
(size_t)(qp->d_write - qp->d_read)
:
memory_length - (qp->d_read - qp->d_write);
available_length = memory_length - q_length - 1;
/* -1, as the Q cannot completely fill up all */
/* available memory in the buffer */
if (message_show(MSG_INFO))
message("push_front %u bytes in `%s'", (unsigned)extra_length, info);
if (extra_length > available_length)
{
size_t original_length = memory_length;
/* enlarge the buffer: */
memory_length += extra_length - available_length + BLOCK_QUEUE;
cp = new_memory(memory_length, sizeof(char));
if (message_show(MSG_INFO))
message("Reallocating queue at %p to %p", qp->d_memory, cp);
if (qp->d_read > qp->d_write) /* q wraps around end */
{
size_t tail_len = qp->d_memory_end - qp->d_read;
memcpy(cp, qp->d_read, tail_len); /* first part -> begin */
/* 2nd part beyond */
memcpy(cp + tail_len, qp->d_memory,
(size_t)(qp->d_write - qp->d_memory));
qp->d_write = cp + q_length;
qp->d_read = cp;
}
else /* q as one block */
{
memcpy(cp, qp->d_memory, original_length);/* cp existing buffer */
qp->d_read = cp + (qp->d_read - qp->d_memory);
qp->d_write = cp + (qp->d_write - qp->d_memory);
}
free(qp->d_memory); /* free old memory */
qp->d_memory_end = cp + memory_length; /* update d_memory_end */
qp->d_memory = cp; /* update d_memory */
}
/*
Write as much as possible at the begin of the buffer, then write
the remaining chars at the end.
q_length is increased by the length of the info string
The first chars to write are at the end of info, and the 2nd part to
write are the initial chars of info, since the initial part of info
is then read first.
*/
/* # chars available at the */
begin_length = qp->d_read - qp->d_memory; /* begin of the buffer */
n_begin = extra_length <= begin_length ? /* determine # to write at */
extra_length /* the begin of the buffer */
:
begin_length;
memcpy /* write trailing part of */
( /* info first */
qp->d_read -= n_begin,
info + extra_length - n_begin,
n_begin
);
if (extra_length > begin_length) /* not yet all chars written*/
{
/* continue with the remaining number of characters. Insert these at*/
/* the end of the buffer */
extra_length -= begin_length; /* reduce # to write */
memcpy /* d_read wraps to the end */
( /* write info's rest */
qp->d_read = qp->d_memory_end - extra_length,
info,
extra_length
);
}
}
| 168,459 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: hstoreArrayToPairs(ArrayType *a, int *npairs)
{
Datum *key_datums;
bool *key_nulls;
int key_count;
Pairs *key_pairs;
int bufsiz;
int i,
j;
deconstruct_array(a,
TEXTOID, -1, false, 'i',
&key_datums, &key_nulls, &key_count);
if (key_count == 0)
{
*npairs = 0;
return NULL;
}
key_pairs = palloc(sizeof(Pairs) * key_count);
for (i = 0, j = 0; i < key_count; i++)
{
if (!key_nulls[i])
{
key_pairs[j].key = VARDATA(key_datums[i]);
key_pairs[j].keylen = VARSIZE(key_datums[i]) - VARHDRSZ;
key_pairs[j].val = NULL;
key_pairs[j].vallen = 0;
key_pairs[j].needfree = 0;
key_pairs[j].isnull = 1;
j++;
}
}
*npairs = hstoreUniquePairs(key_pairs, j, &bufsiz);
return key_pairs;
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | hstoreArrayToPairs(ArrayType *a, int *npairs)
{
Datum *key_datums;
bool *key_nulls;
int key_count;
Pairs *key_pairs;
int bufsiz;
int i,
j;
deconstruct_array(a,
TEXTOID, -1, false, 'i',
&key_datums, &key_nulls, &key_count);
if (key_count == 0)
{
*npairs = 0;
return NULL;
}
/*
* A text array uses at least eight bytes per element, so any overflow in
* "key_count * sizeof(Pairs)" is small enough for palloc() to catch.
* However, credible improvements to the array format could invalidate
* that assumption. Therefore, use an explicit check rather than relying
* on palloc() to complain.
*/
if (key_count > MaxAllocSize / sizeof(Pairs))
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("number of pairs (%d) exceeds the maximum allowed (%d)",
key_count, (int) (MaxAllocSize / sizeof(Pairs)))));
key_pairs = palloc(sizeof(Pairs) * key_count);
for (i = 0, j = 0; i < key_count; i++)
{
if (!key_nulls[i])
{
key_pairs[j].key = VARDATA(key_datums[i]);
key_pairs[j].keylen = VARSIZE(key_datums[i]) - VARHDRSZ;
key_pairs[j].val = NULL;
key_pairs[j].vallen = 0;
key_pairs[j].needfree = 0;
key_pairs[j].isnull = 1;
j++;
}
}
*npairs = hstoreUniquePairs(key_pairs, j, &bufsiz);
return key_pairs;
}
| 166,400 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static long ion_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct ion_client *client = filp->private_data;
struct ion_device *dev = client->dev;
struct ion_handle *cleanup_handle = NULL;
int ret = 0;
unsigned int dir;
union {
struct ion_fd_data fd;
struct ion_allocation_data allocation;
struct ion_handle_data handle;
struct ion_custom_data custom;
} data;
dir = ion_ioctl_dir(cmd);
if (_IOC_SIZE(cmd) > sizeof(data))
return -EINVAL;
if (dir & _IOC_WRITE)
if (copy_from_user(&data, (void __user *)arg, _IOC_SIZE(cmd)))
return -EFAULT;
switch (cmd) {
case ION_IOC_ALLOC:
{
struct ion_handle *handle;
handle = ion_alloc(client, data.allocation.len,
data.allocation.align,
data.allocation.heap_id_mask,
data.allocation.flags);
if (IS_ERR(handle))
return PTR_ERR(handle);
data.allocation.handle = handle->id;
cleanup_handle = handle;
break;
}
case ION_IOC_FREE:
{
struct ion_handle *handle;
handle = ion_handle_get_by_id(client, data.handle.handle);
if (IS_ERR(handle))
return PTR_ERR(handle);
ion_free(client, handle);
ion_handle_put(handle);
break;
}
case ION_IOC_SHARE:
case ION_IOC_MAP:
{
struct ion_handle *handle;
handle = ion_handle_get_by_id(client, data.handle.handle);
if (IS_ERR(handle))
return PTR_ERR(handle);
data.fd.fd = ion_share_dma_buf_fd(client, handle);
ion_handle_put(handle);
if (data.fd.fd < 0)
ret = data.fd.fd;
break;
}
case ION_IOC_IMPORT:
{
struct ion_handle *handle;
handle = ion_import_dma_buf_fd(client, data.fd.fd);
if (IS_ERR(handle))
ret = PTR_ERR(handle);
else
data.handle.handle = handle->id;
break;
}
case ION_IOC_SYNC:
{
ret = ion_sync_for_device(client, data.fd.fd);
break;
}
case ION_IOC_CUSTOM:
{
if (!dev->custom_ioctl)
return -ENOTTY;
ret = dev->custom_ioctl(client, data.custom.cmd,
data.custom.arg);
break;
}
default:
return -ENOTTY;
}
if (dir & _IOC_READ) {
if (copy_to_user((void __user *)arg, &data, _IOC_SIZE(cmd))) {
if (cleanup_handle)
ion_free(client, cleanup_handle);
return -EFAULT;
}
}
return ret;
}
Commit Message: staging/android/ion : fix a race condition in the ion driver
There is a use-after-free problem in the ion driver.
This is caused by a race condition in the ion_ioctl()
function.
A handle has ref count of 1 and two tasks on different
cpus calls ION_IOC_FREE simultaneously.
cpu 0 cpu 1
-------------------------------------------------------
ion_handle_get_by_id()
(ref == 2)
ion_handle_get_by_id()
(ref == 3)
ion_free()
(ref == 2)
ion_handle_put()
(ref == 1)
ion_free()
(ref == 0 so ion_handle_destroy() is
called
and the handle is freed.)
ion_handle_put() is called and it
decreases the slub's next free pointer
The problem is detected as an unaligned access in the
spin lock functions since it uses load exclusive
instruction. In some cases it corrupts the slub's
free pointer which causes a mis-aligned access to the
next free pointer.(kmalloc returns a pointer like
ffffc0745b4580aa). And it causes lots of other
hard-to-debug problems.
This symptom is caused since the first member in the
ion_handle structure is the reference count and the
ion driver decrements the reference after it has been
freed.
To fix this problem client->lock mutex is extended
to protect all the codes that uses the handle.
Signed-off-by: Eun Taik Lee <[email protected]>
Reviewed-by: Laura Abbott <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-416 | static long ion_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct ion_client *client = filp->private_data;
struct ion_device *dev = client->dev;
struct ion_handle *cleanup_handle = NULL;
int ret = 0;
unsigned int dir;
union {
struct ion_fd_data fd;
struct ion_allocation_data allocation;
struct ion_handle_data handle;
struct ion_custom_data custom;
} data;
dir = ion_ioctl_dir(cmd);
if (_IOC_SIZE(cmd) > sizeof(data))
return -EINVAL;
if (dir & _IOC_WRITE)
if (copy_from_user(&data, (void __user *)arg, _IOC_SIZE(cmd)))
return -EFAULT;
switch (cmd) {
case ION_IOC_ALLOC:
{
struct ion_handle *handle;
handle = ion_alloc(client, data.allocation.len,
data.allocation.align,
data.allocation.heap_id_mask,
data.allocation.flags);
if (IS_ERR(handle))
return PTR_ERR(handle);
data.allocation.handle = handle->id;
cleanup_handle = handle;
break;
}
case ION_IOC_FREE:
{
struct ion_handle *handle;
mutex_lock(&client->lock);
handle = ion_handle_get_by_id_nolock(client, data.handle.handle);
if (IS_ERR(handle)) {
mutex_unlock(&client->lock);
return PTR_ERR(handle);
}
ion_free_nolock(client, handle);
ion_handle_put_nolock(handle);
mutex_unlock(&client->lock);
break;
}
case ION_IOC_SHARE:
case ION_IOC_MAP:
{
struct ion_handle *handle;
handle = ion_handle_get_by_id(client, data.handle.handle);
if (IS_ERR(handle))
return PTR_ERR(handle);
data.fd.fd = ion_share_dma_buf_fd(client, handle);
ion_handle_put(handle);
if (data.fd.fd < 0)
ret = data.fd.fd;
break;
}
case ION_IOC_IMPORT:
{
struct ion_handle *handle;
handle = ion_import_dma_buf_fd(client, data.fd.fd);
if (IS_ERR(handle))
ret = PTR_ERR(handle);
else
data.handle.handle = handle->id;
break;
}
case ION_IOC_SYNC:
{
ret = ion_sync_for_device(client, data.fd.fd);
break;
}
case ION_IOC_CUSTOM:
{
if (!dev->custom_ioctl)
return -ENOTTY;
ret = dev->custom_ioctl(client, data.custom.cmd,
data.custom.arg);
break;
}
default:
return -ENOTTY;
}
if (dir & _IOC_READ) {
if (copy_to_user((void __user *)arg, &data, _IOC_SIZE(cmd))) {
if (cleanup_handle)
ion_free(client, cleanup_handle);
return -EFAULT;
}
}
return ret;
}
| 166,899 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void tokenadd(struct jv_parser* p, char c) {
assert(p->tokenpos <= p->tokenlen);
if (p->tokenpos == p->tokenlen) {
p->tokenlen = p->tokenlen*2 + 256;
p->tokenbuf = jv_mem_realloc(p->tokenbuf, p->tokenlen);
}
assert(p->tokenpos < p->tokenlen);
p->tokenbuf[p->tokenpos++] = c;
}
Commit Message: Heap buffer overflow in tokenadd() (fix #105)
This was an off-by one: the NUL terminator byte was not allocated on
resize. This was triggered by JSON-encoded numbers longer than 256
bytes.
CWE ID: CWE-119 | static void tokenadd(struct jv_parser* p, char c) {
assert(p->tokenpos <= p->tokenlen);
if (p->tokenpos >= (p->tokenlen - 1)) {
p->tokenlen = p->tokenlen*2 + 256;
p->tokenbuf = jv_mem_realloc(p->tokenbuf, p->tokenlen);
}
assert(p->tokenpos < p->tokenlen);
p->tokenbuf[p->tokenpos++] = c;
}
| 167,477 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintWebViewHelper::OnPrintForPrintPreview(
const base::DictionaryValue& job_settings) {
if (prep_frame_view_)
return;
if (!render_view()->GetWebView())
return;
blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame();
if (!main_frame)
return;
blink::WebDocument document = main_frame->document();
blink::WebElement pdf_element = document.getElementById("pdf-viewer");
if (pdf_element.isNull()) {
NOTREACHED();
return;
}
blink::WebLocalFrame* plugin_frame = pdf_element.document().frame();
blink::WebElement plugin_element = pdf_element;
if (pdf_element.hasHTMLTagName("iframe")) {
plugin_frame = blink::WebLocalFrame::fromFrameOwnerElement(pdf_element);
plugin_element = delegate_->GetPdfElement(plugin_frame);
if (plugin_element.isNull()) {
NOTREACHED();
return;
}
}
base::AutoReset<bool> set_printing_flag(&print_for_preview_, true);
if (!UpdatePrintSettings(plugin_frame, plugin_element, job_settings)) {
LOG(ERROR) << "UpdatePrintSettings failed";
DidFinishPrinting(FAIL_PRINT);
return;
}
PrintMsg_Print_Params& print_params = print_pages_params_->params;
print_params.printable_area = gfx::Rect(print_params.page_size);
if (!RenderPagesForPrint(plugin_frame, plugin_element)) {
LOG(ERROR) << "RenderPagesForPrint failed";
DidFinishPrinting(FAIL_PRINT);
}
}
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: | void PrintWebViewHelper::OnPrintForPrintPreview(
const base::DictionaryValue& job_settings) {
CHECK_LE(ipc_nesting_level_, 1);
if (prep_frame_view_)
return;
if (!render_view()->GetWebView())
return;
blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame();
if (!main_frame)
return;
blink::WebDocument document = main_frame->document();
blink::WebElement pdf_element = document.getElementById("pdf-viewer");
if (pdf_element.isNull()) {
NOTREACHED();
return;
}
blink::WebLocalFrame* plugin_frame = pdf_element.document().frame();
blink::WebElement plugin_element = pdf_element;
if (pdf_element.hasHTMLTagName("iframe")) {
plugin_frame = blink::WebLocalFrame::fromFrameOwnerElement(pdf_element);
plugin_element = delegate_->GetPdfElement(plugin_frame);
if (plugin_element.isNull()) {
NOTREACHED();
return;
}
}
base::AutoReset<bool> set_printing_flag(&print_for_preview_, true);
if (!UpdatePrintSettings(plugin_frame, plugin_element, job_settings)) {
LOG(ERROR) << "UpdatePrintSettings failed";
DidFinishPrinting(FAIL_PRINT);
return;
}
PrintMsg_Print_Params& print_params = print_pages_params_->params;
print_params.printable_area = gfx::Rect(print_params.page_size);
if (!RenderPagesForPrint(plugin_frame, plugin_element)) {
LOG(ERROR) << "RenderPagesForPrint failed";
DidFinishPrinting(FAIL_PRINT);
}
}
| 171,873 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 br_multicast_del_pg(struct net_bridge *br,
struct net_bridge_port_group *pg)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
mdb = mlock_dereference(br->mdb, br);
mp = br_mdb_ip_get(mdb, &pg->addr);
if (WARN_ON(!mp))
return;
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (p != pg)
continue;
rcu_assign_pointer(*pp, p->next);
hlist_del_init(&p->mglist);
del_timer(&p->timer);
call_rcu_bh(&p->rcu, br_multicast_free_pg);
if (!mp->ports && !mp->mglist &&
netif_running(br->dev))
mod_timer(&mp->timer, jiffies);
return;
}
WARN_ON(1);
}
Commit Message: bridge: fix some kernel warning in multicast timer
Several people reported the warning: "kernel BUG at kernel/timer.c:729!"
and the stack trace is:
#7 [ffff880214d25c10] mod_timer+501 at ffffffff8106d905
#8 [ffff880214d25c50] br_multicast_del_pg.isra.20+261 at ffffffffa0731d25 [bridge]
#9 [ffff880214d25c80] br_multicast_disable_port+88 at ffffffffa0732948 [bridge]
#10 [ffff880214d25cb0] br_stp_disable_port+154 at ffffffffa072bcca [bridge]
#11 [ffff880214d25ce8] br_device_event+520 at ffffffffa072a4e8 [bridge]
#12 [ffff880214d25d18] notifier_call_chain+76 at ffffffff8164aafc
#13 [ffff880214d25d50] raw_notifier_call_chain+22 at ffffffff810858f6
#14 [ffff880214d25d60] call_netdevice_notifiers+45 at ffffffff81536aad
#15 [ffff880214d25d80] dev_close_many+183 at ffffffff81536d17
#16 [ffff880214d25dc0] rollback_registered_many+168 at ffffffff81537f68
#17 [ffff880214d25de8] rollback_registered+49 at ffffffff81538101
#18 [ffff880214d25e10] unregister_netdevice_queue+72 at ffffffff815390d8
#19 [ffff880214d25e30] __tun_detach+272 at ffffffffa074c2f0 [tun]
#20 [ffff880214d25e88] tun_chr_close+45 at ffffffffa074c4bd [tun]
#21 [ffff880214d25ea8] __fput+225 at ffffffff8119b1f1
#22 [ffff880214d25ef0] ____fput+14 at ffffffff8119b3fe
#23 [ffff880214d25f00] task_work_run+159 at ffffffff8107cf7f
#24 [ffff880214d25f30] do_notify_resume+97 at ffffffff810139e1
#25 [ffff880214d25f50] int_signal+18 at ffffffff8164f292
this is due to I forgot to check if mp->timer is armed in
br_multicast_del_pg(). This bug is introduced by
commit 9f00b2e7cf241fa389733d41b6 (bridge: only expire the mdb entry
when query is received).
Same for __br_mdb_del().
Tested-by: poma <[email protected]>
Reported-by: LiYonghua <[email protected]>
Reported-by: Robert Hancock <[email protected]>
Cc: Herbert Xu <[email protected]>
Cc: Stephen Hemminger <[email protected]>
Cc: "David S. Miller" <[email protected]>
Signed-off-by: Cong Wang <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static void br_multicast_del_pg(struct net_bridge *br,
struct net_bridge_port_group *pg)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
mdb = mlock_dereference(br->mdb, br);
mp = br_mdb_ip_get(mdb, &pg->addr);
if (WARN_ON(!mp))
return;
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (p != pg)
continue;
rcu_assign_pointer(*pp, p->next);
hlist_del_init(&p->mglist);
del_timer(&p->timer);
call_rcu_bh(&p->rcu, br_multicast_free_pg);
if (!mp->ports && !mp->mglist && mp->timer_armed &&
netif_running(br->dev))
mod_timer(&mp->timer, jiffies);
return;
}
WARN_ON(1);
}
| 166,019 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void traverse_for_entities(
const char *old,
size_t oldlen,
char *ret, /* should have allocated TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(olden) */
size_t *retlen,
int all,
int flags,
const entity_ht *inv_map,
enum entity_charset charset)
{
const char *p,
*lim;
char *q;
int doctype = flags & ENT_HTML_DOC_TYPE_MASK;
lim = old + oldlen; /* terminator address */
assert(*lim == '\0');
for (p = old, q = ret; p < lim;) {
unsigned code, code2 = 0;
const char *next = NULL; /* when set, next > p, otherwise possible inf loop */
/* Shift JIS, Big5 and HKSCS use multi-byte encodings where an
* ASCII range byte can be part of a multi-byte sequence.
* However, they start at 0x40, therefore if we find a 0x26 byte,
* we're sure it represents the '&' character. */
/* assumes there are no single-char entities */
if (p[0] != '&' || (p + 3 >= lim)) {
*(q++) = *(p++);
continue;
}
/* now p[3] is surely valid and is no terminator */
/* numerical entity */
if (p[1] == '#') {
next = &p[2];
if (process_numeric_entity(&next, &code) == FAILURE)
goto invalid_code;
/* If we're in htmlspecialchars_decode, we're only decoding entities
* that represent &, <, >, " and '. Is this one of them? */
if (!all && (code > 63U ||
stage3_table_be_apos_00000[code].data.ent.entity == NULL))
goto invalid_code;
/* are we allowed to decode this entity in this document type?
* HTML 5 is the only that has a character that cannot be used in
* a numeric entity but is allowed literally (U+000D). The
* unoptimized version would be ... || !numeric_entity_is_allowed(code) */
if (!unicode_cp_is_allowed(code, doctype) ||
(doctype == ENT_HTML_DOC_HTML5 && code == 0x0D))
goto invalid_code;
} else {
const char *start;
size_t ent_len;
next = &p[1];
start = next;
if (process_named_entity_html(&next, &start, &ent_len) == FAILURE)
goto invalid_code;
if (resolve_named_entity_html(start, ent_len, inv_map, &code, &code2) == FAILURE) {
if (doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a'
&& start[1] == 'p' && start[2] == 'o' && start[3] == 's') {
/* uses html4 inv_map, which doesn't include apos;. This is a
* hack to support it */
code = (unsigned) '\'';
} else {
goto invalid_code;
}
}
}
assert(*next == ';');
if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))
/* && code2 == '\0' always true for current maps */)
goto invalid_code;
/* UTF-8 doesn't need mapping (ISO-8859-1 doesn't either, but
* the call is needed to ensure the codepoint <= U+00FF) */
if (charset != cs_utf_8) {
/* replace unicode code point */
if (map_from_unicode(code, charset, &code) == FAILURE || code2 != 0)
goto invalid_code; /* not representable in target charset */
}
q += write_octet_sequence(q, charset, code);
if (code2) {
q += write_octet_sequence(q, charset, code2);
}
/* jump over the valid entity; may go beyond size of buffer; np */
p = next + 1;
continue;
invalid_code:
for (; p < next; p++) {
*(q++) = *p;
}
}
*q = '\0';
*retlen = (size_t)(q - ret);
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190 | static void traverse_for_entities(
const char *old,
size_t oldlen,
char *ret, /* should have allocated TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(olden) */
size_t *retlen,
int all,
int flags,
const entity_ht *inv_map,
enum entity_charset charset)
{
const char *p,
*lim;
char *q;
int doctype = flags & ENT_HTML_DOC_TYPE_MASK;
lim = old + oldlen; /* terminator address */
assert(*lim == '\0');
for (p = old, q = ret; p < lim;) {
unsigned code, code2 = 0;
const char *next = NULL; /* when set, next > p, otherwise possible inf loop */
/* Shift JIS, Big5 and HKSCS use multi-byte encodings where an
* ASCII range byte can be part of a multi-byte sequence.
* However, they start at 0x40, therefore if we find a 0x26 byte,
* we're sure it represents the '&' character. */
/* assumes there are no single-char entities */
if (p[0] != '&' || (p + 3 >= lim)) {
*(q++) = *(p++);
continue;
}
/* now p[3] is surely valid and is no terminator */
/* numerical entity */
if (p[1] == '#') {
next = &p[2];
if (process_numeric_entity(&next, &code) == FAILURE)
goto invalid_code;
/* If we're in htmlspecialchars_decode, we're only decoding entities
* that represent &, <, >, " and '. Is this one of them? */
if (!all && (code > 63U ||
stage3_table_be_apos_00000[code].data.ent.entity == NULL))
goto invalid_code;
/* are we allowed to decode this entity in this document type?
* HTML 5 is the only that has a character that cannot be used in
* a numeric entity but is allowed literally (U+000D). The
* unoptimized version would be ... || !numeric_entity_is_allowed(code) */
if (!unicode_cp_is_allowed(code, doctype) ||
(doctype == ENT_HTML_DOC_HTML5 && code == 0x0D))
goto invalid_code;
} else {
const char *start;
size_t ent_len;
next = &p[1];
start = next;
if (process_named_entity_html(&next, &start, &ent_len) == FAILURE)
goto invalid_code;
if (resolve_named_entity_html(start, ent_len, inv_map, &code, &code2) == FAILURE) {
if (doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a'
&& start[1] == 'p' && start[2] == 'o' && start[3] == 's') {
/* uses html4 inv_map, which doesn't include apos;. This is a
* hack to support it */
code = (unsigned) '\'';
} else {
goto invalid_code;
}
}
}
assert(*next == ';');
if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))
/* && code2 == '\0' always true for current maps */)
goto invalid_code;
/* UTF-8 doesn't need mapping (ISO-8859-1 doesn't either, but
* the call is needed to ensure the codepoint <= U+00FF) */
if (charset != cs_utf_8) {
/* replace unicode code point */
if (map_from_unicode(code, charset, &code) == FAILURE || code2 != 0)
goto invalid_code; /* not representable in target charset */
}
q += write_octet_sequence(q, charset, code);
if (code2) {
q += write_octet_sequence(q, charset, code2);
}
/* jump over the valid entity; may go beyond size of buffer; np */
p = next + 1;
continue;
invalid_code:
for (; p < next; p++) {
*(q++) = *p;
}
}
*q = '\0';
*retlen = (size_t)(q - ret);
}
| 167,178 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DailyDataSavingUpdate(
const char* pref_original, const char* pref_received,
PrefService* pref_service)
: pref_original_(pref_original),
pref_received_(pref_received),
original_update_(pref_service, pref_original_),
received_update_(pref_service, pref_received_) {
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416 | DailyDataSavingUpdate(
const char* pref_original,
const char* pref_received,
PrefService* pref_service)
: original_(pref_original, pref_service),
received_(pref_received, pref_service) {
}
| 171,322 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: scoped_ptr<cc::CompositorFrame> SynchronousCompositorImpl::DemandDrawHw(
gfx::Size surface_size,
const gfx::Transform& transform,
gfx::Rect viewport,
gfx::Rect clip,
gfx::Rect viewport_rect_for_tile_priority,
const gfx::Transform& transform_for_tile_priority) {
DCHECK(CalledOnValidThread());
DCHECK(output_surface_);
DCHECK(begin_frame_source_);
scoped_ptr<cc::CompositorFrame> frame =
output_surface_->DemandDrawHw(surface_size,
transform,
viewport,
clip,
viewport_rect_for_tile_priority,
transform_for_tile_priority);
if (frame.get())
UpdateFrameMetaData(frame->metadata);
return frame.Pass();
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399 | scoped_ptr<cc::CompositorFrame> SynchronousCompositorImpl::DemandDrawHw(
const gfx::Size& surface_size,
const gfx::Transform& transform,
const gfx::Rect& viewport,
const gfx::Rect& clip,
const gfx::Rect& viewport_rect_for_tile_priority,
const gfx::Transform& transform_for_tile_priority) {
DCHECK(CalledOnValidThread());
DCHECK(output_surface_);
DCHECK(begin_frame_source_);
scoped_ptr<cc::CompositorFrame> frame =
output_surface_->DemandDrawHw(surface_size,
transform,
viewport,
clip,
viewport_rect_for_tile_priority,
transform_for_tile_priority);
if (frame.get())
UpdateFrameMetaData(frame->metadata);
return frame.Pass();
}
| 171,619 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ContainerNode::parserInsertBefore(PassRefPtrWillBeRawPtr<Node> newChild, Node& nextChild)
{
ASSERT(newChild);
ASSERT(nextChild.parentNode() == this);
ASSERT(!newChild->isDocumentFragment());
ASSERT(!isHTMLTemplateElement(this));
if (nextChild.previousSibling() == newChild || &nextChild == newChild) // nothing to do
return;
if (!checkParserAcceptChild(*newChild))
return;
RefPtrWillBeRawPtr<Node> protect(this);
while (RefPtrWillBeRawPtr<ContainerNode> parent = newChild->parentNode())
parent->parserRemoveChild(*newChild);
if (document() != newChild->document())
document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION);
{
EventDispatchForbiddenScope assertNoEventDispatch;
ScriptForbiddenScope forbidScript;
treeScope().adoptIfNeeded(*newChild);
insertBeforeCommon(nextChild, *newChild);
newChild->updateAncestorConnectedSubframeCountForInsertion();
ChildListMutationScope(*this).childAdded(*newChild);
}
notifyNodeInserted(*newChild, ChildrenChangeSourceParser);
}
Commit Message: parserInsertBefore: Bail out if the parent no longer contains the child.
nextChild may be removed from the DOM tree during the
|parserRemoveChild(*newChild)| call which triggers unload events of newChild's
descendant iframes. In order to maintain the integrity of the DOM tree, the
insertion of newChild must be aborted in this case.
This patch adds a return statement that rectifies the behavior in this
edge case.
BUG=519558
Review URL: https://codereview.chromium.org/1283263002
git-svn-id: svn://svn.chromium.org/blink/trunk@200690 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264 | void ContainerNode::parserInsertBefore(PassRefPtrWillBeRawPtr<Node> newChild, Node& nextChild)
{
ASSERT(newChild);
ASSERT(nextChild.parentNode() == this);
ASSERT(!newChild->isDocumentFragment());
ASSERT(!isHTMLTemplateElement(this));
if (nextChild.previousSibling() == newChild || &nextChild == newChild) // nothing to do
return;
if (!checkParserAcceptChild(*newChild))
return;
RefPtrWillBeRawPtr<Node> protect(this);
while (RefPtrWillBeRawPtr<ContainerNode> parent = newChild->parentNode())
parent->parserRemoveChild(*newChild);
if (nextChild.parentNode() != this)
return;
if (document() != newChild->document())
document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION);
{
EventDispatchForbiddenScope assertNoEventDispatch;
ScriptForbiddenScope forbidScript;
treeScope().adoptIfNeeded(*newChild);
insertBeforeCommon(nextChild, *newChild);
newChild->updateAncestorConnectedSubframeCountForInsertion();
ChildListMutationScope(*this).childAdded(*newChild);
}
notifyNodeInserted(*newChild, ChildrenChangeSourceParser);
}
| 171,850 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: init_util(void)
{
filegen_register(statsdir, "peerstats", &peerstats);
filegen_register(statsdir, "loopstats", &loopstats);
filegen_register(statsdir, "clockstats", &clockstats);
filegen_register(statsdir, "rawstats", &rawstats);
filegen_register(statsdir, "sysstats", &sysstats);
filegen_register(statsdir, "protostats", &protostats);
#ifdef AUTOKEY
filegen_register(statsdir, "cryptostats", &cryptostats);
#endif /* AUTOKEY */
#ifdef DEBUG_TIMING
filegen_register(statsdir, "timingstats", &timingstats);
#endif /* DEBUG_TIMING */
/*
* register with libntp ntp_set_tod() to call us back
* when time is stepped.
*/
step_callback = &ntpd_time_stepped;
#ifdef DEBUG
atexit(&uninit_util);
#endif /* DEBUG */
}
Commit Message: [Bug 1773] openssl not detected during ./configure.
[Bug 1774] Segfaults if cryptostats enabled and built without OpenSSL.
CWE ID: CWE-20 | init_util(void)
{
filegen_register(statsdir, "peerstats", &peerstats);
filegen_register(statsdir, "loopstats", &loopstats);
filegen_register(statsdir, "clockstats", &clockstats);
filegen_register(statsdir, "rawstats", &rawstats);
filegen_register(statsdir, "sysstats", &sysstats);
filegen_register(statsdir, "protostats", &protostats);
filegen_register(statsdir, "cryptostats", &cryptostats);
filegen_register(statsdir, "timingstats", &timingstats);
/*
* register with libntp ntp_set_tod() to call us back
* when time is stepped.
*/
step_callback = &ntpd_time_stepped;
#ifdef DEBUG
atexit(&uninit_util);
#endif /* DEBUG */
}
| 168,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: void GestureProviderAura::OnGestureEvent(
const GestureEventData& gesture) {
GestureEventDetails details = gesture.details;
if (gesture.type == ET_GESTURE_TAP) {
int tap_count = 1;
if (previous_tap_ && IsConsideredDoubleTap(*previous_tap_, gesture))
tap_count = 1 + (previous_tap_->details.tap_count() % 3);
details.set_tap_count(tap_count);
if (!previous_tap_)
previous_tap_.reset(new GestureEventData(gesture));
else
*previous_tap_ = gesture;
previous_tap_->details = details;
} else if (gesture.type == ET_GESTURE_TAP_CANCEL) {
previous_tap_.reset();
}
scoped_ptr<ui::GestureEvent> event(
new ui::GestureEvent(gesture.type,
gesture.x,
gesture.y,
last_touch_event_flags_,
gesture.time - base::TimeTicks(),
details,
1 << gesture.motion_event_id));
if (!handling_event_) {
client_->OnGestureEvent(event.get());
} else {
pending_gestures_.push_back(event.release());
}
}
Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura.
BUG=379812
TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent
Review URL: https://codereview.chromium.org/309823002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GestureProviderAura::OnGestureEvent(
const GestureEventData& gesture) {
GestureEventDetails details = gesture.details;
if (gesture.type == ET_GESTURE_TAP) {
int tap_count = 1;
if (previous_tap_ && IsConsideredDoubleTap(*previous_tap_, gesture))
tap_count = 1 + (previous_tap_->details.tap_count() % 3);
details.set_tap_count(tap_count);
if (!previous_tap_)
previous_tap_.reset(new GestureEventData(gesture));
else
*previous_tap_ = gesture;
previous_tap_->details = details;
} else if (gesture.type == ET_GESTURE_TAP_CANCEL) {
previous_tap_.reset();
}
scoped_ptr<ui::GestureEvent> event(
new ui::GestureEvent(gesture.type,
gesture.x,
gesture.y,
last_touch_event_flags_,
gesture.time - base::TimeTicks(),
details,
1 << gesture.motion_event_id));
ui::LatencyInfo* gesture_latency = event->latency();
gesture_latency->CopyLatencyFrom(
last_touch_event_latency_info_,
ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT);
gesture_latency->CopyLatencyFrom(
last_touch_event_latency_info_,
ui::INPUT_EVENT_LATENCY_UI_COMPONENT);
gesture_latency->CopyLatencyFrom(
last_touch_event_latency_info_,
ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT);
if (!handling_event_) {
client_->OnGestureEvent(event.get());
} else {
pending_gestures_.push_back(event.release());
}
}
| 171,204 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHPAPI php_stream *_php_stream_memory_open(int mode, char *buf, size_t length STREAMS_DC TSRMLS_DC)
{
php_stream *stream;
php_stream_memory_data *ms;
if ((stream = php_stream_memory_create_rel(mode)) != NULL) {
ms = (php_stream_memory_data*)stream->abstract;
if (mode == TEMP_STREAM_READONLY || mode == TEMP_STREAM_TAKE_BUFFER) {
/* use the buffer directly */
ms->data = buf;
ms->fsize = length;
} else {
if (length) {
assert(buf != NULL);
php_stream_write(stream, buf, length);
}
}
}
return stream;
}
Commit Message:
CWE ID: CWE-20 | PHPAPI php_stream *_php_stream_memory_open(int mode, char *buf, size_t length STREAMS_DC TSRMLS_DC)
{
php_stream *stream;
php_stream_memory_data *ms;
if ((stream = php_stream_memory_create_rel(mode)) != NULL) {
ms = (php_stream_memory_data*)stream->abstract;
if (mode == TEMP_STREAM_READONLY || mode == TEMP_STREAM_TAKE_BUFFER) {
/* use the buffer directly */
ms->data = buf;
ms->fsize = length;
} else {
if (length) {
assert(buf != NULL);
php_stream_write(stream, buf, length);
}
}
}
return stream;
}
| 165,475 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_module_get_algo_block_size)
{
MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
RETURN_LONG(mcrypt_module_get_algo_block_size(module, dir));
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190 | PHP_FUNCTION(mcrypt_module_get_algo_block_size)
{
MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
RETURN_LONG(mcrypt_module_get_algo_block_size(module, dir));
}
| 167,099 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gsicc_open_search(const char* pname, int namelen, gs_memory_t *mem_gc,
const char* dirname, int dirlen, stream**strp)
{
char *buffer;
stream* str;
/* Check if we need to prepend the file name */
if ( dirname != NULL) {
/* If this fails, we will still try the file by itself and with
%rom% since someone may have left a space some of the spaces
as our defaults, even if they defined the directory to use.
This will occur only after searching the defined directory.
A warning is noted. */
buffer = (char *) gs_alloc_bytes(mem_gc, namelen + dirlen + 1,
"gsicc_open_search");
if (buffer == NULL)
return_error(gs_error_VMerror);
strcpy(buffer, dirname);
strcat(buffer, pname);
/* Just to make sure we were null terminated */
buffer[namelen + dirlen] = '\0';
str = sfopen(buffer, "r", mem_gc);
gs_free_object(mem_gc, buffer, "gsicc_open_search");
if (str != NULL) {
*strp = str;
return 0;
}
}
/* First just try it like it is */
str = sfopen(pname, "r", mem_gc);
if (str != NULL) {
*strp = str;
return 0;
}
/* If that fails, try %rom% */ /* FIXME: Not sure this is needed or correct */
strlen(DEFAULT_DIR_ICC),"gsicc_open_search");
if (buffer == NULL)
return_error(gs_error_VMerror);
strcpy(buffer, DEFAULT_DIR_ICC);
strcat(buffer, pname);
/* Just to make sure we were null terminated */
buffer[namelen + strlen(DEFAULT_DIR_ICC)] = '\0';
str = sfopen(buffer, "r", mem_gc);
gs_free_object(mem_gc, buffer, "gsicc_open_search");
if (str == NULL) {
gs_warn1("Could not find %s ",pname);
}
*strp = str;
return 0;
}
Commit Message:
CWE ID: CWE-20 | gsicc_open_search(const char* pname, int namelen, gs_memory_t *mem_gc,
const char* dirname, int dirlen, stream**strp)
{
char *buffer;
stream* str;
/* Check if we need to prepend the file name */
if ( dirname != NULL) {
/* If this fails, we will still try the file by itself and with
%rom% since someone may have left a space some of the spaces
as our defaults, even if they defined the directory to use.
This will occur only after searching the defined directory.
A warning is noted. */
buffer = (char *) gs_alloc_bytes(mem_gc, namelen + dirlen + 1,
"gsicc_open_search");
if (buffer == NULL)
return_error(gs_error_VMerror);
strcpy(buffer, dirname);
strcat(buffer, pname);
/* Just to make sure we were null terminated */
buffer[namelen + dirlen] = '\0';
str = sfopen(buffer, "r", mem_gc);
gs_free_object(mem_gc, buffer, "gsicc_open_search");
if (str != NULL) {
*strp = str;
return 0;
}
}
/* First just try it like it is */
if (gs_check_file_permission(mem_gc, pname, namelen, "r") >= 0) {
str = sfopen(pname, "r", mem_gc);
if (str != NULL) {
*strp = str;
return 0;
}
}
/* If that fails, try %rom% */ /* FIXME: Not sure this is needed or correct */
strlen(DEFAULT_DIR_ICC),"gsicc_open_search");
if (buffer == NULL)
return_error(gs_error_VMerror);
strcpy(buffer, DEFAULT_DIR_ICC);
strcat(buffer, pname);
/* Just to make sure we were null terminated */
buffer[namelen + strlen(DEFAULT_DIR_ICC)] = '\0';
str = sfopen(buffer, "r", mem_gc);
gs_free_object(mem_gc, buffer, "gsicc_open_search");
if (str == NULL) {
gs_warn1("Could not find %s ",pname);
}
*strp = str;
return 0;
}
| 165,265 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ContentBrowserClient::ShouldSwapProcessesForNavigation(
const GURL& current_url,
const GURL& new_url) {
return false;
}
Commit Message: Ensure extensions and the Chrome Web Store are loaded in new BrowsingInstances.
BUG=174943
TEST=Can't post message to CWS. See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/12301013
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@184208 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | bool ContentBrowserClient::ShouldSwapProcessesForNavigation(
SiteInstance* site_instance,
const GURL& current_url,
const GURL& new_url) {
return false;
}
| 171,438 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SendTabToSelfInfoBarDelegate::Create(const SendTabToSelfEntry* entry) {
return base::WrapUnique(new SendTabToSelfInfoBarDelegate(entry));
}
Commit Message: [SendTabToSelf] Added logic to display an infobar for the feature.
This CL is one of many to come. It covers:
* Creation of the infobar from the SendTabToSelfInfoBarController
* Plumbed the call to create the infobar to the native code.
* Open the link when user taps on the link
In follow-up CLs, the following will be done:
* Instantiate the InfobarController in the ChromeActivity
* Listen for Model changes in the Controller
Bug: 949233,963193
Change-Id: I5df1359debb5f0f35c32c2df3b691bf9129cdeb8
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1604406
Reviewed-by: Tommy Nyquist <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Mikel Astiz <[email protected]>
Reviewed-by: sebsg <[email protected]>
Reviewed-by: Jeffrey Cohen <[email protected]>
Reviewed-by: Matthew Jones <[email protected]>
Commit-Queue: Tanya Gupta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660854}
CWE ID: CWE-190 | SendTabToSelfInfoBarDelegate::Create(const SendTabToSelfEntry* entry) {
SendTabToSelfInfoBarDelegate::Create(content::WebContents* web_contents,
const SendTabToSelfEntry* entry) {
return base::WrapUnique(
new SendTabToSelfInfoBarDelegate(web_contents, entry));
}
| 172,540 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct sk_buff *udp6_ufo_fragment(struct sk_buff *skb,
netdev_features_t features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
unsigned int mss;
unsigned int unfrag_ip6hlen, unfrag_len;
struct frag_hdr *fptr;
u8 *packet_start, *prevhdr;
u8 nexthdr;
u8 frag_hdr_sz = sizeof(struct frag_hdr);
int offset;
__wsum csum;
int tnl_hlen;
mss = skb_shinfo(skb)->gso_size;
if (unlikely(skb->len <= mss))
goto out;
if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) {
/* Packet is from an untrusted source, reset gso_segs. */
int type = skb_shinfo(skb)->gso_type;
if (unlikely(type & ~(SKB_GSO_UDP |
SKB_GSO_DODGY |
SKB_GSO_UDP_TUNNEL |
SKB_GSO_GRE |
SKB_GSO_IPIP |
SKB_GSO_SIT |
SKB_GSO_MPLS) ||
!(type & (SKB_GSO_UDP))))
goto out;
skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss);
segs = NULL;
goto out;
}
if (skb->encapsulation && skb_shinfo(skb)->gso_type & SKB_GSO_UDP_TUNNEL)
segs = skb_udp_tunnel_segment(skb, features);
else {
/* Do software UFO. Complete and fill in the UDP checksum as HW cannot
* do checksum of UDP packets sent as multiple IP fragments.
*/
offset = skb_checksum_start_offset(skb);
csum = skb_checksum(skb, offset, skb->len - offset, 0);
offset += skb->csum_offset;
*(__sum16 *)(skb->data + offset) = csum_fold(csum);
skb->ip_summed = CHECKSUM_NONE;
/* Check if there is enough headroom to insert fragment header. */
tnl_hlen = skb_tnl_header_len(skb);
if (skb_headroom(skb) < (tnl_hlen + frag_hdr_sz)) {
if (gso_pskb_expand_head(skb, tnl_hlen + frag_hdr_sz))
goto out;
}
/* Find the unfragmentable header and shift it left by frag_hdr_sz
* bytes to insert fragment header.
*/
unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr);
nexthdr = *prevhdr;
*prevhdr = NEXTHDR_FRAGMENT;
unfrag_len = (skb_network_header(skb) - skb_mac_header(skb)) +
unfrag_ip6hlen + tnl_hlen;
packet_start = (u8 *) skb->head + SKB_GSO_CB(skb)->mac_offset;
memmove(packet_start-frag_hdr_sz, packet_start, unfrag_len);
SKB_GSO_CB(skb)->mac_offset -= frag_hdr_sz;
skb->mac_header -= frag_hdr_sz;
skb->network_header -= frag_hdr_sz;
fptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen);
fptr->nexthdr = nexthdr;
fptr->reserved = 0;
ipv6_select_ident(fptr, (struct rt6_info *)skb_dst(skb));
/* Fragment the skb. ipv6 header and the remaining fields of the
* fragment header are updated in ipv6_gso_segment()
*/
segs = skb_segment(skb, features);
}
out:
return segs;
}
Commit Message: ipv6: fix headroom calculation in udp6_ufo_fragment
Commit 1e2bd517c108816220f262d7954b697af03b5f9c ("udp6: Fix udp
fragmentation for tunnel traffic.") changed the calculation if
there is enough space to include a fragment header in the skb from a
skb->mac_header dervived one to skb_headroom. Because we already peeled
off the skb to transport_header this is wrong. Change this back to check
if we have enough room before the mac_header.
This fixes a panic Saran Neti reported. He used the tbf scheduler which
skb_gso_segments the skb. The offsets get negative and we panic in memcpy
because the skb was erroneously not expanded at the head.
Reported-by: Saran Neti <[email protected]>
Cc: Pravin B Shelar <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-189 | static struct sk_buff *udp6_ufo_fragment(struct sk_buff *skb,
netdev_features_t features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
unsigned int mss;
unsigned int unfrag_ip6hlen, unfrag_len;
struct frag_hdr *fptr;
u8 *packet_start, *prevhdr;
u8 nexthdr;
u8 frag_hdr_sz = sizeof(struct frag_hdr);
int offset;
__wsum csum;
int tnl_hlen;
mss = skb_shinfo(skb)->gso_size;
if (unlikely(skb->len <= mss))
goto out;
if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) {
/* Packet is from an untrusted source, reset gso_segs. */
int type = skb_shinfo(skb)->gso_type;
if (unlikely(type & ~(SKB_GSO_UDP |
SKB_GSO_DODGY |
SKB_GSO_UDP_TUNNEL |
SKB_GSO_GRE |
SKB_GSO_IPIP |
SKB_GSO_SIT |
SKB_GSO_MPLS) ||
!(type & (SKB_GSO_UDP))))
goto out;
skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss);
segs = NULL;
goto out;
}
if (skb->encapsulation && skb_shinfo(skb)->gso_type & SKB_GSO_UDP_TUNNEL)
segs = skb_udp_tunnel_segment(skb, features);
else {
/* Do software UFO. Complete and fill in the UDP checksum as HW cannot
* do checksum of UDP packets sent as multiple IP fragments.
*/
offset = skb_checksum_start_offset(skb);
csum = skb_checksum(skb, offset, skb->len - offset, 0);
offset += skb->csum_offset;
*(__sum16 *)(skb->data + offset) = csum_fold(csum);
skb->ip_summed = CHECKSUM_NONE;
/* Check if there is enough headroom to insert fragment header. */
tnl_hlen = skb_tnl_header_len(skb);
if (skb->mac_header < (tnl_hlen + frag_hdr_sz)) {
if (gso_pskb_expand_head(skb, tnl_hlen + frag_hdr_sz))
goto out;
}
/* Find the unfragmentable header and shift it left by frag_hdr_sz
* bytes to insert fragment header.
*/
unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr);
nexthdr = *prevhdr;
*prevhdr = NEXTHDR_FRAGMENT;
unfrag_len = (skb_network_header(skb) - skb_mac_header(skb)) +
unfrag_ip6hlen + tnl_hlen;
packet_start = (u8 *) skb->head + SKB_GSO_CB(skb)->mac_offset;
memmove(packet_start-frag_hdr_sz, packet_start, unfrag_len);
SKB_GSO_CB(skb)->mac_offset -= frag_hdr_sz;
skb->mac_header -= frag_hdr_sz;
skb->network_header -= frag_hdr_sz;
fptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen);
fptr->nexthdr = nexthdr;
fptr->reserved = 0;
ipv6_select_ident(fptr, (struct rt6_info *)skb_dst(skb));
/* Fragment the skb. ipv6 header and the remaining fields of the
* fragment header are updated in ipv6_gso_segment()
*/
segs = skb_segment(skb, features);
}
out:
return segs;
}
| 165,960 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 send_solid_rect(VncState *vs)
{
size_t bytes;
tight_pack24(vs, vs->tight.tight.buffer, 1, &vs->tight.tight.offset);
bytes = 3;
} else {
bytes = vs->clientds.pf.bytes_per_pixel;
}
Commit Message:
CWE ID: CWE-125 | static int send_solid_rect(VncState *vs)
{
size_t bytes;
tight_pack24(vs, vs->tight.tight.buffer, 1, &vs->tight.tight.offset);
bytes = 3;
} else {
bytes = vs->client_pf.bytes_per_pixel;
}
| 165,462 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
pcap_if_t *alldevs = NULL; // pointer to the header of the interface chain
pcap_if_t *d; // temp pointer needed to scan the interface chain
struct pcap_addr *address; // pcap structure that keeps a network address of an interface
struct rpcap_findalldevs_if *findalldevs_if;// rpcap structure that packet all the data of an interface together
uint16 nif = 0; // counts the number of interface listed
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
if (pcap_findalldevs(&alldevs, errmsgbuf) == -1)
goto error;
if (alldevs == NULL)
{
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_NOREMOTEIF,
"No interfaces found! Make sure libpcap/WinPcap is properly installed"
" and you have the right to access to the remote device.",
errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
for (d = alldevs; d != NULL; d = d->next)
{
nif++;
if (d->description)
plen+= strlen(d->description);
if (d->name)
plen+= strlen(d->name);
plen+= sizeof(struct rpcap_findalldevs_if);
for (address = d->addresses; address != NULL; address = address->next)
{
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
plen+= (sizeof(struct rpcap_sockaddr) * 4);
break;
default:
break;
}
}
}
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_FINDALLIF_REPLY, nif, plen);
for (d = alldevs; d != NULL; d = d->next)
{
uint16 lname, ldescr;
findalldevs_if = (struct rpcap_findalldevs_if *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_findalldevs_if), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
memset(findalldevs_if, 0, sizeof(struct rpcap_findalldevs_if));
if (d->description) ldescr = (short) strlen(d->description);
else ldescr = 0;
if (d->name) lname = (short) strlen(d->name);
else lname = 0;
findalldevs_if->desclen = htons(ldescr);
findalldevs_if->namelen = htons(lname);
findalldevs_if->flags = htonl(d->flags);
for (address = d->addresses; address != NULL; address = address->next)
{
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
findalldevs_if->naddr++;
break;
default:
break;
}
}
findalldevs_if->naddr = htons(findalldevs_if->naddr);
if (sock_bufferize(d->name, lname, sendbuf, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
if (sock_bufferize(d->description, ldescr, sendbuf, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
for (address = d->addresses; address != NULL; address = address->next)
{
struct rpcap_sockaddr *sockaddr;
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->addr, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->netmask, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->broadaddr, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->dstaddr, sockaddr);
break;
default:
break;
}
}
}
pcap_freealldevs(alldevs);
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
if (alldevs)
pcap_freealldevs(alldevs);
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_FINDALLIF,
errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
Commit Message: Calculate the reply payload length in a local variable.
Using the same variable for the remaining request length and the reply
length is confusing at best and can cause errors at worst (if the
request had extra stuff at the end, so that the variable is non-zero).
This addresses Include Security issue I8: [libpcap] Remote Packet
Capture Daemon Parameter Reuse.
CWE ID: CWE-20 | daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
pcap_if_t *alldevs = NULL; // pointer to the header of the interface chain
pcap_if_t *d; // temp pointer needed to scan the interface chain
struct pcap_addr *address; // pcap structure that keeps a network address of an interface
struct rpcap_findalldevs_if *findalldevs_if;// rpcap structure that packet all the data of an interface together
uint32 replylen; // length of reply payload
uint16 nif = 0; // counts the number of interface listed
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
if (pcap_findalldevs(&alldevs, errmsgbuf) == -1)
goto error;
if (alldevs == NULL)
{
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_NOREMOTEIF,
"No interfaces found! Make sure libpcap/WinPcap is properly installed"
" and you have the right to access to the remote device.",
errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
// This checks the number of interfaces and computes the total
// length of the payload.
replylen = 0;
for (d = alldevs; d != NULL; d = d->next)
{
nif++;
if (d->description)
replylen += strlen(d->description);
if (d->name)
replylen += strlen(d->name);
replylen += sizeof(struct rpcap_findalldevs_if);
for (address = d->addresses; address != NULL; address = address->next)
{
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
replylen += (sizeof(struct rpcap_sockaddr) * 4);
break;
default:
break;
}
}
}
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_FINDALLIF_REPLY, nif, replylen);
for (d = alldevs; d != NULL; d = d->next)
{
uint16 lname, ldescr;
findalldevs_if = (struct rpcap_findalldevs_if *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_findalldevs_if), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
memset(findalldevs_if, 0, sizeof(struct rpcap_findalldevs_if));
if (d->description) ldescr = (short) strlen(d->description);
else ldescr = 0;
if (d->name) lname = (short) strlen(d->name);
else lname = 0;
findalldevs_if->desclen = htons(ldescr);
findalldevs_if->namelen = htons(lname);
findalldevs_if->flags = htonl(d->flags);
for (address = d->addresses; address != NULL; address = address->next)
{
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
findalldevs_if->naddr++;
break;
default:
break;
}
}
findalldevs_if->naddr = htons(findalldevs_if->naddr);
if (sock_bufferize(d->name, lname, sendbuf, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
if (sock_bufferize(d->description, ldescr, sendbuf, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
for (address = d->addresses; address != NULL; address = address->next)
{
struct rpcap_sockaddr *sockaddr;
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->addr, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->netmask, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->broadaddr, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->dstaddr, sockaddr);
break;
default:
break;
}
}
}
pcap_freealldevs(alldevs);
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
if (alldevs)
pcap_freealldevs(alldevs);
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_FINDALLIF,
errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
| 169,543 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 gdTransformAffineCopy(gdImagePtr dst,
int dst_x, int dst_y,
const gdImagePtr src,
gdRectPtr src_region,
const double affine[6])
{
int c1x,c1y,c2x,c2y;
int backclip = 0;
int backup_clipx1, backup_clipy1, backup_clipx2, backup_clipy2;
register int x, y, src_offset_x, src_offset_y;
double inv[6];
int *dst_p;
gdPointF pt, src_pt;
gdRect bbox;
int end_x, end_y;
gdInterpolationMethod interpolation_id_bak = GD_DEFAULT;
interpolation_method interpolation_bak;
/* These methods use special implementations */
if (src->interpolation_id == GD_BILINEAR_FIXED || src->interpolation_id == GD_BICUBIC_FIXED || src->interpolation_id == GD_NEAREST_NEIGHBOUR) {
interpolation_id_bak = src->interpolation_id;
interpolation_bak = src->interpolation;
gdImageSetInterpolationMethod(src, GD_BICUBIC);
}
gdImageClipRectangle(src, src_region);
if (src_region->x > 0 || src_region->y > 0
|| src_region->width < gdImageSX(src)
|| src_region->height < gdImageSY(src)) {
backclip = 1;
gdImageGetClip(src, &backup_clipx1, &backup_clipy1,
&backup_clipx2, &backup_clipy2);
gdImageSetClip(src, src_region->x, src_region->y,
src_region->x + src_region->width - 1,
src_region->y + src_region->height - 1);
}
if (!gdTransformAffineBoundingBox(src_region, affine, &bbox)) {
if (backclip) {
gdImageSetClip(src, backup_clipx1, backup_clipy1,
backup_clipx2, backup_clipy2);
}
gdImageSetInterpolationMethod(src, interpolation_id_bak);
return GD_FALSE;
}
gdImageGetClip(dst, &c1x, &c1y, &c2x, &c2y);
end_x = bbox.width + (int) fabs(bbox.x);
end_y = bbox.height + (int) fabs(bbox.y);
/* Get inverse affine to let us work with destination -> source */
gdAffineInvert(inv, affine);
src_offset_x = src_region->x;
src_offset_y = src_region->y;
if (dst->alphaBlendingFlag) {
for (y = bbox.y; y <= end_y; y++) {
pt.y = y + 0.5;
for (x = 0; x <= end_x; x++) {
pt.x = x + 0.5;
gdAffineApplyToPointF(&src_pt, &pt, inv);
gdImageSetPixel(dst, dst_x + x, dst_y + y, getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, 0));
}
}
} else {
for (y = 0; y <= end_y; y++) {
pt.y = y + 0.5 + bbox.y;
if ((dst_y + y) < 0 || ((dst_y + y) > gdImageSY(dst) -1)) {
continue;
}
dst_p = dst->tpixels[dst_y + y] + dst_x;
for (x = 0; x <= end_x; x++) {
pt.x = x + 0.5 + bbox.x;
gdAffineApplyToPointF(&src_pt, &pt, inv);
if ((dst_x + x) < 0 || (dst_x + x) > (gdImageSX(dst) - 1)) {
break;
}
*(dst_p++) = getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, -1);
}
}
}
/* Restore clip if required */
if (backclip) {
gdImageSetClip(src, backup_clipx1, backup_clipy1,
backup_clipx2, backup_clipy2);
}
gdImageSetInterpolationMethod(src, interpolation_id_bak);
return GD_TRUE;
}
Commit Message: Fixed bug #72227: imagescale out-of-bounds read
Ported from https://github.com/libgd/libgd/commit/4f65a3e4eedaffa1efcf9ee1eb08f0b504fbc31a
CWE ID: CWE-125 | int gdTransformAffineCopy(gdImagePtr dst,
int dst_x, int dst_y,
const gdImagePtr src,
gdRectPtr src_region,
const double affine[6])
{
int c1x,c1y,c2x,c2y;
int backclip = 0;
int backup_clipx1, backup_clipy1, backup_clipx2, backup_clipy2;
register int x, y, src_offset_x, src_offset_y;
double inv[6];
int *dst_p;
gdPointF pt, src_pt;
gdRect bbox;
int end_x, end_y;
gdInterpolationMethod interpolation_id_bak = GD_DEFAULT;
interpolation_method interpolation_bak;
/* These methods use special implementations */
if (src->interpolation_id == GD_BILINEAR_FIXED || src->interpolation_id == GD_BICUBIC_FIXED || src->interpolation_id == GD_NEAREST_NEIGHBOUR) {
interpolation_id_bak = src->interpolation_id;
interpolation_bak = src->interpolation;
gdImageSetInterpolationMethod(src, GD_BICUBIC);
}
gdImageClipRectangle(src, src_region);
if (src_region->x > 0 || src_region->y > 0
|| src_region->width < gdImageSX(src)
|| src_region->height < gdImageSY(src)) {
backclip = 1;
gdImageGetClip(src, &backup_clipx1, &backup_clipy1,
&backup_clipx2, &backup_clipy2);
gdImageSetClip(src, src_region->x, src_region->y,
src_region->x + src_region->width - 1,
src_region->y + src_region->height - 1);
}
if (!gdTransformAffineBoundingBox(src_region, affine, &bbox)) {
if (backclip) {
gdImageSetClip(src, backup_clipx1, backup_clipy1,
backup_clipx2, backup_clipy2);
}
gdImageSetInterpolationMethod(src, interpolation_id_bak);
return GD_FALSE;
}
gdImageGetClip(dst, &c1x, &c1y, &c2x, &c2y);
end_x = bbox.width + (int) fabs(bbox.x);
end_y = bbox.height + (int) fabs(bbox.y);
/* Get inverse affine to let us work with destination -> source */
gdAffineInvert(inv, affine);
src_offset_x = src_region->x;
src_offset_y = src_region->y;
if (dst->alphaBlendingFlag) {
for (y = bbox.y; y <= end_y; y++) {
pt.y = y + 0.5;
for (x = 0; x <= end_x; x++) {
pt.x = x + 0.5;
gdAffineApplyToPointF(&src_pt, &pt, inv);
gdImageSetPixel(dst, dst_x + x, dst_y + y, getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, 0));
}
}
} else {
for (y = 0; y <= end_y; y++) {
pt.y = y + 0.5 + bbox.y;
if ((dst_y + y) < 0 || ((dst_y + y) > gdImageSY(dst) -1)) {
continue;
}
dst_p = dst->tpixels[dst_y + y] + dst_x;
for (x = 0; x <= end_x; x++) {
pt.x = x + 0.5 + bbox.x;
gdAffineApplyToPointF(&src_pt, &pt, inv);
if ((dst_x + x) < 0 || (dst_x + x) > (gdImageSX(dst) - 1)) {
break;
}
*(dst_p++) = getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, -1);
}
}
}
/* Restore clip if required */
if (backclip) {
gdImageSetClip(src, backup_clipx1, backup_clipy1,
backup_clipx2, backup_clipy2);
}
gdImageSetInterpolationMethod(src, interpolation_id_bak);
return GD_TRUE;
}
| 170,006 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: media::interfaces::ServiceFactory* RenderFrameImpl::GetMediaServiceFactory() {
if (!media_service_factory_) {
mojo::InterfacePtr<mojo::Shell> shell_ptr;
GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&shell_ptr));
mojo::ServiceProviderPtr service_provider;
mojo::URLRequestPtr request(mojo::URLRequest::New());
request->url = mojo::String::From("mojo:media");
shell_ptr->ConnectToApplication(request.Pass(), GetProxy(&service_provider),
nullptr, nullptr);
mojo::ConnectToService(service_provider.get(), &media_service_factory_);
media_service_factory_.set_connection_error_handler(
base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError,
base::Unretained(this)));
}
return media_service_factory_.get();
}
Commit Message: Connect WebUSB client interface to the devices app
This provides a basic WebUSB client interface in
content/renderer. Most of the interface is unimplemented,
but this CL hooks up navigator.usb.getDevices() to the
browser's Mojo devices app to enumerate available USB
devices.
BUG=492204
Review URL: https://codereview.chromium.org/1293253002
Cr-Commit-Position: refs/heads/master@{#344881}
CWE ID: CWE-399 | media::interfaces::ServiceFactory* RenderFrameImpl::GetMediaServiceFactory() {
if (!media_service_factory_) {
mojo::ServiceProviderPtr service_provider =
ConnectToApplication(GURL("mojo:media"));
mojo::ConnectToService(service_provider.get(), &media_service_factory_);
media_service_factory_.set_connection_error_handler(
base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError,
base::Unretained(this)));
}
return media_service_factory_.get();
}
| 171,696 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: t42_parse_charstrings( T42_Face face,
T42_Loader loader )
{
T42_Parser parser = &loader->parser;
PS_Table code_table = &loader->charstrings;
PS_Table name_table = &loader->glyph_names;
PS_Table swap_table = &loader->swap_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
PSAux_Service psaux = (PSAux_Service)face->psaux;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
FT_UInt n;
FT_UInt notdef_index = 0;
FT_Byte notdef_found = 0;
T1_Skip_Spaces( parser );
if ( parser->root.cursor >= limit )
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
if ( ft_isdigit( *parser->root.cursor ) )
{
loader->num_glyphs = (FT_UInt)T1_ToInt( parser );
if ( parser->root.error )
return;
}
else if ( *parser->root.cursor == '<' )
{
/* We have `<< ... >>'. Count the number of `/' in the dictionary */
/* to get its size. */
FT_UInt count = 0;
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
while ( parser->root.cursor < limit )
{
if ( *parser->root.cursor == '/' )
count++;
else if ( *parser->root.cursor == '>' )
{
loader->num_glyphs = count;
parser->root.cursor = cur; /* rewind */
break;
}
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
T1_Skip_Spaces( parser );
}
}
else
{
FT_ERROR(( "t42_parse_charstrings: invalid token\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
if ( parser->root.cursor >= limit )
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* initialize tables */
error = psaux->ps_table_funcs->init( code_table,
loader->num_glyphs,
memory );
if ( error )
goto Fail;
error = psaux->ps_table_funcs->init( name_table,
loader->num_glyphs,
memory );
if ( error )
goto Fail;
/* Initialize table for swapping index notdef_index and */
/* index 0 names and codes (if necessary). */
error = psaux->ps_table_funcs->init( swap_table, 4, memory );
if ( error )
goto Fail;
n = 0;
for (;;)
{
/* The format is simple: */
/* `/glyphname' + index [+ def] */
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
break;
/* We stop when we find an `end' keyword or '>' */
if ( *cur == 'e' &&
cur + 3 < limit &&
cur[1] == 'n' &&
cur[2] == 'd' &&
t42_is_space( cur[3] ) )
break;
if ( *cur == '>' )
break;
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
cur++; /* skip `/' */
len = parser->root.cursor - cur;
error = T1_Add_Table( name_table, n, cur, len + 1 );
if ( error )
goto Fail;
/* add a trailing zero to the name table */
name_table->elements[n][len] = '\0';
/* record index of /.notdef */
if ( *cur == '.' &&
ft_strcmp( ".notdef",
(const char*)(name_table->elements[n]) ) == 0 )
{
notdef_index = n;
notdef_found = 1;
}
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
(void)T1_ToInt( parser );
if ( parser->root.cursor >= limit )
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
len = parser->root.cursor - cur;
error = T1_Add_Table( code_table, n, cur, len + 1 );
if ( error )
goto Fail;
code_table->elements[n][len] = '\0';
n++;
if ( n >= loader->num_glyphs )
break;
}
}
Commit Message:
CWE ID: CWE-119 | t42_parse_charstrings( T42_Face face,
T42_Loader loader )
{
T42_Parser parser = &loader->parser;
PS_Table code_table = &loader->charstrings;
PS_Table name_table = &loader->glyph_names;
PS_Table swap_table = &loader->swap_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
PSAux_Service psaux = (PSAux_Service)face->psaux;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
FT_UInt n;
FT_UInt notdef_index = 0;
FT_Byte notdef_found = 0;
T1_Skip_Spaces( parser );
if ( parser->root.cursor >= limit )
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
if ( ft_isdigit( *parser->root.cursor ) )
{
loader->num_glyphs = (FT_UInt)T1_ToInt( parser );
if ( parser->root.error )
return;
}
else if ( *parser->root.cursor == '<' )
{
/* We have `<< ... >>'. Count the number of `/' in the dictionary */
/* to get its size. */
FT_UInt count = 0;
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
while ( parser->root.cursor < limit )
{
if ( *parser->root.cursor == '/' )
count++;
else if ( *parser->root.cursor == '>' )
{
loader->num_glyphs = count;
parser->root.cursor = cur; /* rewind */
break;
}
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
T1_Skip_Spaces( parser );
}
}
else
{
FT_ERROR(( "t42_parse_charstrings: invalid token\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
if ( parser->root.cursor >= limit )
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* initialize tables */
error = psaux->ps_table_funcs->init( code_table,
loader->num_glyphs,
memory );
if ( error )
goto Fail;
error = psaux->ps_table_funcs->init( name_table,
loader->num_glyphs,
memory );
if ( error )
goto Fail;
/* Initialize table for swapping index notdef_index and */
/* index 0 names and codes (if necessary). */
error = psaux->ps_table_funcs->init( swap_table, 4, memory );
if ( error )
goto Fail;
n = 0;
for (;;)
{
/* The format is simple: */
/* `/glyphname' + index [+ def] */
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
break;
/* We stop when we find an `end' keyword or '>' */
if ( *cur == 'e' &&
cur + 3 < limit &&
cur[1] == 'n' &&
cur[2] == 'd' &&
t42_is_space( cur[3] ) )
break;
if ( *cur == '>' )
break;
T1_Skip_PS_Token( parser );
if ( parser->root.cursor >= limit )
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
if ( parser->root.error )
return;
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
cur++; /* skip `/' */
len = parser->root.cursor - cur;
error = T1_Add_Table( name_table, n, cur, len + 1 );
if ( error )
goto Fail;
/* add a trailing zero to the name table */
name_table->elements[n][len] = '\0';
/* record index of /.notdef */
if ( *cur == '.' &&
ft_strcmp( ".notdef",
(const char*)(name_table->elements[n]) ) == 0 )
{
notdef_index = n;
notdef_found = 1;
}
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
(void)T1_ToInt( parser );
if ( parser->root.cursor >= limit )
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
len = parser->root.cursor - cur;
error = T1_Add_Table( code_table, n, cur, len + 1 );
if ( error )
goto Fail;
code_table->elements[n][len] = '\0';
n++;
if ( n >= loader->num_glyphs )
break;
}
}
| 164,858 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: lldp_mgmt_addr_tlv_print(netdissect_options *ndo,
const u_char *pptr, u_int len)
{
uint8_t mgmt_addr_len, intf_num_subtype, oid_len;
const u_char *tptr;
u_int tlen;
char *mgmt_addr;
tlen = len;
tptr = pptr;
if (tlen < 1) {
return 0;
}
mgmt_addr_len = *tptr++;
tlen--;
if (tlen < mgmt_addr_len) {
return 0;
}
mgmt_addr = lldp_network_addr_print(ndo, tptr, mgmt_addr_len);
if (mgmt_addr == NULL) {
return 0;
}
ND_PRINT((ndo, "\n\t Management Address length %u, %s",
mgmt_addr_len, mgmt_addr));
tptr += mgmt_addr_len;
tlen -= mgmt_addr_len;
if (tlen < LLDP_INTF_NUM_LEN) {
return 0;
}
intf_num_subtype = *tptr;
ND_PRINT((ndo, "\n\t %s Interface Numbering (%u): %u",
tok2str(lldp_intf_numb_subtype_values, "Unknown", intf_num_subtype),
intf_num_subtype,
EXTRACT_32BITS(tptr + 1)));
tptr += LLDP_INTF_NUM_LEN;
tlen -= LLDP_INTF_NUM_LEN;
/*
* The OID is optional.
*/
if (tlen) {
oid_len = *tptr;
if (tlen < oid_len) {
return 0;
}
if (oid_len) {
ND_PRINT((ndo, "\n\t OID length %u", oid_len));
safeputs(ndo, tptr + 1, oid_len);
}
}
return 1;
}
Commit Message: CVE-2017-13027/LLDP: Fix a bounds check.
The total length of the OID is the OID length plus the length of the OID
length itself.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125 | lldp_mgmt_addr_tlv_print(netdissect_options *ndo,
const u_char *pptr, u_int len)
{
uint8_t mgmt_addr_len, intf_num_subtype, oid_len;
const u_char *tptr;
u_int tlen;
char *mgmt_addr;
tlen = len;
tptr = pptr;
if (tlen < 1) {
return 0;
}
mgmt_addr_len = *tptr++;
tlen--;
if (tlen < mgmt_addr_len) {
return 0;
}
mgmt_addr = lldp_network_addr_print(ndo, tptr, mgmt_addr_len);
if (mgmt_addr == NULL) {
return 0;
}
ND_PRINT((ndo, "\n\t Management Address length %u, %s",
mgmt_addr_len, mgmt_addr));
tptr += mgmt_addr_len;
tlen -= mgmt_addr_len;
if (tlen < LLDP_INTF_NUM_LEN) {
return 0;
}
intf_num_subtype = *tptr;
ND_PRINT((ndo, "\n\t %s Interface Numbering (%u): %u",
tok2str(lldp_intf_numb_subtype_values, "Unknown", intf_num_subtype),
intf_num_subtype,
EXTRACT_32BITS(tptr + 1)));
tptr += LLDP_INTF_NUM_LEN;
tlen -= LLDP_INTF_NUM_LEN;
/*
* The OID is optional.
*/
if (tlen) {
oid_len = *tptr;
if (tlen < 1U + oid_len) {
return 0;
}
if (oid_len) {
ND_PRINT((ndo, "\n\t OID length %u", oid_len));
safeputs(ndo, tptr + 1, oid_len);
}
}
return 1;
}
| 167,863 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void SetUp() {
video_ = new libvpx_test::WebMVideoSource(kVP9TestFile);
ASSERT_TRUE(video_ != NULL);
video_->Init();
video_->Begin();
vpx_codec_dec_cfg_t cfg = {0};
decoder_ = new libvpx_test::VP9Decoder(cfg, 0);
ASSERT_TRUE(decoder_ != NULL);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | virtual void SetUp() {
video_ = new libvpx_test::WebMVideoSource(kVP9TestFile);
ASSERT_TRUE(video_ != NULL);
video_->Init();
video_->Begin();
vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t();
decoder_ = new libvpx_test::VP9Decoder(cfg, 0);
ASSERT_TRUE(decoder_ != NULL);
}
| 174,546 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos,
unsigned int *pv)
{
unsigned int field_type;
unsigned int value_count;
field_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian);
value_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian);
if(value_count!=1) return 0;
if(field_type==3) { // SHORT (uint16)
*pv = iw_get_ui16_e(&e->d[tag_pos+8],e->endian);
return 1;
}
else if(field_type==4) { // LONG (uint32)
*pv = iw_get_ui32_e(&e->d[tag_pos+8],e->endian);
return 1;
}
return 0;
}
Commit Message: Fixed invalid memory access bugs when decoding JPEG Exif data
Fixes issues #22, #23, #24, #25
CWE ID: CWE-125 | static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos,
unsigned int *pv)
{
unsigned int field_type;
unsigned int value_count;
field_type = get_exif_ui16(e, tag_pos+2);
value_count = get_exif_ui32(e, tag_pos+4);
if(value_count!=1) return 0;
if(field_type==3) { // SHORT (uint16)
*pv = get_exif_ui16(e, tag_pos+8);
return 1;
}
else if(field_type==4) { // LONG (uint32)
*pv = get_exif_ui32(e, tag_pos+8);
return 1;
}
return 0;
}
| 168,114 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 rtecp_select_file(sc_card_t *card,
const sc_path_t *in_path, sc_file_t **file_out)
{
sc_file_t **file_out_copy, *file;
int r;
assert(card && card->ctx && in_path);
switch (in_path->type)
{
case SC_PATH_TYPE_DF_NAME:
case SC_PATH_TYPE_FROM_CURRENT:
case SC_PATH_TYPE_PARENT:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED);
}
assert(iso_ops && iso_ops->select_file);
file_out_copy = file_out;
r = iso_ops->select_file(card, in_path, file_out_copy);
if (r || file_out_copy == NULL)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
assert(file_out_copy);
file = *file_out_copy;
assert(file);
if (file->sec_attr && file->sec_attr_len == SC_RTECP_SEC_ATTR_SIZE)
set_acl_from_sec_attr(card, file);
else
r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
if (r)
sc_file_free(file);
else
{
assert(file_out);
*file_out = file;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125 | static int rtecp_select_file(sc_card_t *card,
const sc_path_t *in_path, sc_file_t **file_out)
{
sc_file_t **file_out_copy, *file;
int r;
assert(card && card->ctx && in_path);
switch (in_path->type)
{
case SC_PATH_TYPE_DF_NAME:
case SC_PATH_TYPE_FROM_CURRENT:
case SC_PATH_TYPE_PARENT:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED);
}
assert(iso_ops && iso_ops->select_file);
file_out_copy = file_out;
r = iso_ops->select_file(card, in_path, file_out_copy);
if (r || file_out_copy == NULL)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
assert(file_out_copy);
file = *file_out_copy;
assert(file);
if (file->sec_attr && file->sec_attr_len == SC_RTECP_SEC_ATTR_SIZE)
set_acl_from_sec_attr(card, file);
else
r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
if (r && !file_out)
sc_file_free(file);
else
{
assert(file_out);
*file_out = file;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
| 169,063 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: header_put_le_int (SF_PRIVATE *psf, int x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 4)
{ psf->header [psf->headindex++] = x ;
psf->header [psf->headindex++] = (x >> 8) ;
psf->header [psf->headindex++] = (x >> 16) ;
psf->header [psf->headindex++] = (x >> 24) ;
} ;
} /* header_put_le_int */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119 | header_put_le_int (SF_PRIVATE *psf, int x)
{ psf->header.ptr [psf->header.indx++] = x ;
psf->header.ptr [psf->header.indx++] = (x >> 8) ;
psf->header.ptr [psf->header.indx++] = (x >> 16) ;
psf->header.ptr [psf->header.indx++] = (x >> 24) ;
} /* header_put_le_int */
| 170,057 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: fst_get_iface(struct fst_card_info *card, struct fst_port_info *port,
struct ifreq *ifr)
{
sync_serial_settings sync;
int i;
/* First check what line type is set, we'll default to reporting X.21
* if nothing is set as IF_IFACE_SYNC_SERIAL implies it can't be
* changed
*/
switch (port->hwif) {
case E1:
ifr->ifr_settings.type = IF_IFACE_E1;
break;
case T1:
ifr->ifr_settings.type = IF_IFACE_T1;
break;
case V35:
ifr->ifr_settings.type = IF_IFACE_V35;
break;
case V24:
ifr->ifr_settings.type = IF_IFACE_V24;
break;
case X21D:
ifr->ifr_settings.type = IF_IFACE_X21D;
break;
case X21:
default:
ifr->ifr_settings.type = IF_IFACE_X21;
break;
}
if (ifr->ifr_settings.size == 0) {
return 0; /* only type requested */
}
if (ifr->ifr_settings.size < sizeof (sync)) {
return -ENOMEM;
}
i = port->index;
sync.clock_rate = FST_RDL(card, portConfig[i].lineSpeed);
/* Lucky card and linux use same encoding here */
sync.clock_type = FST_RDB(card, portConfig[i].internalClock) ==
INTCLK ? CLOCK_INT : CLOCK_EXT;
sync.loopback = 0;
if (copy_to_user(ifr->ifr_settings.ifs_ifsu.sync, &sync, sizeof (sync))) {
return -EFAULT;
}
ifr->ifr_settings.size = sizeof (sync);
return 0;
}
Commit Message: farsync: fix info leak in ioctl
The fst_get_iface() code fails to initialize the two padding bytes of
struct sync_serial_settings after the ->loopback member. Add an explicit
memset(0) before filling the structure to avoid the info leak.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | fst_get_iface(struct fst_card_info *card, struct fst_port_info *port,
struct ifreq *ifr)
{
sync_serial_settings sync;
int i;
/* First check what line type is set, we'll default to reporting X.21
* if nothing is set as IF_IFACE_SYNC_SERIAL implies it can't be
* changed
*/
switch (port->hwif) {
case E1:
ifr->ifr_settings.type = IF_IFACE_E1;
break;
case T1:
ifr->ifr_settings.type = IF_IFACE_T1;
break;
case V35:
ifr->ifr_settings.type = IF_IFACE_V35;
break;
case V24:
ifr->ifr_settings.type = IF_IFACE_V24;
break;
case X21D:
ifr->ifr_settings.type = IF_IFACE_X21D;
break;
case X21:
default:
ifr->ifr_settings.type = IF_IFACE_X21;
break;
}
if (ifr->ifr_settings.size == 0) {
return 0; /* only type requested */
}
if (ifr->ifr_settings.size < sizeof (sync)) {
return -ENOMEM;
}
i = port->index;
memset(&sync, 0, sizeof(sync));
sync.clock_rate = FST_RDL(card, portConfig[i].lineSpeed);
/* Lucky card and linux use same encoding here */
sync.clock_type = FST_RDB(card, portConfig[i].internalClock) ==
INTCLK ? CLOCK_INT : CLOCK_EXT;
sync.loopback = 0;
if (copy_to_user(ifr->ifr_settings.ifs_ifsu.sync, &sync, sizeof (sync))) {
return -EFAULT;
}
ifr->ifr_settings.size = sizeof (sync);
return 0;
}
| 166,439 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cg_open(const char *path, struct fuse_file_info *fi)
{
const char *cgroup;
char *fpath = NULL, *path1, *path2, * cgdir = NULL, *controller;
struct cgfs_files *k = NULL;
struct file_info *file_info;
struct fuse_context *fc = fuse_get_context();
int ret;
if (!fc)
return -EIO;
controller = pick_controller_from_path(fc, path);
if (!controller)
return -EIO;
cgroup = find_cgroup_in_path(path);
if (!cgroup)
return -EINVAL;
get_cgdir_and_path(cgroup, &cgdir, &fpath);
if (!fpath) {
path1 = "/";
path2 = cgdir;
} else {
path1 = cgdir;
path2 = fpath;
}
k = cgfs_get_key(controller, path1, path2);
if (!k) {
ret = -EINVAL;
goto out;
}
free_key(k);
if (!fc_may_access(fc, controller, path1, path2, fi->flags)) {
ret = -EACCES;
goto out;
}
/* we'll free this at cg_release */
file_info = malloc(sizeof(*file_info));
if (!file_info) {
ret = -ENOMEM;
goto out;
}
file_info->controller = must_copy_string(controller);
file_info->cgroup = must_copy_string(path1);
file_info->file = must_copy_string(path2);
file_info->type = LXC_TYPE_CGFILE;
file_info->buf = NULL;
file_info->buflen = 0;
fi->fh = (unsigned long)file_info;
ret = 0;
out:
free(cgdir);
return ret;
}
Commit Message: Fix checking of parent directories
Taken from the justification in the launchpad bug:
To a task in freezer cgroup /a/b/c/d, it should appear that there are no
cgroups other than its descendents. Since this is a filesystem, we must have
the parent directories, but each parent cgroup should only contain the child
which the task can see.
So, when this task looks at /a/b, it should see only directory 'c' and no
files. Attempt to create /a/b/x should result in -EPERM, whether /a/b/x already
exists or not. Attempts to query /a/b/x should result in -ENOENT whether /a/b/x
exists or not. Opening /a/b/tasks should result in -ENOENT.
The caller_may_see_dir checks specifically whether a task may see a cgroup
directory - i.e. /a/b/x if opening /a/b/x/tasks, and /a/b/c/d if doing
opendir('/a/b/c/d').
caller_is_in_ancestor() will return true if the caller in /a/b/c/d looks at
/a/b/c/d/e. If the caller is in a child cgroup of the queried one - i.e. if the
task in /a/b/c/d queries /a/b, then *nextcg will container the next (the only)
directory which he can see in the path - 'c'.
Beyond this, regular DAC permissions should apply, with the
root-in-user-namespace privilege over its mapped uids being respected. The
fc_may_access check does this check for both directories and files.
This is CVE-2015-1342 (LP: #1508481)
Signed-off-by: Serge Hallyn <[email protected]>
CWE ID: CWE-264 | static int cg_open(const char *path, struct fuse_file_info *fi)
{
const char *cgroup;
char *fpath = NULL, *path1, *path2, * cgdir = NULL, *controller;
struct cgfs_files *k = NULL;
struct file_info *file_info;
struct fuse_context *fc = fuse_get_context();
int ret;
if (!fc)
return -EIO;
controller = pick_controller_from_path(fc, path);
if (!controller)
return -EIO;
cgroup = find_cgroup_in_path(path);
if (!cgroup)
return -EINVAL;
get_cgdir_and_path(cgroup, &cgdir, &fpath);
if (!fpath) {
path1 = "/";
path2 = cgdir;
} else {
path1 = cgdir;
path2 = fpath;
}
k = cgfs_get_key(controller, path1, path2);
if (!k) {
ret = -EINVAL;
goto out;
}
free_key(k);
if (!caller_may_see_dir(fc->pid, controller, path1)) {
ret = -ENOENT;
goto out;
}
if (!fc_may_access(fc, controller, path1, path2, fi->flags)) {
ret = -EACCES;
goto out;
}
/* we'll free this at cg_release */
file_info = malloc(sizeof(*file_info));
if (!file_info) {
ret = -ENOMEM;
goto out;
}
file_info->controller = must_copy_string(controller);
file_info->cgroup = must_copy_string(path1);
file_info->file = must_copy_string(path2);
file_info->type = LXC_TYPE_CGFILE;
file_info->buf = NULL;
file_info->buflen = 0;
fi->fh = (unsigned long)file_info;
ret = 0;
out:
free(cgdir);
return ret;
}
| 166,706 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DefragVlanTest(void)
{
Packet *p1 = NULL, *p2 = NULL, *r = NULL;
int ret = 0;
DefragInit();
p1 = BuildTestPacket(1, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = BuildTestPacket(1, 1, 0, 'B', 8);
if (p2 == NULL)
goto end;
/* With no VLAN IDs set, packets should re-assemble. */
if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)
goto end;
if ((r = Defrag(NULL, NULL, p2, NULL)) == NULL)
goto end;
SCFree(r);
/* With mismatched VLANs, packets should not re-assemble. */
p1->vlan_id[0] = 1;
p2->vlan_id[0] = 2;
if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)
goto end;
if ((r = Defrag(NULL, NULL, p2, NULL)) != NULL)
goto end;
/* Pass. */
ret = 1;
end:
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358 | DefragVlanTest(void)
{
Packet *p1 = NULL, *p2 = NULL, *r = NULL;
int ret = 0;
DefragInit();
p1 = BuildTestPacket(IPPROTO_ICMP, 1, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = BuildTestPacket(IPPROTO_ICMP, 1, 1, 0, 'B', 8);
if (p2 == NULL)
goto end;
/* With no VLAN IDs set, packets should re-assemble. */
if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)
goto end;
if ((r = Defrag(NULL, NULL, p2, NULL)) == NULL)
goto end;
SCFree(r);
/* With mismatched VLANs, packets should not re-assemble. */
p1->vlan_id[0] = 1;
p2->vlan_id[0] = 2;
if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)
goto end;
if ((r = Defrag(NULL, NULL, p2, NULL)) != NULL)
goto end;
/* Pass. */
ret = 1;
end:
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
DefragDestroy();
return ret;
}
| 168,306 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SoftMPEG4Encoder::~SoftMPEG4Encoder() {
ALOGV("Destruct SoftMPEG4Encoder");
releaseEncoder();
List<BufferInfo *> &outQueue = getPortQueue(1);
List<BufferInfo *> &inQueue = getPortQueue(0);
CHECK(outQueue.empty());
CHECK(inQueue.empty());
}
Commit Message: codecs: handle onReset() for a few encoders
Test: Run PoC binaries
Bug: 34749392
Bug: 34705519
Change-Id: I3356eb615b0e79272d71d72578d363671038c6dd
CWE ID: | SoftMPEG4Encoder::~SoftMPEG4Encoder() {
ALOGV("Destruct SoftMPEG4Encoder");
onReset();
releaseEncoder();
List<BufferInfo *> &outQueue = getPortQueue(1);
List<BufferInfo *> &inQueue = getPortQueue(0);
CHECK(outQueue.empty());
CHECK(inQueue.empty());
}
| 174,011 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void f2fs_wait_discard_bios(struct f2fs_sb_info *sbi)
{
__issue_discard_cmd(sbi, false);
__drop_discard_cmd(sbi);
__wait_discard_cmd(sbi, false);
}
Commit Message: f2fs: fix potential panic during fstrim
As Ju Hyung Park reported:
"When 'fstrim' is called for manual trim, a BUG() can be triggered
randomly with this patch.
I'm seeing this issue on both x86 Desktop and arm64 Android phone.
On x86 Desktop, this was caused during Ubuntu boot-up. I have a
cronjob installed which calls 'fstrim -v /' during boot. On arm64
Android, this was caused during GC looping with 1ms gc_min_sleep_time
& gc_max_sleep_time."
Root cause of this issue is that f2fs_wait_discard_bios can only be
used by f2fs_put_super, because during put_super there must be no
other referrers, so it can ignore discard entry's reference count
when removing the entry, otherwise in other caller we will hit bug_on
in __remove_discard_cmd as there may be other issuer added reference
count in discard entry.
Thread A Thread B
- issue_discard_thread
- f2fs_ioc_fitrim
- f2fs_trim_fs
- f2fs_wait_discard_bios
- __issue_discard_cmd
- __submit_discard_cmd
- __wait_discard_cmd
- dc->ref++
- __wait_one_discard_bio
- __wait_discard_cmd
- __remove_discard_cmd
- f2fs_bug_on(sbi, dc->ref)
Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de
Reported-by: Ju Hyung Park <[email protected]>
Signed-off-by: Chao Yu <[email protected]>
Signed-off-by: Jaegeuk Kim <[email protected]>
CWE ID: CWE-20 | void f2fs_wait_discard_bios(struct f2fs_sb_info *sbi)
void f2fs_wait_discard_bios(struct f2fs_sb_info *sbi, bool umount)
{
__issue_discard_cmd(sbi, false);
__drop_discard_cmd(sbi);
__wait_discard_cmd(sbi, !umount);
}
| 169,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: QString IRCView::closeToTagString(TextHtmlData* data, const QString& _tag)
{
QString ret;
QString tag;
int i = data->openHtmlTags.count() - 1;
for ( ; i >= 0 ; --i)
{
tag = data->openHtmlTags.at(i);
ret += QLatin1String("</") + tag + QLatin1Char('>');
if (tag == _tag)
{
data->openHtmlTags.removeAt(i);
break;
}
}
ret += openTags(data, i);
return ret;
}
Commit Message:
CWE ID: | QString IRCView::closeToTagString(TextHtmlData* data, const QString& _tag)
{
QString ret;
QString tag;
int i = data->openHtmlTags.count() - 1;
for ( ; i >= 0 ; --i)
{
tag = data->openHtmlTags.at(i);
ret += QLatin1String("</") + tag + QLatin1Char('>');
if (tag == _tag)
{
data->openHtmlTags.removeAt(i);
break;
}
}
if (i > -1)
ret += openTags(data, i);
return ret;
}
| 164,648 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.