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: cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h, cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count) { size_t i, maxcount; const cdf_summary_info_header_t *si = CAST(const cdf_summary_info_header_t *, sst->sst_tab); const cdf_section_declaration_t *sd = CAST(const cdf_section_declaration_t *, (const void *) ((const char *)sst->sst_tab + CDF_SECTION_DECLARATION_OFFSET)); if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 || cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1) return -1; ssi->si_byte_order = CDF_TOLE2(si->si_byte_order); ssi->si_os_version = CDF_TOLE2(si->si_os_version); ssi->si_os = CDF_TOLE2(si->si_os); ssi->si_class = si->si_class; cdf_swap_class(&ssi->si_class); ssi->si_count = CDF_TOLE2(si->si_count); *count = 0; maxcount = 0; *info = NULL; for (i = 0; i < CDF_TOLE4(si->si_count); i++) { if (i >= CDF_LOOP_LIMIT) { DPRINTF(("Unpack summary info loop limit")); errno = EFTYPE; return -1; } if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info, count, &maxcount) == -1) { return -1; } } return 0; } Commit Message: Remove loop that kept reading the same offset (Jan Kaluza) CWE ID: CWE-399
cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h, cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count) { size_t maxcount; const cdf_summary_info_header_t *si = CAST(const cdf_summary_info_header_t *, sst->sst_tab); const cdf_section_declaration_t *sd = CAST(const cdf_section_declaration_t *, (const void *) ((const char *)sst->sst_tab + CDF_SECTION_DECLARATION_OFFSET)); if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 || cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1) return -1; ssi->si_byte_order = CDF_TOLE2(si->si_byte_order); ssi->si_os_version = CDF_TOLE2(si->si_os_version); ssi->si_os = CDF_TOLE2(si->si_os); ssi->si_class = si->si_class; cdf_swap_class(&ssi->si_class); ssi->si_count = CDF_TOLE4(si->si_count); *count = 0; maxcount = 0; *info = NULL; if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info, count, &maxcount) == -1) return -1; return 0; }
166,443
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void sycc444_to_rgb(opj_image_t *img) { int *d0, *d1, *d2, *r, *g, *b; const int *y, *cb, *cr; unsigned int maxw, maxh, max, i; int offset, upb; upb = (int)img->comps[0].prec; offset = 1<<(upb - 1); upb = (1<<upb)-1; maxw = (unsigned int)img->comps[0].w; maxh = (unsigned int)img->comps[0].h; max = maxw * maxh; y = img->comps[0].data; cb = img->comps[1].data; cr = img->comps[2].data; d0 = r = (int*)malloc(sizeof(int) * (size_t)max); d1 = g = (int*)malloc(sizeof(int) * (size_t)max); d2 = b = (int*)malloc(sizeof(int) * (size_t)max); if(r == NULL || g == NULL || b == NULL) goto fails; for(i = 0U; i < max; ++i) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++cb; ++cr; ++r; ++g; ++b; } free(img->comps[0].data); img->comps[0].data = d0; free(img->comps[1].data); img->comps[1].data = d1; free(img->comps[2].data); img->comps[2].data = d2; return; fails: if(r) free(r); if(g) free(g); if(b) free(b); }/* sycc444_to_rgb() */ Commit Message: Fix Out-Of-Bounds Read in sycc42x_to_rgb function (#745) 42x Images with an odd x0/y0 lead to subsampled component starting at the 2nd column/line. That is offset = comp->dx * comp->x0 - image->x0 = 1 Fix #726 CWE ID: CWE-125
static void sycc444_to_rgb(opj_image_t *img) { int *d0, *d1, *d2, *r, *g, *b; const int *y, *cb, *cr; size_t maxw, maxh, max, i; int offset, upb; upb = (int)img->comps[0].prec; offset = 1<<(upb - 1); upb = (1<<upb)-1; maxw = (size_t)img->comps[0].w; maxh = (size_t)img->comps[0].h; max = maxw * maxh; y = img->comps[0].data; cb = img->comps[1].data; cr = img->comps[2].data; d0 = r = (int*)malloc(sizeof(int) * max); d1 = g = (int*)malloc(sizeof(int) * max); d2 = b = (int*)malloc(sizeof(int) * max); if(r == NULL || g == NULL || b == NULL) goto fails; for(i = 0U; i < max; ++i) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++cb; ++cr; ++r; ++g; ++b; } free(img->comps[0].data); img->comps[0].data = d0; free(img->comps[1].data); img->comps[1].data = d1; free(img->comps[2].data); img->comps[2].data = d2; img->color_space = OPJ_CLRSPC_SRGB; return; fails: free(r); free(g); free(b); }/* sycc444_to_rgb() */
168,841
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GraphicsContext::clipOut(const Path&) { notImplemented(); } Commit Message: Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void GraphicsContext::clipOut(const Path&) { if (paintingDisabled()) return; notImplemented(); }
170,423
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Segment::LoadCluster( long long& pos, long& len) { for (;;) { const long result = DoLoadCluster(pos, len); if (result <= 1) return result; } } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Segment::LoadCluster( if (result <= 1) return result; } } long Segment::DoLoadCluster(long long& pos, long& len) { if (m_pos < 0) return DoLoadClusterUnknownSize(pos, len); long long total, avail; long status = m_pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; long long cluster_off = -1; // offset relative to start of segment long long cluster_size = -1; // size of cluster payload for (;;) { if ((total >= 0) && (m_pos >= total)) return 1; // no more clusters if ((segment_stop >= 0) && (m_pos >= segment_stop)) return 1; // no more clusters pos = m_pos; // Read ID if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; }
174,396
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ExtensionTtsSpeakFunction::SpeechFinished() { error_ = utterance_->error(); bool success = error_.empty(); SendResponse(success); Release(); // Balanced in RunImpl(). } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ExtensionTtsSpeakFunction::SpeechFinished() {
170,390
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Ins_JMPR( INS_ARG ) { CUR.IP += (Int)(args[0]); CUR.step_ins = FALSE; * allow for simple cases here by just checking the preceding byte. * Fonts with this problem are not uncommon. */ CUR.IP -= 1; } Commit Message: CWE ID: CWE-125
static void Ins_JMPR( INS_ARG ) { if ( BOUNDS(CUR.IP + args[0], CUR.codeSize ) ) { CUR.error = TT_Err_Invalid_Reference; return; } CUR.IP += (Int)(args[0]); CUR.step_ins = FALSE; * allow for simple cases here by just checking the preceding byte. * Fonts with this problem are not uncommon. */ CUR.IP -= 1; }
164,778
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ExtensionServiceBackend::OnExtensionInstalled( const scoped_refptr<const Extension>& extension) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (frontend_.get()) frontend_->OnExtensionInstalled(extension); } Commit Message: Unrevert: Show the install dialog for the initial load of an unpacked extension with plugins. First landing broke some browser tests. BUG=83273 TEST=in the extensions managmenet page, with developer mode enabled, Load an unpacked extension on an extension with NPAPI plugins. You should get an install dialog. TBR=mihaip git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87738 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ExtensionServiceBackend::OnExtensionInstalled( void ExtensionServiceBackend::OnLoadSingleExtension( const scoped_refptr<const Extension>& extension) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (frontend_.get()) frontend_->OnLoadSingleExtension(extension); }
170,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: void FillConstant(uint8_t *data, int stride, uint8_t fill_constant) { for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { data[h * stride + w] = fill_constant; } } } 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
void FillConstant(uint8_t *data, int stride, uint8_t fill_constant) { // Sum of Absolute Differences Average. Given two blocks, and a prediction // calculate the absolute difference between one pixel and average of the // corresponding and predicted pixels; accumulate. unsigned int ReferenceSADavg(int block_idx) { unsigned int sad = 0; const uint8_t *const reference8 = GetReference(block_idx); const uint8_t *const source8 = source_data_; const uint8_t *const second_pred8 = second_pred_; #if CONFIG_VP9_HIGHBITDEPTH const uint16_t *const reference16 = CONVERT_TO_SHORTPTR(GetReference(block_idx)); const uint16_t *const source16 = CONVERT_TO_SHORTPTR(source_data_); const uint16_t *const second_pred16 = CONVERT_TO_SHORTPTR(second_pred_); #endif // CONFIG_VP9_HIGHBITDEPTH for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { if (!use_high_bit_depth_) { const int tmp = second_pred8[h * width_ + w] + reference8[h * reference_stride_ + w]; const uint8_t comp_pred = ROUND_POWER_OF_TWO(tmp, 1); sad += abs(source8[h * source_stride_ + w] - comp_pred); #if CONFIG_VP9_HIGHBITDEPTH } else { const int tmp = second_pred16[h * width_ + w] + reference16[h * reference_stride_ + w]; const uint16_t comp_pred = ROUND_POWER_OF_TWO(tmp, 1); sad += abs(source16[h * source_stride_ + w] - comp_pred); #endif // CONFIG_VP9_HIGHBITDEPTH } } } return sad; } void FillConstant(uint8_t *data, int stride, uint16_t fill_constant) { uint8_t *data8 = data; #if CONFIG_VP9_HIGHBITDEPTH uint16_t *data16 = CONVERT_TO_SHORTPTR(data); #endif // CONFIG_VP9_HIGHBITDEPTH for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { if (!use_high_bit_depth_) { data8[h * stride + w] = static_cast<uint8_t>(fill_constant); #if CONFIG_VP9_HIGHBITDEPTH } else { data16[h * stride + w] = fill_constant; #endif // CONFIG_VP9_HIGHBITDEPTH } } } }
174,571
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 read_boot(DOS_FS * fs) { struct boot_sector b; unsigned total_sectors; unsigned short logical_sector_size, sectors; unsigned fat_length; unsigned total_fat_entries; off_t data_size; fs_read(0, sizeof(b), &b); logical_sector_size = GET_UNALIGNED_W(b.sector_size); if (!logical_sector_size) die("Logical sector size is zero."); /* This was moved up because it's the first thing that will fail */ /* if the platform needs special handling of unaligned multibyte accesses */ /* but such handling isn't being provided. See GET_UNALIGNED_W() above. */ if (logical_sector_size & (SECTOR_SIZE - 1)) die("Logical sector size (%d bytes) is not a multiple of the physical " "sector size.", logical_sector_size); fs->cluster_size = b.cluster_size * logical_sector_size; if (!fs->cluster_size) die("Cluster size is zero."); if (b.fats != 2 && b.fats != 1) die("Currently, only 1 or 2 FATs are supported, not %d.\n", b.fats); fs->nfats = b.fats; sectors = GET_UNALIGNED_W(b.sectors); total_sectors = sectors ? sectors : le32toh(b.total_sect); if (verbose) printf("Checking we can access the last sector of the filesystem\n"); /* Can't access last odd sector anyway, so round down */ fs_test((off_t)((total_sectors & ~1) - 1) * logical_sector_size, logical_sector_size); fat_length = le16toh(b.fat_length) ? le16toh(b.fat_length) : le32toh(b.fat32_length); fs->fat_start = (off_t)le16toh(b.reserved) * logical_sector_size; fs->root_start = ((off_t)le16toh(b.reserved) + b.fats * fat_length) * logical_sector_size; fs->root_entries = GET_UNALIGNED_W(b.dir_entries); fs->data_start = fs->root_start + ROUND_TO_MULTIPLE(fs->root_entries << MSDOS_DIR_BITS, logical_sector_size); data_size = (off_t)total_sectors * logical_sector_size - fs->data_start; fs->data_clusters = data_size / fs->cluster_size; fs->root_cluster = 0; /* indicates standard, pre-FAT32 root dir */ fs->fsinfo_start = 0; /* no FSINFO structure */ fs->free_clusters = -1; /* unknown */ if (!b.fat_length && b.fat32_length) { fs->fat_bits = 32; fs->root_cluster = le32toh(b.root_cluster); if (!fs->root_cluster && fs->root_entries) /* M$ hasn't specified this, but it looks reasonable: If * root_cluster is 0 but there is a separate root dir * (root_entries != 0), we handle the root dir the old way. Give a * warning, but convertig to a root dir in a cluster chain seems * to complex for now... */ printf("Warning: FAT32 root dir not in cluster chain! " "Compatibility mode...\n"); else if (!fs->root_cluster && !fs->root_entries) die("No root directory!"); else if (fs->root_cluster && fs->root_entries) printf("Warning: FAT32 root dir is in a cluster chain, but " "a separate root dir\n" " area is defined. Cannot fix this easily.\n"); if (fs->data_clusters < FAT16_THRESHOLD) printf("Warning: Filesystem is FAT32 according to fat_length " "and fat32_length fields,\n" " but has only %lu clusters, less than the required " "minimum of %d.\n" " This may lead to problems on some systems.\n", (unsigned long)fs->data_clusters, FAT16_THRESHOLD); check_fat_state_bit(fs, &b); fs->backupboot_start = le16toh(b.backup_boot) * logical_sector_size; check_backup_boot(fs, &b, logical_sector_size); read_fsinfo(fs, &b, logical_sector_size); } else if (!atari_format) { /* On real MS-DOS, a 16 bit FAT is used whenever there would be too * much clusers otherwise. */ fs->fat_bits = (fs->data_clusters >= FAT12_THRESHOLD) ? 16 : 12; if (fs->data_clusters >= FAT16_THRESHOLD) die("Too many clusters (%lu) for FAT16 filesystem.", fs->data_clusters); check_fat_state_bit(fs, &b); } else { /* On Atari, things are more difficult: GEMDOS always uses 12bit FATs * on floppies, and always 16 bit on harddisks. */ fs->fat_bits = 16; /* assume 16 bit FAT for now */ /* If more clusters than fat entries in 16-bit fat, we assume * it's a real MSDOS FS with 12-bit fat. */ if (fs->data_clusters + 2 > fat_length * logical_sector_size * 8 / 16 || /* if it has one of the usual floppy sizes -> 12bit FAT */ (total_sectors == 720 || total_sectors == 1440 || total_sectors == 2880)) fs->fat_bits = 12; } /* On FAT32, the high 4 bits of a FAT entry are reserved */ fs->eff_fat_bits = (fs->fat_bits == 32) ? 28 : fs->fat_bits; fs->fat_size = fat_length * logical_sector_size; fs->label = calloc(12, sizeof(uint8_t)); if (fs->fat_bits == 12 || fs->fat_bits == 16) { struct boot_sector_16 *b16 = (struct boot_sector_16 *)&b; if (b16->extended_sig == 0x29) memmove(fs->label, b16->label, 11); else fs->label = NULL; } else if (fs->fat_bits == 32) { if (b.extended_sig == 0x29) memmove(fs->label, &b.label, 11); else fs->label = NULL; } total_fat_entries = (uint64_t)fs->fat_size * 8 / fs->fat_bits; if (fs->data_clusters > total_fat_entries - 2) die("Filesystem has %u clusters but only space for %u FAT entries.", fs->data_clusters, total_fat_entries - 2); if (!fs->root_entries && !fs->root_cluster) die("Root directory has zero size."); if (fs->root_entries & (MSDOS_DPS - 1)) die("Root directory (%d entries) doesn't span an integral number of " "sectors.", fs->root_entries); if (logical_sector_size & (SECTOR_SIZE - 1)) die("Logical sector size (%d bytes) is not a multiple of the physical " "sector size.", logical_sector_size); #if 0 /* linux kernel doesn't check that either */ /* ++roman: On Atari, these two fields are often left uninitialized */ if (!atari_format && (!b.secs_track || !b.heads)) die("Invalid disk format in boot sector."); #endif if (verbose) dump_boot(fs, &b, logical_sector_size); } Commit Message: read_boot(): Handle excessive FAT size specifications The variable used for storing the FAT size (in bytes) was an unsigned int. Since the size in sectors read from the BPB was not sufficiently checked, this could end up being zero after multiplying it with the sector size while some offsets still stayed excessive. Ultimately it would cause segfaults when accessing FAT entries for which no memory was allocated. Make it more robust by changing the types used to store FAT size to off_t and abort if there is no room for data clusters. Additionally check that FAT size is not specified as zero. Fixes #25 and fixes #26. Reported-by: Hanno Böck Signed-off-by: Andreas Bombe <[email protected]> CWE ID: CWE-119
void read_boot(DOS_FS * fs) { struct boot_sector b; unsigned total_sectors; unsigned short logical_sector_size, sectors; off_t fat_length; unsigned total_fat_entries; off_t data_size; fs_read(0, sizeof(b), &b); logical_sector_size = GET_UNALIGNED_W(b.sector_size); if (!logical_sector_size) die("Logical sector size is zero."); /* This was moved up because it's the first thing that will fail */ /* if the platform needs special handling of unaligned multibyte accesses */ /* but such handling isn't being provided. See GET_UNALIGNED_W() above. */ if (logical_sector_size & (SECTOR_SIZE - 1)) die("Logical sector size (%d bytes) is not a multiple of the physical " "sector size.", logical_sector_size); fs->cluster_size = b.cluster_size * logical_sector_size; if (!fs->cluster_size) die("Cluster size is zero."); if (b.fats != 2 && b.fats != 1) die("Currently, only 1 or 2 FATs are supported, not %d.\n", b.fats); fs->nfats = b.fats; sectors = GET_UNALIGNED_W(b.sectors); total_sectors = sectors ? sectors : le32toh(b.total_sect); if (verbose) printf("Checking we can access the last sector of the filesystem\n"); /* Can't access last odd sector anyway, so round down */ fs_test((off_t)((total_sectors & ~1) - 1) * logical_sector_size, logical_sector_size); fat_length = le16toh(b.fat_length) ? le16toh(b.fat_length) : le32toh(b.fat32_length); if (!fat_length) die("FAT size is zero."); fs->fat_start = (off_t)le16toh(b.reserved) * logical_sector_size; fs->root_start = ((off_t)le16toh(b.reserved) + b.fats * fat_length) * logical_sector_size; fs->root_entries = GET_UNALIGNED_W(b.dir_entries); fs->data_start = fs->root_start + ROUND_TO_MULTIPLE(fs->root_entries << MSDOS_DIR_BITS, logical_sector_size); data_size = (off_t)total_sectors * logical_sector_size - fs->data_start; if (data_size < fs->cluster_size) die("Filesystem has no space for any data clusters"); fs->data_clusters = data_size / fs->cluster_size; fs->root_cluster = 0; /* indicates standard, pre-FAT32 root dir */ fs->fsinfo_start = 0; /* no FSINFO structure */ fs->free_clusters = -1; /* unknown */ if (!b.fat_length && b.fat32_length) { fs->fat_bits = 32; fs->root_cluster = le32toh(b.root_cluster); if (!fs->root_cluster && fs->root_entries) /* M$ hasn't specified this, but it looks reasonable: If * root_cluster is 0 but there is a separate root dir * (root_entries != 0), we handle the root dir the old way. Give a * warning, but convertig to a root dir in a cluster chain seems * to complex for now... */ printf("Warning: FAT32 root dir not in cluster chain! " "Compatibility mode...\n"); else if (!fs->root_cluster && !fs->root_entries) die("No root directory!"); else if (fs->root_cluster && fs->root_entries) printf("Warning: FAT32 root dir is in a cluster chain, but " "a separate root dir\n" " area is defined. Cannot fix this easily.\n"); if (fs->data_clusters < FAT16_THRESHOLD) printf("Warning: Filesystem is FAT32 according to fat_length " "and fat32_length fields,\n" " but has only %lu clusters, less than the required " "minimum of %d.\n" " This may lead to problems on some systems.\n", (unsigned long)fs->data_clusters, FAT16_THRESHOLD); check_fat_state_bit(fs, &b); fs->backupboot_start = le16toh(b.backup_boot) * logical_sector_size; check_backup_boot(fs, &b, logical_sector_size); read_fsinfo(fs, &b, logical_sector_size); } else if (!atari_format) { /* On real MS-DOS, a 16 bit FAT is used whenever there would be too * much clusers otherwise. */ fs->fat_bits = (fs->data_clusters >= FAT12_THRESHOLD) ? 16 : 12; if (fs->data_clusters >= FAT16_THRESHOLD) die("Too many clusters (%lu) for FAT16 filesystem.", fs->data_clusters); check_fat_state_bit(fs, &b); } else { /* On Atari, things are more difficult: GEMDOS always uses 12bit FATs * on floppies, and always 16 bit on harddisks. */ fs->fat_bits = 16; /* assume 16 bit FAT for now */ /* If more clusters than fat entries in 16-bit fat, we assume * it's a real MSDOS FS with 12-bit fat. */ if (fs->data_clusters + 2 > fat_length * logical_sector_size * 8 / 16 || /* if it has one of the usual floppy sizes -> 12bit FAT */ (total_sectors == 720 || total_sectors == 1440 || total_sectors == 2880)) fs->fat_bits = 12; } /* On FAT32, the high 4 bits of a FAT entry are reserved */ fs->eff_fat_bits = (fs->fat_bits == 32) ? 28 : fs->fat_bits; fs->fat_size = fat_length * logical_sector_size; fs->label = calloc(12, sizeof(uint8_t)); if (fs->fat_bits == 12 || fs->fat_bits == 16) { struct boot_sector_16 *b16 = (struct boot_sector_16 *)&b; if (b16->extended_sig == 0x29) memmove(fs->label, b16->label, 11); else fs->label = NULL; } else if (fs->fat_bits == 32) { if (b.extended_sig == 0x29) memmove(fs->label, &b.label, 11); else fs->label = NULL; } total_fat_entries = (uint64_t)fs->fat_size * 8 / fs->fat_bits; if (fs->data_clusters > total_fat_entries - 2) die("Filesystem has %u clusters but only space for %u FAT entries.", fs->data_clusters, total_fat_entries - 2); if (!fs->root_entries && !fs->root_cluster) die("Root directory has zero size."); if (fs->root_entries & (MSDOS_DPS - 1)) die("Root directory (%d entries) doesn't span an integral number of " "sectors.", fs->root_entries); if (logical_sector_size & (SECTOR_SIZE - 1)) die("Logical sector size (%d bytes) is not a multiple of the physical " "sector size.", logical_sector_size); #if 0 /* linux kernel doesn't check that either */ /* ++roman: On Atari, these two fields are often left uninitialized */ if (!atari_format && (!b.secs_track || !b.heads)) die("Invalid disk format in boot sector."); #endif if (verbose) dump_boot(fs, &b, logical_sector_size); }
167,232
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebsiteSettings* website_settings() { if (!website_settings_.get()) { website_settings_.reset(new WebsiteSettings( mock_ui(), profile(), tab_specific_content_settings(), infobar_service(), url(), ssl(), cert_store())); } return website_settings_.get(); } Commit Message: Fix UAF in Origin Info Bubble and permission settings UI. In addition to fixing the UAF, will this also fix the problem of the bubble showing over the previous tab (if the bubble is open when the tab it was opened for closes). BUG=490492 TBR=tedchoc Review URL: https://codereview.chromium.org/1317443002 Cr-Commit-Position: refs/heads/master@{#346023} CWE ID:
WebsiteSettings* website_settings() { if (!website_settings_.get()) { website_settings_.reset(new WebsiteSettings( mock_ui(), profile(), tab_specific_content_settings(), web_contents(), url(), ssl(), cert_store())); } return website_settings_.get(); }
171,782
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 netbk_set_skb_gso(struct xenvif *vif, struct sk_buff *skb, struct xen_netif_extra_info *gso) { if (!gso->u.gso.size) { netdev_dbg(vif->dev, "GSO size must not be zero.\n"); return -EINVAL; } /* Currently only TCPv4 S.O. is supported. */ if (gso->u.gso.type != XEN_NETIF_GSO_TYPE_TCPV4) { netdev_dbg(vif->dev, "Bad GSO type %d.\n", gso->u.gso.type); return -EINVAL; } skb_shinfo(skb)->gso_size = gso->u.gso.size; skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4; /* Header must be checked, and gso_segs computed. */ skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY; skb_shinfo(skb)->gso_segs = 0; return 0; } Commit Message: xen/netback: shutdown the ring if it contains garbage. A buggy or malicious frontend should not be able to confuse netback. If we spot anything which is not as it should be then shutdown the device and don't try to continue with the ring in a potentially hostile state. Well behaved and non-hostile frontends will not be penalised. As well as making the existing checks for such errors fatal also add a new check that ensures that there isn't an insane number of requests on the ring (i.e. more than would fit in the ring). If the ring contains garbage then previously is was possible to loop over this insane number, getting an error each time and therefore not generating any more pending requests and therefore not exiting the loop in xen_netbk_tx_build_gops for an externded period. Also turn various netdev_dbg calls which no precipitate a fatal error into netdev_err, they are rate limited because the device is shutdown afterwards. This fixes at least one known DoS/softlockup of the backend domain. Signed-off-by: Ian Campbell <[email protected]> Reviewed-by: Konrad Rzeszutek Wilk <[email protected]> Acked-by: Jan Beulich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
static int netbk_set_skb_gso(struct xenvif *vif, struct sk_buff *skb, struct xen_netif_extra_info *gso) { if (!gso->u.gso.size) { netdev_err(vif->dev, "GSO size must not be zero.\n"); netbk_fatal_tx_err(vif); return -EINVAL; } /* Currently only TCPv4 S.O. is supported. */ if (gso->u.gso.type != XEN_NETIF_GSO_TYPE_TCPV4) { netdev_err(vif->dev, "Bad GSO type %d.\n", gso->u.gso.type); netbk_fatal_tx_err(vif); return -EINVAL; } skb_shinfo(skb)->gso_size = gso->u.gso.size; skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4; /* Header must be checked, and gso_segs computed. */ skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY; skb_shinfo(skb)->gso_segs = 0; return 0; }
166,173
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 InspectorNetworkAgent::DidReceiveResourceResponse( unsigned long identifier, DocumentLoader* loader, const ResourceResponse& response, Resource* cached_resource) { String request_id = IdentifiersFactory::RequestId(identifier); bool is_not_modified = response.HttpStatusCode() == 304; bool resource_is_empty = true; std::unique_ptr<protocol::Network::Response> resource_response = BuildObjectForResourceResponse(response, cached_resource, &resource_is_empty); InspectorPageAgent::ResourceType type = cached_resource ? InspectorPageAgent::CachedResourceType(*cached_resource) : InspectorPageAgent::kOtherResource; InspectorPageAgent::ResourceType saved_type = resources_data_->GetResourceType(request_id); if (saved_type == InspectorPageAgent::kScriptResource || saved_type == InspectorPageAgent::kXHRResource || saved_type == InspectorPageAgent::kDocumentResource || saved_type == InspectorPageAgent::kFetchResource || saved_type == InspectorPageAgent::kEventSourceResource) { type = saved_type; } if (type == InspectorPageAgent::kDocumentResource && loader && loader->GetSubstituteData().IsValid()) return; if (cached_resource) resources_data_->AddResource(request_id, cached_resource); String frame_id = loader && loader->GetFrame() ? IdentifiersFactory::FrameId(loader->GetFrame()) : ""; String loader_id = loader ? IdentifiersFactory::LoaderId(loader) : ""; resources_data_->ResponseReceived(request_id, frame_id, response); resources_data_->SetResourceType(request_id, type); if (response.GetSecurityStyle() != ResourceResponse::kSecurityStyleUnknown && response.GetSecurityStyle() != ResourceResponse::kSecurityStyleUnauthenticated) { const ResourceResponse::SecurityDetails* response_security_details = response.GetSecurityDetails(); resources_data_->SetCertificate(request_id, response_security_details->certificate); } if (resource_response && !resource_is_empty) { Maybe<String> maybe_frame_id; if (!frame_id.IsEmpty()) maybe_frame_id = frame_id; GetFrontend()->responseReceived( request_id, loader_id, MonotonicallyIncreasingTime(), InspectorPageAgent::ResourceTypeJson(type), std::move(resource_response), std::move(maybe_frame_id)); } if (is_not_modified && cached_resource && cached_resource->EncodedSize()) DidReceiveData(identifier, loader, 0, cached_resource->EncodedSize()); } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
void InspectorNetworkAgent::DidReceiveResourceResponse( unsigned long identifier, DocumentLoader* loader, const ResourceResponse& response, Resource* cached_resource) { String request_id = IdentifiersFactory::RequestId(identifier); bool is_not_modified = response.HttpStatusCode() == 304; bool resource_is_empty = true; std::unique_ptr<protocol::Network::Response> resource_response = BuildObjectForResourceResponse(response, cached_resource, &resource_is_empty); InspectorPageAgent::ResourceType type = cached_resource ? InspectorPageAgent::ToResourceType(cached_resource->GetType()) : InspectorPageAgent::kOtherResource; InspectorPageAgent::ResourceType saved_type = resources_data_->GetResourceType(request_id); if (saved_type == InspectorPageAgent::kScriptResource || saved_type == InspectorPageAgent::kXHRResource || saved_type == InspectorPageAgent::kDocumentResource || saved_type == InspectorPageAgent::kFetchResource || saved_type == InspectorPageAgent::kEventSourceResource) { type = saved_type; } if (type == InspectorPageAgent::kDocumentResource && loader && loader->GetSubstituteData().IsValid()) return; if (cached_resource) resources_data_->AddResource(request_id, cached_resource); String frame_id = loader && loader->GetFrame() ? IdentifiersFactory::FrameId(loader->GetFrame()) : ""; String loader_id = loader ? IdentifiersFactory::LoaderId(loader) : ""; resources_data_->ResponseReceived(request_id, frame_id, response); resources_data_->SetResourceType(request_id, type); if (response.GetSecurityStyle() != ResourceResponse::kSecurityStyleUnknown && response.GetSecurityStyle() != ResourceResponse::kSecurityStyleUnauthenticated) { const ResourceResponse::SecurityDetails* response_security_details = response.GetSecurityDetails(); resources_data_->SetCertificate(request_id, response_security_details->certificate); } if (resource_response && !resource_is_empty) { Maybe<String> maybe_frame_id; if (!frame_id.IsEmpty()) maybe_frame_id = frame_id; GetFrontend()->responseReceived( request_id, loader_id, MonotonicallyIncreasingTime(), InspectorPageAgent::ResourceTypeJson(type), std::move(resource_response), std::move(maybe_frame_id)); } if (is_not_modified && cached_resource && cached_resource->EncodedSize()) DidReceiveData(identifier, loader, 0, cached_resource->EncodedSize()); }
172,466
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: base::string16 FormatBookmarkURLForDisplay(const GURL& url) { return url_formatter::FormatUrl( url, url_formatter::kFormatUrlOmitAll & ~url_formatter::kFormatUrlOmitUsernamePassword, net::UnescapeRule::SPACES, nullptr, nullptr, nullptr); } Commit Message: Prevent interpretating userinfo as url scheme when editing bookmarks Chrome's Edit Bookmark dialog formats urls for display such that a url of http://javascript:[email protected] is later converted to a javascript url scheme, allowing persistence of a script injection attack within the user's bookmarks. This fix prevents such misinterpretations by always showing the scheme when a userinfo component is present within the url. BUG=639126 Review-Url: https://codereview.chromium.org/2368593002 Cr-Commit-Position: refs/heads/master@{#422467} CWE ID: CWE-79
base::string16 FormatBookmarkURLForDisplay(const GURL& url) { // and trailing slash, and unescape most characters. However, it's url_formatter::FormatUrlTypes format_types = url_formatter::kFormatUrlOmitAll & ~url_formatter::kFormatUrlOmitUsernamePassword; // If username is present, we must not omit the scheme because FixupURL() will // subsequently interpret the username as a scheme. crbug.com/639126 if (url.has_username()) format_types &= ~url_formatter::kFormatUrlOmitHTTP; return url_formatter::FormatUrl(url, format_types, net::UnescapeRule::SPACES, nullptr, nullptr, nullptr); }
172,103
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 handle_rx(struct vhost_net *net) { struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_RX]; struct vhost_virtqueue *vq = &nvq->vq; unsigned uninitialized_var(in), log; struct vhost_log *vq_log; struct msghdr msg = { .msg_name = NULL, .msg_namelen = 0, .msg_control = NULL, /* FIXME: get and handle RX aux data. */ .msg_controllen = 0, .msg_iov = vq->iov, .msg_flags = MSG_DONTWAIT, }; struct virtio_net_hdr_mrg_rxbuf hdr = { .hdr.flags = 0, .hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE }; size_t total_len = 0; int err, mergeable; s16 headcount; size_t vhost_hlen, sock_hlen; size_t vhost_len, sock_len; struct socket *sock; mutex_lock(&vq->mutex); sock = vq->private_data; if (!sock) goto out; vhost_disable_notify(&net->dev, vq); vhost_hlen = nvq->vhost_hlen; sock_hlen = nvq->sock_hlen; vq_log = unlikely(vhost_has_feature(&net->dev, VHOST_F_LOG_ALL)) ? vq->log : NULL; mergeable = vhost_has_feature(&net->dev, VIRTIO_NET_F_MRG_RXBUF); while ((sock_len = peek_head_len(sock->sk))) { sock_len += sock_hlen; vhost_len = sock_len + vhost_hlen; headcount = get_rx_bufs(vq, vq->heads, vhost_len, &in, vq_log, &log, likely(mergeable) ? UIO_MAXIOV : 1); /* On error, stop handling until the next kick. */ if (unlikely(headcount < 0)) break; /* OK, now we need to know about added descriptors. */ if (!headcount) { if (unlikely(vhost_enable_notify(&net->dev, vq))) { /* They have slipped one in as we were * doing that: check again. */ vhost_disable_notify(&net->dev, vq); continue; } /* Nothing new? Wait for eventfd to tell us * they refilled. */ break; } /* We don't need to be notified again. */ if (unlikely((vhost_hlen))) /* Skip header. TODO: support TSO. */ move_iovec_hdr(vq->iov, nvq->hdr, vhost_hlen, in); else /* Copy the header for use in VIRTIO_NET_F_MRG_RXBUF: * needed because recvmsg can modify msg_iov. */ copy_iovec_hdr(vq->iov, nvq->hdr, sock_hlen, in); msg.msg_iovlen = in; err = sock->ops->recvmsg(NULL, sock, &msg, sock_len, MSG_DONTWAIT | MSG_TRUNC); /* Userspace might have consumed the packet meanwhile: * it's not supposed to do this usually, but might be hard * to prevent. Discard data we got (if any) and keep going. */ if (unlikely(err != sock_len)) { pr_debug("Discarded rx packet: " " len %d, expected %zd\n", err, sock_len); vhost_discard_vq_desc(vq, headcount); continue; } if (unlikely(vhost_hlen) && memcpy_toiovecend(nvq->hdr, (unsigned char *)&hdr, 0, vhost_hlen)) { vq_err(vq, "Unable to write vnet_hdr at addr %p\n", vq->iov->iov_base); break; } /* TODO: Should check and handle checksum. */ if (likely(mergeable) && memcpy_toiovecend(nvq->hdr, (unsigned char *)&headcount, offsetof(typeof(hdr), num_buffers), sizeof hdr.num_buffers)) { vq_err(vq, "Failed num_buffers write"); vhost_discard_vq_desc(vq, headcount); break; } vhost_add_used_and_signal_n(&net->dev, vq, vq->heads, headcount); if (unlikely(vq_log)) vhost_log_write(vq, vq_log, log, vhost_len); total_len += vhost_len; if (unlikely(total_len >= VHOST_NET_WEIGHT)) { vhost_poll_queue(&vq->poll); break; } } out: mutex_unlock(&vq->mutex); } Commit Message: vhost: fix total length when packets are too short When mergeable buffers are disabled, and the incoming packet is too large for the rx buffer, get_rx_bufs returns success. This was intentional in order for make recvmsg truncate the packet and then handle_rx would detect err != sock_len and drop it. Unfortunately we pass the original sock_len to recvmsg - which means we use parts of iov not fully validated. Fix this up by detecting this overrun and doing packet drop immediately. CVE-2014-0077 Signed-off-by: Michael S. Tsirkin <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
static void handle_rx(struct vhost_net *net) { struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_RX]; struct vhost_virtqueue *vq = &nvq->vq; unsigned uninitialized_var(in), log; struct vhost_log *vq_log; struct msghdr msg = { .msg_name = NULL, .msg_namelen = 0, .msg_control = NULL, /* FIXME: get and handle RX aux data. */ .msg_controllen = 0, .msg_iov = vq->iov, .msg_flags = MSG_DONTWAIT, }; struct virtio_net_hdr_mrg_rxbuf hdr = { .hdr.flags = 0, .hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE }; size_t total_len = 0; int err, mergeable; s16 headcount; size_t vhost_hlen, sock_hlen; size_t vhost_len, sock_len; struct socket *sock; mutex_lock(&vq->mutex); sock = vq->private_data; if (!sock) goto out; vhost_disable_notify(&net->dev, vq); vhost_hlen = nvq->vhost_hlen; sock_hlen = nvq->sock_hlen; vq_log = unlikely(vhost_has_feature(&net->dev, VHOST_F_LOG_ALL)) ? vq->log : NULL; mergeable = vhost_has_feature(&net->dev, VIRTIO_NET_F_MRG_RXBUF); while ((sock_len = peek_head_len(sock->sk))) { sock_len += sock_hlen; vhost_len = sock_len + vhost_hlen; headcount = get_rx_bufs(vq, vq->heads, vhost_len, &in, vq_log, &log, likely(mergeable) ? UIO_MAXIOV : 1); /* On error, stop handling until the next kick. */ if (unlikely(headcount < 0)) break; /* On overrun, truncate and discard */ if (unlikely(headcount > UIO_MAXIOV)) { msg.msg_iovlen = 1; err = sock->ops->recvmsg(NULL, sock, &msg, 1, MSG_DONTWAIT | MSG_TRUNC); pr_debug("Discarded rx packet: len %zd\n", sock_len); continue; } /* OK, now we need to know about added descriptors. */ if (!headcount) { if (unlikely(vhost_enable_notify(&net->dev, vq))) { /* They have slipped one in as we were * doing that: check again. */ vhost_disable_notify(&net->dev, vq); continue; } /* Nothing new? Wait for eventfd to tell us * they refilled. */ break; } /* We don't need to be notified again. */ if (unlikely((vhost_hlen))) /* Skip header. TODO: support TSO. */ move_iovec_hdr(vq->iov, nvq->hdr, vhost_hlen, in); else /* Copy the header for use in VIRTIO_NET_F_MRG_RXBUF: * needed because recvmsg can modify msg_iov. */ copy_iovec_hdr(vq->iov, nvq->hdr, sock_hlen, in); msg.msg_iovlen = in; err = sock->ops->recvmsg(NULL, sock, &msg, sock_len, MSG_DONTWAIT | MSG_TRUNC); /* Userspace might have consumed the packet meanwhile: * it's not supposed to do this usually, but might be hard * to prevent. Discard data we got (if any) and keep going. */ if (unlikely(err != sock_len)) { pr_debug("Discarded rx packet: " " len %d, expected %zd\n", err, sock_len); vhost_discard_vq_desc(vq, headcount); continue; } if (unlikely(vhost_hlen) && memcpy_toiovecend(nvq->hdr, (unsigned char *)&hdr, 0, vhost_hlen)) { vq_err(vq, "Unable to write vnet_hdr at addr %p\n", vq->iov->iov_base); break; } /* TODO: Should check and handle checksum. */ if (likely(mergeable) && memcpy_toiovecend(nvq->hdr, (unsigned char *)&headcount, offsetof(typeof(hdr), num_buffers), sizeof hdr.num_buffers)) { vq_err(vq, "Failed num_buffers write"); vhost_discard_vq_desc(vq, headcount); break; } vhost_add_used_and_signal_n(&net->dev, vq, vq->heads, headcount); if (unlikely(vq_log)) vhost_log_write(vq, vq_log, log, vhost_len); total_len += vhost_len; if (unlikely(total_len >= VHOST_NET_WEIGHT)) { vhost_poll_queue(&vq->poll); break; } } out: mutex_unlock(&vq->mutex); }
166,461
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_expand_gray_1_2_4_to_8_mod( PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { image_transform_png_set_expand_mod(this, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_expand_gray_1_2_4_to_8_mod( const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { #if PNG_LIBPNG_VER < 10700 image_transform_png_set_expand_mod(this, that, pp, display); #else /* Only expand grayscale of bit depth less than 8: */ if (that->colour_type == PNG_COLOR_TYPE_GRAY && that->bit_depth < 8) that->sample_depth = that->bit_depth = 8; this->next->mod(this->next, that, pp, display); #endif /* 1.7 or later */ }
173,631
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void InspectorTraceEvents::WillSendRequest( ExecutionContext*, unsigned long identifier, DocumentLoader* loader, ResourceRequest& request, const ResourceResponse& redirect_response, const FetchInitiatorInfo&) { LocalFrame* frame = loader ? loader->GetFrame() : nullptr; TRACE_EVENT_INSTANT1( "devtools.timeline", "ResourceSendRequest", TRACE_EVENT_SCOPE_THREAD, "data", InspectorSendRequestEvent::Data(identifier, frame, request)); probe::AsyncTaskScheduled(frame ? frame->GetDocument() : nullptr, "SendRequest", AsyncId(identifier)); } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
void InspectorTraceEvents::WillSendRequest( ExecutionContext*, unsigned long identifier, DocumentLoader* loader, ResourceRequest& request, const ResourceResponse& redirect_response, const FetchInitiatorInfo&, Resource::Type) { LocalFrame* frame = loader ? loader->GetFrame() : nullptr; TRACE_EVENT_INSTANT1( "devtools.timeline", "ResourceSendRequest", TRACE_EVENT_SCOPE_THREAD, "data", InspectorSendRequestEvent::Data(identifier, frame, request)); probe::AsyncTaskScheduled(frame ? frame->GetDocument() : nullptr, "SendRequest", AsyncId(identifier)); }
172,471
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *Sys_LoadDll(const char *name, qboolean useSystemLib) { void *dllhandle; if(useSystemLib) Com_Printf("Trying to load \"%s\"...\n", name); if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name))) { const char *topDir; char libPath[MAX_OSPATH]; topDir = Sys_BinaryPath(); if(!*topDir) topDir = "."; Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name); if(!(dllhandle = Sys_LoadLibrary(libPath))) { const char *basePath = Cvar_VariableString("fs_basepath"); if(!basePath || !*basePath) basePath = "."; if(FS_FilenameCompare(topDir, basePath)) { Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name); dllhandle = Sys_LoadLibrary(libPath); } if(!dllhandle) Com_Printf("Loading \"%s\" failed\n", name); } } return dllhandle; } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269
void *Sys_LoadDll(const char *name, qboolean useSystemLib) { void *dllhandle; // Don't load any DLLs that end with the pk3 extension if (COM_CompareExtension(name, ".pk3")) { Com_Printf("Rejecting DLL named \"%s\"", name); return NULL; } if(useSystemLib) Com_Printf("Trying to load \"%s\"...\n", name); if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name))) { const char *topDir; char libPath[MAX_OSPATH]; topDir = Sys_BinaryPath(); if(!*topDir) topDir = "."; Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name); if(!(dllhandle = Sys_LoadLibrary(libPath))) { const char *basePath = Cvar_VariableString("fs_basepath"); if(!basePath || !*basePath) basePath = "."; if(FS_FilenameCompare(topDir, basePath)) { Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name); dllhandle = Sys_LoadLibrary(libPath); } if(!dllhandle) Com_Printf("Loading \"%s\" failed\n", name); } } return dllhandle; }
170,084
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GpuCommandBufferStub::OnCreateVideoDecoder( media::VideoCodecProfile profile, IPC::Message* reply_message) { int decoder_route_id = channel_->GenerateRouteID(); GpuCommandBufferMsg_CreateVideoDecoder::WriteReplyParams( reply_message, decoder_route_id); GpuVideoDecodeAccelerator* decoder = new GpuVideoDecodeAccelerator(this, decoder_route_id, this); video_decoders_.AddWithID(decoder, decoder_route_id); channel_->AddRoute(decoder_route_id, decoder); decoder->Initialize(profile, reply_message, channel_->renderer_process()); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuCommandBufferStub::OnCreateVideoDecoder( media::VideoCodecProfile profile, IPC::Message* reply_message) { int decoder_route_id = channel_->GenerateRouteID(); GpuCommandBufferMsg_CreateVideoDecoder::WriteReplyParams( reply_message, decoder_route_id); GpuVideoDecodeAccelerator* decoder = new GpuVideoDecodeAccelerator(this, decoder_route_id, this); video_decoders_.AddWithID(decoder, decoder_route_id); channel_->AddRoute(decoder_route_id, decoder); decoder->Initialize(profile, reply_message); }
170,936
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void __nfs4_close(struct path *path, struct nfs4_state *state, mode_t mode, int wait) { struct nfs4_state_owner *owner = state->owner; int call_close = 0; int newstate; atomic_inc(&owner->so_count); /* Protect against nfs4_find_state() */ spin_lock(&owner->so_lock); switch (mode & (FMODE_READ | FMODE_WRITE)) { case FMODE_READ: state->n_rdonly--; break; case FMODE_WRITE: state->n_wronly--; break; case FMODE_READ|FMODE_WRITE: state->n_rdwr--; } newstate = FMODE_READ|FMODE_WRITE; if (state->n_rdwr == 0) { if (state->n_rdonly == 0) { newstate &= ~FMODE_READ; call_close |= test_bit(NFS_O_RDONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (state->n_wronly == 0) { newstate &= ~FMODE_WRITE; call_close |= test_bit(NFS_O_WRONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (newstate == 0) clear_bit(NFS_DELEGATED_STATE, &state->flags); } nfs4_state_set_mode_locked(state, newstate); spin_unlock(&owner->so_lock); if (!call_close) { nfs4_put_open_state(state); nfs4_put_state_owner(owner); } else nfs4_do_close(path, state, wait); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static void __nfs4_close(struct path *path, struct nfs4_state *state, mode_t mode, int wait) static void __nfs4_close(struct path *path, struct nfs4_state *state, fmode_t fmode, int wait) { struct nfs4_state_owner *owner = state->owner; int call_close = 0; fmode_t newstate; atomic_inc(&owner->so_count); /* Protect against nfs4_find_state() */ spin_lock(&owner->so_lock); switch (fmode & (FMODE_READ | FMODE_WRITE)) { case FMODE_READ: state->n_rdonly--; break; case FMODE_WRITE: state->n_wronly--; break; case FMODE_READ|FMODE_WRITE: state->n_rdwr--; } newstate = FMODE_READ|FMODE_WRITE; if (state->n_rdwr == 0) { if (state->n_rdonly == 0) { newstate &= ~FMODE_READ; call_close |= test_bit(NFS_O_RDONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (state->n_wronly == 0) { newstate &= ~FMODE_WRITE; call_close |= test_bit(NFS_O_WRONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (newstate == 0) clear_bit(NFS_DELEGATED_STATE, &state->flags); } nfs4_state_set_mode_locked(state, newstate); spin_unlock(&owner->so_lock); if (!call_close) { nfs4_put_open_state(state); nfs4_put_state_owner(owner); } else nfs4_do_close(path, state, wait); }
165,709
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebPreferences::Apply(WebView* web_view) const { WebSettings* settings = web_view->settings(); ApplyFontsFromMap(standard_font_family_map, setStandardFontFamilyWrapper, settings); ApplyFontsFromMap(fixed_font_family_map, setFixedFontFamilyWrapper, settings); ApplyFontsFromMap(serif_font_family_map, setSerifFontFamilyWrapper, settings); ApplyFontsFromMap(sans_serif_font_family_map, setSansSerifFontFamilyWrapper, settings); ApplyFontsFromMap(cursive_font_family_map, setCursiveFontFamilyWrapper, settings); ApplyFontsFromMap(fantasy_font_family_map, setFantasyFontFamilyWrapper, settings); ApplyFontsFromMap(pictograph_font_family_map, setPictographFontFamilyWrapper, settings); settings->setDefaultFontSize(default_font_size); settings->setDefaultFixedFontSize(default_fixed_font_size); settings->setMinimumFontSize(minimum_font_size); settings->setMinimumLogicalFontSize(minimum_logical_font_size); settings->setDefaultTextEncodingName(ASCIIToUTF16(default_encoding)); settings->setApplyDefaultDeviceScaleFactorInCompositor( apply_default_device_scale_factor_in_compositor); settings->setApplyPageScaleFactorInCompositor( apply_page_scale_factor_in_compositor); settings->setPerTilePaintingEnabled(per_tile_painting_enabled); settings->setAcceleratedAnimationEnabled(accelerated_animation_enabled); settings->setJavaScriptEnabled(javascript_enabled); settings->setWebSecurityEnabled(web_security_enabled); settings->setJavaScriptCanOpenWindowsAutomatically( javascript_can_open_windows_automatically); settings->setLoadsImagesAutomatically(loads_images_automatically); settings->setImagesEnabled(images_enabled); settings->setPluginsEnabled(plugins_enabled); settings->setDOMPasteAllowed(dom_paste_enabled); settings->setDeveloperExtrasEnabled(developer_extras_enabled); settings->setNeedsSiteSpecificQuirks(site_specific_quirks_enabled); settings->setShrinksStandaloneImagesToFit(shrinks_standalone_images_to_fit); settings->setUsesEncodingDetector(uses_universal_detector); settings->setTextAreasAreResizable(text_areas_are_resizable); settings->setAllowScriptsToCloseWindows(allow_scripts_to_close_windows); if (user_style_sheet_enabled) settings->setUserStyleSheetLocation(user_style_sheet_location); else settings->setUserStyleSheetLocation(WebURL()); settings->setAuthorAndUserStylesEnabled(author_and_user_styles_enabled); settings->setUsesPageCache(uses_page_cache); settings->setPageCacheSupportsPlugins(page_cache_supports_plugins); settings->setDownloadableBinaryFontsEnabled(remote_fonts_enabled); settings->setJavaScriptCanAccessClipboard(javascript_can_access_clipboard); settings->setXSSAuditorEnabled(xss_auditor_enabled); settings->setDNSPrefetchingEnabled(dns_prefetching_enabled); settings->setLocalStorageEnabled(local_storage_enabled); settings->setSyncXHRInDocumentsEnabled(sync_xhr_in_documents_enabled); WebRuntimeFeatures::enableDatabase(databases_enabled); settings->setOfflineWebApplicationCacheEnabled(application_cache_enabled); settings->setCaretBrowsingEnabled(caret_browsing_enabled); settings->setHyperlinkAuditingEnabled(hyperlink_auditing_enabled); settings->setCookieEnabled(cookie_enabled); settings->setEditableLinkBehaviorNeverLive(); settings->setFrameFlatteningEnabled(frame_flattening_enabled); settings->setFontRenderingModeNormal(); settings->setJavaEnabled(java_enabled); settings->setAllowUniversalAccessFromFileURLs( allow_universal_access_from_file_urls); settings->setAllowFileAccessFromFileURLs(allow_file_access_from_file_urls); settings->setTextDirectionSubmenuInclusionBehaviorNeverIncluded(); settings->setWebAudioEnabled(webaudio_enabled); settings->setExperimentalWebGLEnabled(experimental_webgl_enabled); settings->setOpenGLMultisamplingEnabled(gl_multisampling_enabled); settings->setPrivilegedWebGLExtensionsEnabled( privileged_webgl_extensions_enabled); settings->setWebGLErrorsToConsoleEnabled(webgl_errors_to_console_enabled); settings->setShowDebugBorders(show_composited_layer_borders); settings->setShowFPSCounter(show_fps_counter); settings->setAcceleratedCompositingForOverflowScrollEnabled( accelerated_compositing_for_overflow_scroll_enabled); settings->setAcceleratedCompositingForScrollableFramesEnabled( accelerated_compositing_for_scrollable_frames_enabled); settings->setCompositedScrollingForFramesEnabled( composited_scrolling_for_frames_enabled); settings->setShowPlatformLayerTree(show_composited_layer_tree); settings->setShowPaintRects(show_paint_rects); settings->setRenderVSyncEnabled(render_vsync_enabled); settings->setAcceleratedCompositingEnabled(accelerated_compositing_enabled); settings->setAcceleratedCompositingForFixedPositionEnabled( fixed_position_compositing_enabled); settings->setAccelerated2dCanvasEnabled(accelerated_2d_canvas_enabled); settings->setDeferred2dCanvasEnabled(deferred_2d_canvas_enabled); settings->setAntialiased2dCanvasEnabled(!antialiased_2d_canvas_disabled); settings->setAcceleratedPaintingEnabled(accelerated_painting_enabled); settings->setAcceleratedFiltersEnabled(accelerated_filters_enabled); settings->setGestureTapHighlightEnabled(gesture_tap_highlight_enabled); settings->setAcceleratedCompositingFor3DTransformsEnabled( accelerated_compositing_for_3d_transforms_enabled); settings->setAcceleratedCompositingForVideoEnabled( accelerated_compositing_for_video_enabled); settings->setAcceleratedCompositingForAnimationEnabled( accelerated_compositing_for_animation_enabled); settings->setAcceleratedCompositingForPluginsEnabled( accelerated_compositing_for_plugins_enabled); settings->setAcceleratedCompositingForCanvasEnabled( experimental_webgl_enabled || accelerated_2d_canvas_enabled); settings->setMemoryInfoEnabled(memory_info_enabled); settings->setAsynchronousSpellCheckingEnabled( asynchronous_spell_checking_enabled); settings->setUnifiedTextCheckerEnabled(unified_textchecker_enabled); for (WebInspectorPreferences::const_iterator it = inspector_settings.begin(); it != inspector_settings.end(); ++it) web_view->setInspectorSetting(WebString::fromUTF8(it->first), WebString::fromUTF8(it->second)); web_view->setTabsToLinks(tabs_to_links); settings->setInteractiveFormValidationEnabled(true); settings->setFullScreenEnabled(fullscreen_enabled); settings->setAllowDisplayOfInsecureContent(allow_displaying_insecure_content); settings->setAllowRunningOfInsecureContent(allow_running_insecure_content); settings->setPasswordEchoEnabled(password_echo_enabled); settings->setShouldPrintBackgrounds(should_print_backgrounds); settings->setEnableScrollAnimator(enable_scroll_animator); settings->setVisualWordMovementEnabled(visual_word_movement_enabled); settings->setCSSStickyPositionEnabled(css_sticky_position_enabled); settings->setExperimentalCSSCustomFilterEnabled(css_shaders_enabled); settings->setExperimentalCSSVariablesEnabled(css_variables_enabled); settings->setExperimentalCSSGridLayoutEnabled(css_grid_layout_enabled); WebRuntimeFeatures::enableTouch(touch_enabled); settings->setDeviceSupportsTouch(device_supports_touch); settings->setDeviceSupportsMouse(device_supports_mouse); settings->setEnableTouchAdjustment(touch_adjustment_enabled); settings->setDefaultTileSize( WebSize(default_tile_width, default_tile_height)); settings->setMaxUntiledLayerSize( WebSize(max_untiled_layer_width, max_untiled_layer_height)); settings->setFixedPositionCreatesStackingContext( fixed_position_creates_stacking_context); settings->setDeferredImageDecodingEnabled(deferred_image_decoding_enabled); settings->setShouldRespectImageOrientation(should_respect_image_orientation); settings->setEditingBehavior( static_cast<WebSettings::EditingBehavior>(editing_behavior)); settings->setSupportsMultipleWindows(supports_multiple_windows); settings->setViewportEnabled(viewport_enabled); #if defined(OS_ANDROID) settings->setAllowCustomScrollbarInMainFrame(false); settings->setTextAutosizingEnabled(text_autosizing_enabled); settings->setTextAutosizingFontScaleFactor(font_scale_factor); web_view->setIgnoreViewportTagMaximumScale(force_enable_zoom); settings->setAutoZoomFocusedNodeToLegibleScale(true); settings->setDoubleTapToZoomEnabled(true); settings->setMediaPlaybackRequiresUserGesture( user_gesture_required_for_media_playback); #endif WebNetworkStateNotifier::setOnLine(is_online); } Commit Message: Copy-paste preserves <embed> tags containing active content. BUG=112325 Enable webkit preference for Chromium to disallow unsafe plugin pasting. Review URL: https://chromiumcodereview.appspot.com/11884025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176856 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void WebPreferences::Apply(WebView* web_view) const { WebSettings* settings = web_view->settings(); ApplyFontsFromMap(standard_font_family_map, setStandardFontFamilyWrapper, settings); ApplyFontsFromMap(fixed_font_family_map, setFixedFontFamilyWrapper, settings); ApplyFontsFromMap(serif_font_family_map, setSerifFontFamilyWrapper, settings); ApplyFontsFromMap(sans_serif_font_family_map, setSansSerifFontFamilyWrapper, settings); ApplyFontsFromMap(cursive_font_family_map, setCursiveFontFamilyWrapper, settings); ApplyFontsFromMap(fantasy_font_family_map, setFantasyFontFamilyWrapper, settings); ApplyFontsFromMap(pictograph_font_family_map, setPictographFontFamilyWrapper, settings); settings->setDefaultFontSize(default_font_size); settings->setDefaultFixedFontSize(default_fixed_font_size); settings->setMinimumFontSize(minimum_font_size); settings->setMinimumLogicalFontSize(minimum_logical_font_size); settings->setDefaultTextEncodingName(ASCIIToUTF16(default_encoding)); settings->setApplyDefaultDeviceScaleFactorInCompositor( apply_default_device_scale_factor_in_compositor); settings->setApplyPageScaleFactorInCompositor( apply_page_scale_factor_in_compositor); settings->setPerTilePaintingEnabled(per_tile_painting_enabled); settings->setAcceleratedAnimationEnabled(accelerated_animation_enabled); settings->setJavaScriptEnabled(javascript_enabled); settings->setWebSecurityEnabled(web_security_enabled); settings->setJavaScriptCanOpenWindowsAutomatically( javascript_can_open_windows_automatically); settings->setLoadsImagesAutomatically(loads_images_automatically); settings->setImagesEnabled(images_enabled); settings->setPluginsEnabled(plugins_enabled); settings->setDOMPasteAllowed(dom_paste_enabled); settings->setDeveloperExtrasEnabled(developer_extras_enabled); settings->setNeedsSiteSpecificQuirks(site_specific_quirks_enabled); settings->setShrinksStandaloneImagesToFit(shrinks_standalone_images_to_fit); settings->setUsesEncodingDetector(uses_universal_detector); settings->setTextAreasAreResizable(text_areas_are_resizable); settings->setAllowScriptsToCloseWindows(allow_scripts_to_close_windows); if (user_style_sheet_enabled) settings->setUserStyleSheetLocation(user_style_sheet_location); else settings->setUserStyleSheetLocation(WebURL()); settings->setAuthorAndUserStylesEnabled(author_and_user_styles_enabled); settings->setUsesPageCache(uses_page_cache); settings->setPageCacheSupportsPlugins(page_cache_supports_plugins); settings->setDownloadableBinaryFontsEnabled(remote_fonts_enabled); settings->setJavaScriptCanAccessClipboard(javascript_can_access_clipboard); settings->setXSSAuditorEnabled(xss_auditor_enabled); settings->setDNSPrefetchingEnabled(dns_prefetching_enabled); settings->setLocalStorageEnabled(local_storage_enabled); settings->setSyncXHRInDocumentsEnabled(sync_xhr_in_documents_enabled); WebRuntimeFeatures::enableDatabase(databases_enabled); settings->setOfflineWebApplicationCacheEnabled(application_cache_enabled); settings->setCaretBrowsingEnabled(caret_browsing_enabled); settings->setHyperlinkAuditingEnabled(hyperlink_auditing_enabled); settings->setCookieEnabled(cookie_enabled); settings->setEditableLinkBehaviorNeverLive(); settings->setFrameFlatteningEnabled(frame_flattening_enabled); settings->setFontRenderingModeNormal(); settings->setJavaEnabled(java_enabled); settings->setAllowUniversalAccessFromFileURLs( allow_universal_access_from_file_urls); settings->setAllowFileAccessFromFileURLs(allow_file_access_from_file_urls); settings->setTextDirectionSubmenuInclusionBehaviorNeverIncluded(); settings->setWebAudioEnabled(webaudio_enabled); settings->setExperimentalWebGLEnabled(experimental_webgl_enabled); settings->setOpenGLMultisamplingEnabled(gl_multisampling_enabled); settings->setPrivilegedWebGLExtensionsEnabled( privileged_webgl_extensions_enabled); settings->setWebGLErrorsToConsoleEnabled(webgl_errors_to_console_enabled); settings->setShowDebugBorders(show_composited_layer_borders); settings->setShowFPSCounter(show_fps_counter); settings->setAcceleratedCompositingForOverflowScrollEnabled( accelerated_compositing_for_overflow_scroll_enabled); settings->setAcceleratedCompositingForScrollableFramesEnabled( accelerated_compositing_for_scrollable_frames_enabled); settings->setCompositedScrollingForFramesEnabled( composited_scrolling_for_frames_enabled); settings->setShowPlatformLayerTree(show_composited_layer_tree); settings->setShowPaintRects(show_paint_rects); settings->setRenderVSyncEnabled(render_vsync_enabled); settings->setAcceleratedCompositingEnabled(accelerated_compositing_enabled); settings->setAcceleratedCompositingForFixedPositionEnabled( fixed_position_compositing_enabled); settings->setAccelerated2dCanvasEnabled(accelerated_2d_canvas_enabled); settings->setDeferred2dCanvasEnabled(deferred_2d_canvas_enabled); settings->setAntialiased2dCanvasEnabled(!antialiased_2d_canvas_disabled); settings->setAcceleratedPaintingEnabled(accelerated_painting_enabled); settings->setAcceleratedFiltersEnabled(accelerated_filters_enabled); settings->setGestureTapHighlightEnabled(gesture_tap_highlight_enabled); settings->setAcceleratedCompositingFor3DTransformsEnabled( accelerated_compositing_for_3d_transforms_enabled); settings->setAcceleratedCompositingForVideoEnabled( accelerated_compositing_for_video_enabled); settings->setAcceleratedCompositingForAnimationEnabled( accelerated_compositing_for_animation_enabled); settings->setAcceleratedCompositingForPluginsEnabled( accelerated_compositing_for_plugins_enabled); settings->setAcceleratedCompositingForCanvasEnabled( experimental_webgl_enabled || accelerated_2d_canvas_enabled); settings->setMemoryInfoEnabled(memory_info_enabled); settings->setAsynchronousSpellCheckingEnabled( asynchronous_spell_checking_enabled); settings->setUnifiedTextCheckerEnabled(unified_textchecker_enabled); for (WebInspectorPreferences::const_iterator it = inspector_settings.begin(); it != inspector_settings.end(); ++it) web_view->setInspectorSetting(WebString::fromUTF8(it->first), WebString::fromUTF8(it->second)); web_view->setTabsToLinks(tabs_to_links); settings->setInteractiveFormValidationEnabled(true); settings->setFullScreenEnabled(fullscreen_enabled); settings->setAllowDisplayOfInsecureContent(allow_displaying_insecure_content); settings->setAllowRunningOfInsecureContent(allow_running_insecure_content); settings->setPasswordEchoEnabled(password_echo_enabled); settings->setShouldPrintBackgrounds(should_print_backgrounds); settings->setEnableScrollAnimator(enable_scroll_animator); settings->setVisualWordMovementEnabled(visual_word_movement_enabled); settings->setCSSStickyPositionEnabled(css_sticky_position_enabled); settings->setExperimentalCSSCustomFilterEnabled(css_shaders_enabled); settings->setExperimentalCSSVariablesEnabled(css_variables_enabled); settings->setExperimentalCSSGridLayoutEnabled(css_grid_layout_enabled); WebRuntimeFeatures::enableTouch(touch_enabled); settings->setDeviceSupportsTouch(device_supports_touch); settings->setDeviceSupportsMouse(device_supports_mouse); settings->setEnableTouchAdjustment(touch_adjustment_enabled); settings->setDefaultTileSize( WebSize(default_tile_width, default_tile_height)); settings->setMaxUntiledLayerSize( WebSize(max_untiled_layer_width, max_untiled_layer_height)); settings->setFixedPositionCreatesStackingContext( fixed_position_creates_stacking_context); settings->setDeferredImageDecodingEnabled(deferred_image_decoding_enabled); settings->setShouldRespectImageOrientation(should_respect_image_orientation); settings->setUnsafePluginPastingEnabled(false); settings->setEditingBehavior( static_cast<WebSettings::EditingBehavior>(editing_behavior)); settings->setSupportsMultipleWindows(supports_multiple_windows); settings->setViewportEnabled(viewport_enabled); #if defined(OS_ANDROID) settings->setAllowCustomScrollbarInMainFrame(false); settings->setTextAutosizingEnabled(text_autosizing_enabled); settings->setTextAutosizingFontScaleFactor(font_scale_factor); web_view->setIgnoreViewportTagMaximumScale(force_enable_zoom); settings->setAutoZoomFocusedNodeToLegibleScale(true); settings->setDoubleTapToZoomEnabled(true); settings->setMediaPlaybackRequiresUserGesture( user_gesture_required_for_media_playback); #endif WebNetworkStateNotifier::setOnLine(is_online); }
171,457
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DOMWindow* CreateWindow(const String& url_string, const AtomicString& frame_name, const String& window_features_string, LocalDOMWindow& calling_window, LocalFrame& first_frame, LocalFrame& opener_frame, ExceptionState& exception_state) { LocalFrame* active_frame = calling_window.GetFrame(); DCHECK(active_frame); KURL completed_url = url_string.IsEmpty() ? KURL(kParsedURLString, g_empty_string) : first_frame.GetDocument()->CompleteURL(url_string); if (!completed_url.IsEmpty() && !completed_url.IsValid()) { UseCounter::Count(active_frame, WebFeature::kWindowOpenWithInvalidURL); exception_state.ThrowDOMException( kSyntaxError, "Unable to open a window with invalid URL '" + completed_url.GetString() + "'.\n"); return nullptr; } WebWindowFeatures window_features = GetWindowFeaturesFromString(window_features_string); FrameLoadRequest frame_request(calling_window.document(), ResourceRequest(completed_url), frame_name); frame_request.SetShouldSetOpener(window_features.noopener ? kNeverSetOpener : kMaybeSetOpener); frame_request.GetResourceRequest().SetFrameType( WebURLRequest::kFrameTypeAuxiliary); frame_request.GetResourceRequest().SetRequestorOrigin( SecurityOrigin::Create(active_frame->GetDocument()->Url())); frame_request.GetResourceRequest().SetHTTPReferrer( SecurityPolicy::GenerateReferrer( active_frame->GetDocument()->GetReferrerPolicy(), completed_url, active_frame->GetDocument()->OutgoingReferrer())); bool has_user_gesture = UserGestureIndicator::ProcessingUserGesture(); bool created; Frame* new_frame = CreateWindowHelper( opener_frame, *active_frame, opener_frame, frame_request, window_features, kNavigationPolicyIgnore, created); if (!new_frame) return nullptr; if (new_frame->DomWindow()->IsInsecureScriptAccess(calling_window, completed_url)) return window_features.noopener ? nullptr : new_frame->DomWindow(); if (created) { FrameLoadRequest request(calling_window.document(), ResourceRequest(completed_url)); request.GetResourceRequest().SetHasUserGesture(has_user_gesture); new_frame->Navigate(request); } else if (!url_string.IsEmpty()) { new_frame->Navigate(*calling_window.document(), completed_url, false, has_user_gesture ? UserGestureStatus::kActive : UserGestureStatus::kNone); } return window_features.noopener ? nullptr : new_frame->DomWindow(); } Commit Message: CSP now prevents opening javascript url windows when they're not allowed spec: https://html.spec.whatwg.org/#navigate which leads to: https://w3c.github.io/webappsec-csp/#should-block-navigation-request Bug: 756040 Change-Id: I5fd62ebfb6fe1d767694b0ed6cf427c8ea95994a Reviewed-on: https://chromium-review.googlesource.com/632580 Reviewed-by: Mike West <[email protected]> Commit-Queue: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#497338} CWE ID:
DOMWindow* CreateWindow(const String& url_string, const AtomicString& frame_name, const String& window_features_string, LocalDOMWindow& calling_window, LocalFrame& first_frame, LocalFrame& opener_frame, ExceptionState& exception_state) { LocalFrame* active_frame = calling_window.GetFrame(); DCHECK(active_frame); KURL completed_url = url_string.IsEmpty() ? KURL(kParsedURLString, g_empty_string) : first_frame.GetDocument()->CompleteURL(url_string); if (!completed_url.IsEmpty() && !completed_url.IsValid()) { UseCounter::Count(active_frame, WebFeature::kWindowOpenWithInvalidURL); exception_state.ThrowDOMException( kSyntaxError, "Unable to open a window with invalid URL '" + completed_url.GetString() + "'.\n"); return nullptr; } if (completed_url.ProtocolIsJavaScript() && opener_frame.GetDocument()->GetContentSecurityPolicy() && !ContentSecurityPolicy::ShouldBypassMainWorld( opener_frame.GetDocument())) { const int kJavascriptSchemeLength = sizeof("javascript:") - 1; String script_source = DecodeURLEscapeSequences(completed_url.GetString()) .Substring(kJavascriptSchemeLength); if (!opener_frame.GetDocument() ->GetContentSecurityPolicy() ->AllowJavaScriptURLs(nullptr, script_source, opener_frame.GetDocument()->Url(), OrdinalNumber())) { return nullptr; } } WebWindowFeatures window_features = GetWindowFeaturesFromString(window_features_string); FrameLoadRequest frame_request(calling_window.document(), ResourceRequest(completed_url), frame_name); frame_request.SetShouldSetOpener(window_features.noopener ? kNeverSetOpener : kMaybeSetOpener); frame_request.GetResourceRequest().SetFrameType( WebURLRequest::kFrameTypeAuxiliary); frame_request.GetResourceRequest().SetRequestorOrigin( SecurityOrigin::Create(active_frame->GetDocument()->Url())); frame_request.GetResourceRequest().SetHTTPReferrer( SecurityPolicy::GenerateReferrer( active_frame->GetDocument()->GetReferrerPolicy(), completed_url, active_frame->GetDocument()->OutgoingReferrer())); bool has_user_gesture = UserGestureIndicator::ProcessingUserGesture(); bool created; Frame* new_frame = CreateWindowHelper( opener_frame, *active_frame, opener_frame, frame_request, window_features, kNavigationPolicyIgnore, created); if (!new_frame) return nullptr; if (new_frame->DomWindow()->IsInsecureScriptAccess(calling_window, completed_url)) return window_features.noopener ? nullptr : new_frame->DomWindow(); if (created) { FrameLoadRequest request(calling_window.document(), ResourceRequest(completed_url)); request.GetResourceRequest().SetHasUserGesture(has_user_gesture); new_frame->Navigate(request); } else if (!url_string.IsEmpty()) { new_frame->Navigate(*calling_window.document(), completed_url, false, has_user_gesture ? UserGestureStatus::kActive : UserGestureStatus::kNone); } return window_features.noopener ? nullptr : new_frame->DomWindow(); }
172,953
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ssdp_recv(int sd) { ssize_t len; struct sockaddr sa; socklen_t salen; char buf[MAX_PKT_SIZE]; memset(buf, 0, sizeof(buf)); len = recvfrom(sd, buf, sizeof(buf), MSG_DONTWAIT, &sa, &salen); if (len > 0) { buf[len] = 0; if (sa.sa_family != AF_INET) return; if (strstr(buf, "M-SEARCH *")) { size_t i; char *ptr, *type; struct ifsock *ifs; struct sockaddr_in *sin = (struct sockaddr_in *)&sa; ifs = find_outbound(&sa); if (!ifs) { logit(LOG_DEBUG, "No matching socket for client %s", inet_ntoa(sin->sin_addr)); return; } logit(LOG_DEBUG, "Matching socket for client %s", inet_ntoa(sin->sin_addr)); type = strcasestr(buf, "\r\nST:"); if (!type) { logit(LOG_DEBUG, "No Search Type (ST:) found in M-SEARCH *, assuming " SSDP_ST_ALL); type = SSDP_ST_ALL; send_message(ifs, type, &sa); return; } type = strchr(type, ':'); if (!type) return; type++; while (isspace(*type)) type++; ptr = strstr(type, "\r\n"); if (!ptr) return; *ptr = 0; for (i = 0; supported_types[i]; i++) { if (!strcmp(supported_types[i], type)) { logit(LOG_DEBUG, "M-SEARCH * ST: %s from %s port %d", type, inet_ntoa(sin->sin_addr), ntohs(sin->sin_port)); send_message(ifs, type, &sa); return; } } logit(LOG_DEBUG, "M-SEARCH * for unsupported ST: %s from %s", type, inet_ntoa(sin->sin_addr)); } } } Commit Message: Fix #1: Ensure recv buf is always NUL terminated Signed-off-by: Joachim Nilsson <[email protected]> CWE ID: CWE-119
static void ssdp_recv(int sd) { ssize_t len; struct sockaddr sa; socklen_t salen; char buf[MAX_PKT_SIZE + 1]; memset(buf, 0, sizeof(buf)); len = recvfrom(sd, buf, sizeof(buf) - 1, MSG_DONTWAIT, &sa, &salen); if (len > 0) { if (sa.sa_family != AF_INET) return; if (strstr(buf, "M-SEARCH *")) { size_t i; char *ptr, *type; struct ifsock *ifs; struct sockaddr_in *sin = (struct sockaddr_in *)&sa; ifs = find_outbound(&sa); if (!ifs) { logit(LOG_DEBUG, "No matching socket for client %s", inet_ntoa(sin->sin_addr)); return; } logit(LOG_DEBUG, "Matching socket for client %s", inet_ntoa(sin->sin_addr)); type = strcasestr(buf, "\r\nST:"); if (!type) { logit(LOG_DEBUG, "No Search Type (ST:) found in M-SEARCH *, assuming " SSDP_ST_ALL); type = SSDP_ST_ALL; send_message(ifs, type, &sa); return; } type = strchr(type, ':'); if (!type) return; type++; while (isspace(*type)) type++; ptr = strstr(type, "\r\n"); if (!ptr) return; *ptr = 0; for (i = 0; supported_types[i]; i++) { if (!strcmp(supported_types[i], type)) { logit(LOG_DEBUG, "M-SEARCH * ST: %s from %s port %d", type, inet_ntoa(sin->sin_addr), ntohs(sin->sin_port)); send_message(ifs, type, &sa); return; } } logit(LOG_DEBUG, "M-SEARCH * for unsupported ST: %s from %s", type, inet_ntoa(sin->sin_addr)); } } }
169,584
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __scm_destroy(struct scm_cookie *scm) { struct scm_fp_list *fpl = scm->fp; int i; if (fpl) { scm->fp = NULL; for (i=fpl->count-1; i>=0; i--) fput(fpl->fp[i]); kfree(fpl); } } Commit Message: unix: correctly track in-flight fds in sending process user_struct The commit referenced in the Fixes tag incorrectly accounted the number of in-flight fds over a unix domain socket to the original opener of the file-descriptor. This allows another process to arbitrary deplete the original file-openers resource limit for the maximum of open files. Instead the sending processes and its struct cred should be credited. To do so, we add a reference counted struct user_struct pointer to the scm_fp_list and use it to account for the number of inflight unix fds. Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets") Reported-by: David Herrmann <[email protected]> Cc: David Herrmann <[email protected]> Cc: Willy Tarreau <[email protected]> Cc: Linus Torvalds <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
void __scm_destroy(struct scm_cookie *scm) { struct scm_fp_list *fpl = scm->fp; int i; if (fpl) { scm->fp = NULL; for (i=fpl->count-1; i>=0; i--) fput(fpl->fp[i]); free_uid(fpl->user); kfree(fpl); } }
167,391
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 StoreExistingGroupExistingCache() { MakeCacheAndGroup(kManifestUrl, 1, 1, true); EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin]); base::Time now = base::Time::Now(); cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::MASTER, 1, 100)); cache_->set_update_time(now); PushNextTask(base::BindOnce( &AppCacheStorageImplTest::Verify_StoreExistingGroupExistingCache, base::Unretained(this), now)); EXPECT_EQ(cache_.get(), group_->newest_complete_cache()); storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate()); EXPECT_FALSE(delegate()->stored_group_success_); } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200
void StoreExistingGroupExistingCache() { MakeCacheAndGroup(kManifestUrl, 1, 1, true); EXPECT_EQ(kDefaultEntrySize + kDefaultEntryPadding, storage()->usage_map_[kOrigin]); base::Time now = base::Time::Now(); cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::EXPLICIT, /*response_id=*/1, /*response_size=*/100, /*padding_size=*/10)); cache_->set_update_time(now); PushNextTask(base::BindOnce( &AppCacheStorageImplTest::Verify_StoreExistingGroupExistingCache, base::Unretained(this), now)); EXPECT_EQ(cache_.get(), group_->newest_complete_cache()); storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate()); EXPECT_FALSE(delegate()->stored_group_success_); }
172,990
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MountError PerformFakeMount(const std::string& source_path, const base::FilePath& mounted_path) { if (mounted_path.empty()) return MOUNT_ERROR_INVALID_ARGUMENT; if (!base::CreateDirectory(mounted_path)) { DLOG(ERROR) << "Failed to create directory at " << mounted_path.value(); return MOUNT_ERROR_DIRECTORY_CREATION_FAILED; } const base::FilePath dummy_file_path = mounted_path.Append("SUCCESSFULLY_PERFORMED_FAKE_MOUNT.txt"); const std::string dummy_file_content = "This is a dummy file."; const int write_result = base::WriteFile( dummy_file_path, dummy_file_content.data(), dummy_file_content.size()); if (write_result != static_cast<int>(dummy_file_content.size())) { DLOG(ERROR) << "Failed to put a dummy file at " << dummy_file_path.value(); return MOUNT_ERROR_MOUNT_PROGRAM_FAILED; } return MOUNT_ERROR_NONE; } Commit Message: Add a fake DriveFS launcher client. Using DriveFS requires building and deploying ChromeOS. Add a client for the fake DriveFS launcher to allow the use of a real DriveFS from a ChromeOS chroot to be used with a target_os="chromeos" build of chrome. This connects to the fake DriveFS launcher using mojo over a unix domain socket named by a command-line flag, using the launcher to create DriveFS instances. Bug: 848126 Change-Id: I22dcca154d41bda196dd7c1782bb503f6bcba5b1 Reviewed-on: https://chromium-review.googlesource.com/1098434 Reviewed-by: Xiyuan Xia <[email protected]> Commit-Queue: Sam McNally <[email protected]> Cr-Commit-Position: refs/heads/master@{#567513} CWE ID:
MountError PerformFakeMount(const std::string& source_path, const base::FilePath& mounted_path, MountType type) { if (mounted_path.empty()) return MOUNT_ERROR_INVALID_ARGUMENT; if (!base::CreateDirectory(mounted_path)) { DLOG(ERROR) << "Failed to create directory at " << mounted_path.value(); return MOUNT_ERROR_DIRECTORY_CREATION_FAILED; } // Fake network mounts are responsible for populating their mount paths so // don't need a dummy file. if (type == MOUNT_TYPE_NETWORK_STORAGE) return MOUNT_ERROR_NONE; const base::FilePath dummy_file_path = mounted_path.Append("SUCCESSFULLY_PERFORMED_FAKE_MOUNT.txt"); const std::string dummy_file_content = "This is a dummy file."; const int write_result = base::WriteFile( dummy_file_path, dummy_file_content.data(), dummy_file_content.size()); if (write_result != static_cast<int>(dummy_file_content.size())) { DLOG(ERROR) << "Failed to put a dummy file at " << dummy_file_path.value(); return MOUNT_ERROR_MOUNT_PROGRAM_FAILED; } return MOUNT_ERROR_NONE; }
171,731
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int php_stream_temp_seek(php_stream *stream, off_t offset, int whence, off_t *newoffs TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; int ret; assert(ts != NULL); if (!ts->innerstream) { *newoffs = -1; return -1; } ret = php_stream_seek(ts->innerstream, offset, whence); *newoffs = php_stream_tell(ts->innerstream); stream->eof = ts->innerstream->eof; return ret; } Commit Message: CWE ID: CWE-20
static int php_stream_temp_seek(php_stream *stream, off_t offset, int whence, off_t *newoffs TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; int ret; assert(ts != NULL); if (!ts->innerstream) { *newoffs = -1; return -1; } ret = php_stream_seek(ts->innerstream, offset, whence); *newoffs = php_stream_tell(ts->innerstream); stream->eof = ts->innerstream->eof; return ret; }
165,481
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 impeg2d_peek_next_start_code(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; impeg2d_bit_stream_flush_to_byte_boundary(ps_stream); while ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX) && (ps_dec->s_bit_stream.u4_offset <= ps_dec->s_bit_stream.u4_max_offset)) { impeg2d_bit_stream_get(ps_stream,8); } return; } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254
void impeg2d_peek_next_start_code(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; impeg2d_bit_stream_flush_to_byte_boundary(ps_stream); while ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX) && (ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset)) { impeg2d_bit_stream_get(ps_stream,8); } return; }
173,951
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: T42_Face_Init( FT_Stream stream, FT_Face t42face, /* T42_Face */ FT_Int face_index, FT_Int num_params, FT_Parameter* params ) { T42_Face face = (T42_Face)t42face; FT_Error error; FT_Service_PsCMaps psnames; PSAux_Service psaux; FT_Face root = (FT_Face)&face->root; T1_Font type1 = &face->type1; PS_FontInfo info = &type1->font_info; FT_UNUSED( num_params ); FT_UNUSED( params ); FT_UNUSED( stream ); face->ttf_face = NULL; face->root.num_faces = 1; FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS ); face->psnames = psnames; face->psaux = FT_Get_Module_Interface( FT_FACE_LIBRARY( face ), "psaux" ); psaux = (PSAux_Service)face->psaux; if ( !psaux ) { FT_ERROR(( "T42_Face_Init: cannot access `psaux' module\n" )); error = FT_THROW( Missing_Module ); goto Exit; } FT_TRACE2(( "Type 42 driver\n" )); /* open the tokenizer, this will also check the font format */ error = T42_Open_Face( face ); if ( error ) goto Exit; /* if we just wanted to check the format, leave successfully now */ if ( face_index < 0 ) goto Exit; /* check the face index */ if ( face_index > 0 ) { FT_ERROR(( "T42_Face_Init: invalid face index\n" )); error = FT_THROW( Invalid_Argument ); goto Exit; } /* Now load the font program into the face object */ /* Init the face object fields */ /* Now set up root face fields */ root->num_glyphs = type1->num_glyphs; root->num_charmaps = 0; root->face_index = 0; root->face_flags |= FT_FACE_FLAG_SCALABLE | FT_FACE_FLAG_HORIZONTAL | FT_FACE_FLAG_GLYPH_NAMES; if ( info->is_fixed_pitch ) root->face_flags |= FT_FACE_FLAG_FIXED_WIDTH; /* We only set this flag if we have the patented bytecode interpreter. */ /* There are no known `tricky' Type42 fonts that could be loaded with */ /* the unpatented interpreter. */ #ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER root->face_flags |= FT_FACE_FLAG_HINTER; #endif /* XXX: TODO -- add kerning with .afm support */ /* get style name -- be careful, some broken fonts only */ /* have a `/FontName' dictionary entry! */ root->family_name = info->family_name; /* assume "Regular" style if we don't know better */ root->style_name = (char *)"Regular"; if ( root->family_name ) { char* full = info->full_name; char* family = root->family_name; if ( full ) { while ( *full ) { if ( *full == *family ) { family++; full++; } else { if ( *full == ' ' || *full == '-' ) full++; else if ( *family == ' ' || *family == '-' ) family++; else { if ( !*family ) root->style_name = full; break; } } } } } else { /* do we have a `/FontName'? */ if ( type1->font_name ) root->family_name = type1->font_name; } /* no embedded bitmap support */ root->num_fixed_sizes = 0; root->available_sizes = 0; /* Load the TTF font embedded in the T42 font */ { FT_Open_Args args; args.flags = FT_OPEN_MEMORY; args.memory_base = face->ttf_data; args.memory_size = face->ttf_size; args.flags |= FT_OPEN_PARAMS; args.num_params = num_params; args.params = params; } error = FT_Open_Face( FT_FACE_LIBRARY( face ), &args, 0, &face->ttf_face ); } Commit Message: CWE ID:
T42_Face_Init( FT_Stream stream, FT_Face t42face, /* T42_Face */ FT_Int face_index, FT_Int num_params, FT_Parameter* params ) { T42_Face face = (T42_Face)t42face; FT_Error error; FT_Service_PsCMaps psnames; PSAux_Service psaux; FT_Face root = (FT_Face)&face->root; T1_Font type1 = &face->type1; PS_FontInfo info = &type1->font_info; FT_UNUSED( num_params ); FT_UNUSED( params ); FT_UNUSED( stream ); face->ttf_face = NULL; face->root.num_faces = 1; FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS ); face->psnames = psnames; face->psaux = FT_Get_Module_Interface( FT_FACE_LIBRARY( face ), "psaux" ); psaux = (PSAux_Service)face->psaux; if ( !psaux ) { FT_ERROR(( "T42_Face_Init: cannot access `psaux' module\n" )); error = FT_THROW( Missing_Module ); goto Exit; } FT_TRACE2(( "Type 42 driver\n" )); /* open the tokenizer, this will also check the font format */ error = T42_Open_Face( face ); if ( error ) goto Exit; /* if we just wanted to check the format, leave successfully now */ if ( face_index < 0 ) goto Exit; /* check the face index */ if ( face_index > 0 ) { FT_ERROR(( "T42_Face_Init: invalid face index\n" )); error = FT_THROW( Invalid_Argument ); goto Exit; } /* Now load the font program into the face object */ /* Init the face object fields */ /* Now set up root face fields */ root->num_glyphs = type1->num_glyphs; root->num_charmaps = 0; root->face_index = 0; root->face_flags |= FT_FACE_FLAG_SCALABLE | FT_FACE_FLAG_HORIZONTAL | FT_FACE_FLAG_GLYPH_NAMES; if ( info->is_fixed_pitch ) root->face_flags |= FT_FACE_FLAG_FIXED_WIDTH; /* We only set this flag if we have the patented bytecode interpreter. */ /* There are no known `tricky' Type42 fonts that could be loaded with */ /* the unpatented interpreter. */ #ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER root->face_flags |= FT_FACE_FLAG_HINTER; #endif /* XXX: TODO -- add kerning with .afm support */ /* get style name -- be careful, some broken fonts only */ /* have a `/FontName' dictionary entry! */ root->family_name = info->family_name; /* assume "Regular" style if we don't know better */ root->style_name = (char *)"Regular"; if ( root->family_name ) { char* full = info->full_name; char* family = root->family_name; if ( full ) { while ( *full ) { if ( *full == *family ) { family++; full++; } else { if ( *full == ' ' || *full == '-' ) full++; else if ( *family == ' ' || *family == '-' ) family++; else { if ( !*family ) root->style_name = full; break; } } } } } else { /* do we have a `/FontName'? */ if ( type1->font_name ) root->family_name = type1->font_name; } /* no embedded bitmap support */ root->num_fixed_sizes = 0; root->available_sizes = 0; /* Load the TTF font embedded in the T42 font */ { FT_Open_Args args; args.flags = FT_OPEN_MEMORY | FT_OPEN_DRIVER; args.driver = FT_Get_Module( FT_FACE_LIBRARY( face ), "truetype" ); args.memory_base = face->ttf_data; args.memory_size = face->ttf_size; args.flags |= FT_OPEN_PARAMS; args.num_params = num_params; args.params = params; } error = FT_Open_Face( FT_FACE_LIBRARY( face ), &args, 0, &face->ttf_face ); }
164,860
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Document::InitSecurityContext(const DocumentInit& initializer) { DCHECK(!GetSecurityOrigin()); if (!initializer.HasSecurityContext()) { cookie_url_ = KURL(g_empty_string); SetSecurityOrigin(SecurityOrigin::CreateUniqueOpaque()); InitContentSecurityPolicy(); ApplyFeaturePolicy({}); return; } SandboxFlags sandbox_flags = initializer.GetSandboxFlags(); if (fetcher_->Archive()) { sandbox_flags |= kSandboxAll & ~(kSandboxPopups | kSandboxPropagatesToAuxiliaryBrowsingContexts); } EnforceSandboxFlags(sandbox_flags); SetInsecureRequestPolicy(initializer.GetInsecureRequestPolicy()); if (initializer.InsecureNavigationsToUpgrade()) { for (auto to_upgrade : *initializer.InsecureNavigationsToUpgrade()) AddInsecureNavigationUpgrade(to_upgrade); } const ContentSecurityPolicy* policy_to_inherit = nullptr; if (IsSandboxed(kSandboxOrigin)) { cookie_url_ = url_; scoped_refptr<SecurityOrigin> security_origin = SecurityOrigin::CreateUniqueOpaque(); Document* owner = initializer.OwnerDocument(); if (owner) { if (owner->GetSecurityOrigin()->IsPotentiallyTrustworthy()) security_origin->SetOpaqueOriginIsPotentiallyTrustworthy(true); if (owner->GetSecurityOrigin()->CanLoadLocalResources()) security_origin->GrantLoadLocalResources(); policy_to_inherit = owner->GetContentSecurityPolicy(); } SetSecurityOrigin(std::move(security_origin)); } else if (Document* owner = initializer.OwnerDocument()) { cookie_url_ = owner->CookieURL(); SetSecurityOrigin(owner->GetMutableSecurityOrigin()); policy_to_inherit = owner->GetContentSecurityPolicy(); } else { cookie_url_ = url_; SetSecurityOrigin(SecurityOrigin::Create(url_)); } if (initializer.IsHostedInReservedIPRange()) { SetAddressSpace(GetSecurityOrigin()->IsLocalhost() ? mojom::IPAddressSpace::kLocal : mojom::IPAddressSpace::kPrivate); } else if (GetSecurityOrigin()->IsLocal()) { SetAddressSpace(mojom::IPAddressSpace::kLocal); } else { SetAddressSpace(mojom::IPAddressSpace::kPublic); } if (ImportsController()) { SetContentSecurityPolicy( ImportsController()->Master()->GetContentSecurityPolicy()); } else { InitContentSecurityPolicy(nullptr, policy_to_inherit, initializer.PreviousDocumentCSP()); } if (Settings* settings = initializer.GetSettings()) { if (!settings->GetWebSecurityEnabled()) { GetMutableSecurityOrigin()->GrantUniversalAccess(); } else if (GetSecurityOrigin()->IsLocal()) { if (settings->GetAllowUniversalAccessFromFileURLs()) { GetMutableSecurityOrigin()->GrantUniversalAccess(); } else if (!settings->GetAllowFileAccessFromFileURLs()) { GetMutableSecurityOrigin()->BlockLocalAccessFromLocalOrigin(); } } } if (GetSecurityOrigin()->IsOpaque() && SecurityOrigin::Create(url_)->IsPotentiallyTrustworthy()) GetMutableSecurityOrigin()->SetOpaqueOriginIsPotentiallyTrustworthy(true); ApplyFeaturePolicy({}); InitSecureContextState(); } Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener Spec PR: https://github.com/w3c/webappsec-csp/pull/358 Bug: 905301, 894228, 836148 Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a Reviewed-on: https://chromium-review.googlesource.com/c/1314633 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#610850} CWE ID: CWE-20
void Document::InitSecurityContext(const DocumentInit& initializer) { DCHECK(!GetSecurityOrigin()); if (!initializer.HasSecurityContext()) { cookie_url_ = KURL(g_empty_string); SetSecurityOrigin(SecurityOrigin::CreateUniqueOpaque()); InitContentSecurityPolicy(); ApplyFeaturePolicy({}); return; } SandboxFlags sandbox_flags = initializer.GetSandboxFlags(); if (fetcher_->Archive()) { sandbox_flags |= kSandboxAll & ~(kSandboxPopups | kSandboxPropagatesToAuxiliaryBrowsingContexts); } EnforceSandboxFlags(sandbox_flags); SetInsecureRequestPolicy(initializer.GetInsecureRequestPolicy()); if (initializer.InsecureNavigationsToUpgrade()) { for (auto to_upgrade : *initializer.InsecureNavigationsToUpgrade()) AddInsecureNavigationUpgrade(to_upgrade); } Document* origin_document = frame_ ? frame_->Loader().GetLastOriginDocument() : nullptr; if (IsSandboxed(kSandboxOrigin)) { cookie_url_ = url_; scoped_refptr<SecurityOrigin> security_origin = SecurityOrigin::CreateUniqueOpaque(); Document* owner = initializer.OwnerDocument(); if (owner) { if (owner->GetSecurityOrigin()->IsPotentiallyTrustworthy()) security_origin->SetOpaqueOriginIsPotentiallyTrustworthy(true); if (owner->GetSecurityOrigin()->CanLoadLocalResources()) security_origin->GrantLoadLocalResources(); if (url_.IsEmpty()) origin_document = owner; } SetSecurityOrigin(std::move(security_origin)); } else if (Document* owner = initializer.OwnerDocument()) { cookie_url_ = owner->CookieURL(); SetSecurityOrigin(owner->GetMutableSecurityOrigin()); if (url_.IsEmpty()) origin_document = owner; } else { cookie_url_ = url_; SetSecurityOrigin(SecurityOrigin::Create(url_)); } if (initializer.IsHostedInReservedIPRange()) { SetAddressSpace(GetSecurityOrigin()->IsLocalhost() ? mojom::IPAddressSpace::kLocal : mojom::IPAddressSpace::kPrivate); } else if (GetSecurityOrigin()->IsLocal()) { SetAddressSpace(mojom::IPAddressSpace::kLocal); } else { SetAddressSpace(mojom::IPAddressSpace::kPublic); } if (ImportsController()) { SetContentSecurityPolicy( ImportsController()->Master()->GetContentSecurityPolicy()); } else { InitContentSecurityPolicy(nullptr, origin_document); } if (Settings* settings = initializer.GetSettings()) { if (!settings->GetWebSecurityEnabled()) { GetMutableSecurityOrigin()->GrantUniversalAccess(); } else if (GetSecurityOrigin()->IsLocal()) { if (settings->GetAllowUniversalAccessFromFileURLs()) { GetMutableSecurityOrigin()->GrantUniversalAccess(); } else if (!settings->GetAllowFileAccessFromFileURLs()) { GetMutableSecurityOrigin()->BlockLocalAccessFromLocalOrigin(); } } } if (GetSecurityOrigin()->IsOpaque() && SecurityOrigin::Create(url_)->IsPotentiallyTrustworthy()) GetMutableSecurityOrigin()->SetOpaqueOriginIsPotentiallyTrustworthy(true); ApplyFeaturePolicy({}); InitSecureContextState(); }
173,053
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FFmpegVideoDecoder::GetVideoBuffer(AVCodecContext* codec_context, AVFrame* frame) { VideoFrame::Format format = PixelFormatToVideoFormat(codec_context->pix_fmt); if (format == VideoFrame::UNKNOWN) return AVERROR(EINVAL); DCHECK(format == VideoFrame::YV12 || format == VideoFrame::YV16 || format == VideoFrame::YV12J); gfx::Size size(codec_context->width, codec_context->height); int ret; if ((ret = av_image_check_size(size.width(), size.height(), 0, NULL)) < 0) return ret; gfx::Size natural_size; if (codec_context->sample_aspect_ratio.num > 0) { natural_size = GetNaturalSize(size, codec_context->sample_aspect_ratio.num, codec_context->sample_aspect_ratio.den); } else { natural_size = config_.natural_size(); } if (!VideoFrame::IsValidConfig(format, size, gfx::Rect(size), natural_size)) return AVERROR(EINVAL); scoped_refptr<VideoFrame> video_frame = frame_pool_.CreateFrame(format, size, gfx::Rect(size), natural_size, kNoTimestamp()); for (int i = 0; i < 3; i++) { frame->base[i] = video_frame->data(i); frame->data[i] = video_frame->data(i); frame->linesize[i] = video_frame->stride(i); } frame->opaque = NULL; video_frame.swap(reinterpret_cast<VideoFrame**>(&frame->opaque)); frame->type = FF_BUFFER_TYPE_USER; frame->width = codec_context->width; frame->height = codec_context->height; frame->format = codec_context->pix_fmt; return 0; } Commit Message: Replicate FFmpeg's video frame allocation strategy. This should avoid accidental overreads and overwrites due to our VideoFrame's not being as large as FFmpeg expects. BUG=368980 TEST=new regression test Review URL: https://codereview.chromium.org/270193002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268831 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
int FFmpegVideoDecoder::GetVideoBuffer(AVCodecContext* codec_context, AVFrame* frame) { VideoFrame::Format format = PixelFormatToVideoFormat(codec_context->pix_fmt); if (format == VideoFrame::UNKNOWN) return AVERROR(EINVAL); DCHECK(format == VideoFrame::YV12 || format == VideoFrame::YV16 || format == VideoFrame::YV12J); gfx::Size size(codec_context->width, codec_context->height); const int ret = av_image_check_size(size.width(), size.height(), 0, NULL); if (ret < 0) return ret; gfx::Size natural_size; if (codec_context->sample_aspect_ratio.num > 0) { natural_size = GetNaturalSize(size, codec_context->sample_aspect_ratio.num, codec_context->sample_aspect_ratio.den); } else { natural_size = config_.natural_size(); } // FFmpeg has specific requirements on the allocation size of the frame. The // following logic replicates FFmpeg's allocation strategy to ensure buffers // are not overread / overwritten. See ff_init_buffer_info() for details. // // When lowres is non-zero, dimensions should be divided by 2^(lowres), but // since we don't use this, just DCHECK that it's zero. DCHECK_EQ(codec_context->lowres, 0); gfx::Size coded_size(std::max(size.width(), codec_context->coded_width), std::max(size.height(), codec_context->coded_height)); if (!VideoFrame::IsValidConfig( format, coded_size, gfx::Rect(size), natural_size)) return AVERROR(EINVAL); scoped_refptr<VideoFrame> video_frame = frame_pool_.CreateFrame( format, coded_size, gfx::Rect(size), natural_size, kNoTimestamp()); for (int i = 0; i < 3; i++) { frame->base[i] = video_frame->data(i); frame->data[i] = video_frame->data(i); frame->linesize[i] = video_frame->stride(i); } frame->opaque = NULL; video_frame.swap(reinterpret_cast<VideoFrame**>(&frame->opaque)); frame->type = FF_BUFFER_TYPE_USER; frame->width = coded_size.width(); frame->height = coded_size.height(); frame->format = codec_context->pix_fmt; return 0; }
171,677
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 HTMLScriptRunner::executePendingScriptAndDispatchEvent(PendingScript& pendingScript, PendingScript::Type pendingScriptType) { bool errorOccurred = false; double loadFinishTime = pendingScript.resource() && pendingScript.resource()->url().protocolIsInHTTPFamily() ? pendingScript.resource()->loadFinishTime() : 0; ScriptSourceCode sourceCode = pendingScript.getSource(documentURLForScriptExecution(m_document), errorOccurred); pendingScript.stopWatchingForLoad(this); if (!isExecutingScript()) { Microtask::performCheckpoint(); if (pendingScriptType == PendingScript::ParsingBlocking) { m_hasScriptsWaitingForResources = !m_document->isScriptExecutionReady(); if (m_hasScriptsWaitingForResources) return; } } RefPtrWillBeRawPtr<Element> element = pendingScript.releaseElementAndClear(); double compilationFinishTime = 0; if (ScriptLoader* scriptLoader = toScriptLoaderIfPossible(element.get())) { NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel); IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_document); if (errorOccurred) scriptLoader->dispatchErrorEvent(); else { ASSERT(isExecutingScript()); if (!scriptLoader->executeScript(sourceCode, &compilationFinishTime)) { scriptLoader->dispatchErrorEvent(); } else { element->dispatchEvent(createScriptLoadEvent()); } } } const double epsilon = 1; if (pendingScriptType == PendingScript::ParsingBlocking && !m_parserBlockingScriptAlreadyLoaded && compilationFinishTime > epsilon && loadFinishTime > epsilon) { Platform::current()->histogramCustomCounts("WebCore.Scripts.ParsingBlocking.TimeBetweenLoadedAndCompiled", (compilationFinishTime - loadFinishTime) * 1000, 0, 10000, 50); } ASSERT(!isExecutingScript()); } Commit Message: Correctly keep track of isolates for microtask execution BUG=487155 [email protected] Review URL: https://codereview.chromium.org/1161823002 git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-254
void HTMLScriptRunner::executePendingScriptAndDispatchEvent(PendingScript& pendingScript, PendingScript::Type pendingScriptType) { bool errorOccurred = false; double loadFinishTime = pendingScript.resource() && pendingScript.resource()->url().protocolIsInHTTPFamily() ? pendingScript.resource()->loadFinishTime() : 0; ScriptSourceCode sourceCode = pendingScript.getSource(documentURLForScriptExecution(m_document), errorOccurred); pendingScript.stopWatchingForLoad(this); if (!isExecutingScript()) { Microtask::performCheckpoint(V8PerIsolateData::mainThreadIsolate()); if (pendingScriptType == PendingScript::ParsingBlocking) { m_hasScriptsWaitingForResources = !m_document->isScriptExecutionReady(); if (m_hasScriptsWaitingForResources) return; } } RefPtrWillBeRawPtr<Element> element = pendingScript.releaseElementAndClear(); double compilationFinishTime = 0; if (ScriptLoader* scriptLoader = toScriptLoaderIfPossible(element.get())) { NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel); IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_document); if (errorOccurred) scriptLoader->dispatchErrorEvent(); else { ASSERT(isExecutingScript()); if (!scriptLoader->executeScript(sourceCode, &compilationFinishTime)) { scriptLoader->dispatchErrorEvent(); } else { element->dispatchEvent(createScriptLoadEvent()); } } } const double epsilon = 1; if (pendingScriptType == PendingScript::ParsingBlocking && !m_parserBlockingScriptAlreadyLoaded && compilationFinishTime > epsilon && loadFinishTime > epsilon) { Platform::current()->histogramCustomCounts("WebCore.Scripts.ParsingBlocking.TimeBetweenLoadedAndCompiled", (compilationFinishTime - loadFinishTime) * 1000, 0, 10000, 50); } ASSERT(!isExecutingScript()); }
171,946
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); assert((cc%(bps*stride))==0); if (!tmp) return; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) } Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-119
fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); if((cc%(bps*stride))!=0) { TIFFErrorExt(tif->tif_clientdata, "fpDiff", "%s", "(cc%(bps*stride))!=0"); return 0; } if (!tmp) return 0; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) return 1; }
166,881
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long ssl_get_algorithm2(SSL *s) { long alg2 = s->s3->tmp.new_cipher->algorithm2; if (TLS1_get_version(s) >= TLS1_2_VERSION && alg2 == (SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF)) return SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256; return alg2; } Commit Message: CWE ID: CWE-310
long ssl_get_algorithm2(SSL *s) { long alg2 = s->s3->tmp.new_cipher->algorithm2; if (s->method->version == TLS1_2_VERSION && alg2 == (SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF)) return SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256; return alg2; }
164,567
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const Track* Tracks::GetTrackByNumber(long tn) const { if (tn < 0) return NULL; Track** i = m_trackEntries; Track** const j = m_trackEntriesEnd; while (i != j) { Track* const pTrack = *i++; if (pTrack == NULL) continue; if (tn == pTrack->GetNumber()) return pTrack; } return NULL; //not found } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const Track* Tracks::GetTrackByNumber(long tn) const
174,371
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int magicmouse_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *data, int size) { struct magicmouse_sc *msc = hid_get_drvdata(hdev); struct input_dev *input = msc->input; int x = 0, y = 0, ii, clicks = 0, npoints; switch (data[0]) { case TRACKPAD_REPORT_ID: /* Expect four bytes of prefix, and N*9 bytes of touch data. */ if (size < 4 || ((size - 4) % 9) != 0) return 0; npoints = (size - 4) / 9; msc->ntouches = 0; for (ii = 0; ii < npoints; ii++) magicmouse_emit_touch(msc, ii, data + ii * 9 + 4); clicks = data[1]; /* The following bits provide a device specific timestamp. They * are unused here. * * ts = data[1] >> 6 | data[2] << 2 | data[3] << 10; */ break; case MOUSE_REPORT_ID: /* Expect six bytes of prefix, and N*8 bytes of touch data. */ if (size < 6 || ((size - 6) % 8) != 0) return 0; npoints = (size - 6) / 8; msc->ntouches = 0; for (ii = 0; ii < npoints; ii++) magicmouse_emit_touch(msc, ii, data + ii * 8 + 6); /* When emulating three-button mode, it is important * to have the current touch information before * generating a click event. */ x = (int)(((data[3] & 0x0c) << 28) | (data[1] << 22)) >> 22; y = (int)(((data[3] & 0x30) << 26) | (data[2] << 22)) >> 22; clicks = data[3]; /* The following bits provide a device specific timestamp. They * are unused here. * * ts = data[3] >> 6 | data[4] << 2 | data[5] << 10; */ break; case DOUBLE_REPORT_ID: /* Sometimes the trackpad sends two touch reports in one * packet. */ magicmouse_raw_event(hdev, report, data + 2, data[1]); magicmouse_raw_event(hdev, report, data + 2 + data[1], size - 2 - data[1]); break; default: return 0; } if (input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE) { magicmouse_emit_buttons(msc, clicks & 3); input_report_rel(input, REL_X, x); input_report_rel(input, REL_Y, y); } else { /* USB_DEVICE_ID_APPLE_MAGICTRACKPAD */ input_report_key(input, BTN_MOUSE, clicks & 1); input_mt_report_pointer_emulation(input, true); } input_sync(input); return 1; } Commit Message: HID: magicmouse: sanity check report size in raw_event() callback The report passed to us from transport driver could potentially be arbitrarily large, therefore we better sanity-check it so that magicmouse_emit_touch() gets only valid values of raw_id. Cc: [email protected] Reported-by: Steven Vittitoe <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119
static int magicmouse_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *data, int size) { struct magicmouse_sc *msc = hid_get_drvdata(hdev); struct input_dev *input = msc->input; int x = 0, y = 0, ii, clicks = 0, npoints; switch (data[0]) { case TRACKPAD_REPORT_ID: /* Expect four bytes of prefix, and N*9 bytes of touch data. */ if (size < 4 || ((size - 4) % 9) != 0) return 0; npoints = (size - 4) / 9; if (npoints > 15) { hid_warn(hdev, "invalid size value (%d) for TRACKPAD_REPORT_ID\n", size); return 0; } msc->ntouches = 0; for (ii = 0; ii < npoints; ii++) magicmouse_emit_touch(msc, ii, data + ii * 9 + 4); clicks = data[1]; /* The following bits provide a device specific timestamp. They * are unused here. * * ts = data[1] >> 6 | data[2] << 2 | data[3] << 10; */ break; case MOUSE_REPORT_ID: /* Expect six bytes of prefix, and N*8 bytes of touch data. */ if (size < 6 || ((size - 6) % 8) != 0) return 0; npoints = (size - 6) / 8; if (npoints > 15) { hid_warn(hdev, "invalid size value (%d) for MOUSE_REPORT_ID\n", size); return 0; } msc->ntouches = 0; for (ii = 0; ii < npoints; ii++) magicmouse_emit_touch(msc, ii, data + ii * 8 + 6); /* When emulating three-button mode, it is important * to have the current touch information before * generating a click event. */ x = (int)(((data[3] & 0x0c) << 28) | (data[1] << 22)) >> 22; y = (int)(((data[3] & 0x30) << 26) | (data[2] << 22)) >> 22; clicks = data[3]; /* The following bits provide a device specific timestamp. They * are unused here. * * ts = data[3] >> 6 | data[4] << 2 | data[5] << 10; */ break; case DOUBLE_REPORT_ID: /* Sometimes the trackpad sends two touch reports in one * packet. */ magicmouse_raw_event(hdev, report, data + 2, data[1]); magicmouse_raw_event(hdev, report, data + 2 + data[1], size - 2 - data[1]); break; default: return 0; } if (input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE) { magicmouse_emit_buttons(msc, clicks & 3); input_report_rel(input, REL_X, x); input_report_rel(input, REL_Y, y); } else { /* USB_DEVICE_ID_APPLE_MAGICTRACKPAD */ input_report_key(input, BTN_MOUSE, clicks & 1); input_mt_report_pointer_emulation(input, true); } input_sync(input); return 1; }
166,379
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: uint32_t GetPayloadTime(size_t handle, uint32_t index, float *in, float *out) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return 0; if (mp4->metaoffsets == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 1; *in = (float)((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon); *out = (float)((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon); return 0; } Commit Message: fixed many security issues with the too crude mp4 reader CWE ID: CWE-787
uint32_t GetPayloadTime(size_t handle, uint32_t index, float *in, float *out) uint32_t GetPayloadTime(size_t handle, uint32_t index, double *in, double *out) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return GPMF_ERROR_MEMORY; if (mp4->metaoffsets == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return GPMF_ERROR_MEMORY; *in = ((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon); *out = ((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon); return GPMF_OK; }
169,549
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int user_update(struct key *key, struct key_preparsed_payload *prep) { struct user_key_payload *zap = NULL; int ret; /* check the quota and attach the new data */ ret = key_payload_reserve(key, prep->datalen); if (ret < 0) return ret; /* attach the new data, displacing the old */ key->expiry = prep->expiry; if (!test_bit(KEY_FLAG_NEGATIVE, &key->flags)) zap = dereference_key_locked(key); rcu_assign_keypointer(key, prep->payload.data[0]); prep->payload.data[0] = NULL; if (zap) call_rcu(&zap->rcu, user_free_payload_rcu); return ret; } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20
int user_update(struct key *key, struct key_preparsed_payload *prep) { struct user_key_payload *zap = NULL; int ret; /* check the quota and attach the new data */ ret = key_payload_reserve(key, prep->datalen); if (ret < 0) return ret; /* attach the new data, displacing the old */ key->expiry = prep->expiry; if (key_is_positive(key)) zap = dereference_key_locked(key); rcu_assign_keypointer(key, prep->payload.data[0]); prep->payload.data[0] = NULL; if (zap) call_rcu(&zap->rcu, user_free_payload_rcu); return ret; }
167,710
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: FramebufferInfoTest() : manager_(1, 1), feature_info_(new FeatureInfo()), renderbuffer_manager_(NULL, kMaxRenderbufferSize, kMaxSamples, kDepth24Supported) { texture_manager_.reset(new TextureManager(NULL, feature_info_.get(), kMaxTextureSize, kMaxCubemapSize, kUseDefaultTextures)); } Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled. This is when we expose DrawBuffers extension. BUG=376951 TEST=the attached test case, webgl conformance [email protected],[email protected] Review URL: https://codereview.chromium.org/315283002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
FramebufferInfoTest() : manager_(kMaxDrawBuffers, kMaxColorAttachments), feature_info_(new FeatureInfo()), renderbuffer_manager_(NULL, kMaxRenderbufferSize, kMaxSamples, kDepth24Supported) { texture_manager_.reset(new TextureManager(NULL, feature_info_.get(), kMaxTextureSize, kMaxCubemapSize, kUseDefaultTextures)); }
171,656
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_hunkmax (void) { if (!p_line) p_line = (char **) malloc (hunkmax * sizeof *p_line); if (!p_len) p_len = (size_t *) malloc (hunkmax * sizeof *p_len); if (!p_Char) p_Char = malloc (hunkmax * sizeof *p_Char); } Commit Message: CWE ID: CWE-399
set_hunkmax (void) { if (!p_line) p_line = (char **) xmalloc (hunkmax * sizeof *p_line); if (!p_len) p_len = (size_t *) xmalloc (hunkmax * sizeof *p_len); if (!p_Char) p_Char = xmalloc (hunkmax * sizeof *p_Char); }
165,401
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: LocalSiteCharacteristicsWebContentsObserverTest() { scoped_feature_list_.InitAndEnableFeature( features::kSiteCharacteristicsDatabase); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
LocalSiteCharacteristicsWebContentsObserverTest() {
172,217
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 scoped_refptr<ui::Texture> CreateTransportClient( const gfx::Size& size, float device_scale_factor, uint64 transport_handle) { if (!shared_context_.get()) return NULL; scoped_refptr<ImageTransportClientTexture> image( new ImageTransportClientTexture(shared_context_.get(), size, device_scale_factor, transport_handle)); return image; } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
virtual scoped_refptr<ui::Texture> CreateTransportClient( const gfx::Size& size, float device_scale_factor, const std::string& mailbox_name) { if (!shared_context_.get()) return NULL; scoped_refptr<ImageTransportClientTexture> image( new ImageTransportClientTexture(shared_context_.get(), size, device_scale_factor, mailbox_name)); return image; }
171,361
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void SetUpCommandLine(CommandLine* command_line) { GpuFeatureTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kEnableThreadedCompositing); } Commit Message: Revert 124346 - Add basic threaded compositor test to gpu_feature_browsertest.cc BUG=113159 Review URL: http://codereview.chromium.org/9509001 [email protected] Review URL: https://chromiumcodereview.appspot.com/9561011 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@124356 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
virtual void SetUpCommandLine(CommandLine* command_line) {
170,959
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 print_bpf_insn(struct bpf_insn *insn) { u8 class = BPF_CLASS(insn->code); if (class == BPF_ALU || class == BPF_ALU64) { if (BPF_SRC(insn->code) == BPF_X) verbose("(%02x) %sr%d %s %sr%d\n", insn->code, class == BPF_ALU ? "(u32) " : "", insn->dst_reg, bpf_alu_string[BPF_OP(insn->code) >> 4], class == BPF_ALU ? "(u32) " : "", insn->src_reg); else verbose("(%02x) %sr%d %s %s%d\n", insn->code, class == BPF_ALU ? "(u32) " : "", insn->dst_reg, bpf_alu_string[BPF_OP(insn->code) >> 4], class == BPF_ALU ? "(u32) " : "", insn->imm); } else if (class == BPF_STX) { if (BPF_MODE(insn->code) == BPF_MEM) verbose("(%02x) *(%s *)(r%d %+d) = r%d\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->dst_reg, insn->off, insn->src_reg); else if (BPF_MODE(insn->code) == BPF_XADD) verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->dst_reg, insn->off, insn->src_reg); else verbose("BUG_%02x\n", insn->code); } else if (class == BPF_ST) { if (BPF_MODE(insn->code) != BPF_MEM) { verbose("BUG_st_%02x\n", insn->code); return; } verbose("(%02x) *(%s *)(r%d %+d) = %d\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->dst_reg, insn->off, insn->imm); } else if (class == BPF_LDX) { if (BPF_MODE(insn->code) != BPF_MEM) { verbose("BUG_ldx_%02x\n", insn->code); return; } verbose("(%02x) r%d = *(%s *)(r%d %+d)\n", insn->code, insn->dst_reg, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->src_reg, insn->off); } else if (class == BPF_LD) { if (BPF_MODE(insn->code) == BPF_ABS) { verbose("(%02x) r0 = *(%s *)skb[%d]\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->imm); } else if (BPF_MODE(insn->code) == BPF_IND) { verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->src_reg, insn->imm); } else if (BPF_MODE(insn->code) == BPF_IMM) { verbose("(%02x) r%d = 0x%x\n", insn->code, insn->dst_reg, insn->imm); } else { verbose("BUG_ld_%02x\n", insn->code); return; } } else if (class == BPF_JMP) { u8 opcode = BPF_OP(insn->code); if (opcode == BPF_CALL) { verbose("(%02x) call %s#%d\n", insn->code, func_id_name(insn->imm), insn->imm); } else if (insn->code == (BPF_JMP | BPF_JA)) { verbose("(%02x) goto pc%+d\n", insn->code, insn->off); } else if (insn->code == (BPF_JMP | BPF_EXIT)) { verbose("(%02x) exit\n", insn->code); } else if (BPF_SRC(insn->code) == BPF_X) { verbose("(%02x) if r%d %s r%d goto pc%+d\n", insn->code, insn->dst_reg, bpf_jmp_string[BPF_OP(insn->code) >> 4], insn->src_reg, insn->off); } else { verbose("(%02x) if r%d %s 0x%x goto pc%+d\n", insn->code, insn->dst_reg, bpf_jmp_string[BPF_OP(insn->code) >> 4], insn->imm, insn->off); } } else { verbose("(%02x) %s\n", insn->code, bpf_class_string[class]); } } Commit Message: bpf: don't let ldimm64 leak map addresses on unprivileged The patch fixes two things at once: 1) It checks the env->allow_ptr_leaks and only prints the map address to the log if we have the privileges to do so, otherwise it just dumps 0 as we would when kptr_restrict is enabled on %pK. Given the latter is off by default and not every distro sets it, I don't want to rely on this, hence the 0 by default for unprivileged. 2) Printing of ldimm64 in the verifier log is currently broken in that we don't print the full immediate, but only the 32 bit part of the first insn part for ldimm64. Thus, fix this up as well; it's okay to access, since we verified all ldimm64 earlier already (including just constants) through replace_map_fd_with_map_ptr(). Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Fixes: cbd357008604 ("bpf: verifier (add ability to receive verification log)") Reported-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Alexei Starovoitov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static void print_bpf_insn(struct bpf_insn *insn) static void print_bpf_insn(const struct bpf_verifier_env *env, const struct bpf_insn *insn) { u8 class = BPF_CLASS(insn->code); if (class == BPF_ALU || class == BPF_ALU64) { if (BPF_SRC(insn->code) == BPF_X) verbose("(%02x) %sr%d %s %sr%d\n", insn->code, class == BPF_ALU ? "(u32) " : "", insn->dst_reg, bpf_alu_string[BPF_OP(insn->code) >> 4], class == BPF_ALU ? "(u32) " : "", insn->src_reg); else verbose("(%02x) %sr%d %s %s%d\n", insn->code, class == BPF_ALU ? "(u32) " : "", insn->dst_reg, bpf_alu_string[BPF_OP(insn->code) >> 4], class == BPF_ALU ? "(u32) " : "", insn->imm); } else if (class == BPF_STX) { if (BPF_MODE(insn->code) == BPF_MEM) verbose("(%02x) *(%s *)(r%d %+d) = r%d\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->dst_reg, insn->off, insn->src_reg); else if (BPF_MODE(insn->code) == BPF_XADD) verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->dst_reg, insn->off, insn->src_reg); else verbose("BUG_%02x\n", insn->code); } else if (class == BPF_ST) { if (BPF_MODE(insn->code) != BPF_MEM) { verbose("BUG_st_%02x\n", insn->code); return; } verbose("(%02x) *(%s *)(r%d %+d) = %d\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->dst_reg, insn->off, insn->imm); } else if (class == BPF_LDX) { if (BPF_MODE(insn->code) != BPF_MEM) { verbose("BUG_ldx_%02x\n", insn->code); return; } verbose("(%02x) r%d = *(%s *)(r%d %+d)\n", insn->code, insn->dst_reg, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->src_reg, insn->off); } else if (class == BPF_LD) { if (BPF_MODE(insn->code) == BPF_ABS) { verbose("(%02x) r0 = *(%s *)skb[%d]\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->imm); } else if (BPF_MODE(insn->code) == BPF_IND) { verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->src_reg, insn->imm); } else if (BPF_MODE(insn->code) == BPF_IMM && BPF_SIZE(insn->code) == BPF_DW) { /* At this point, we already made sure that the second * part of the ldimm64 insn is accessible. */ u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD; if (map_ptr && !env->allow_ptr_leaks) imm = 0; verbose("(%02x) r%d = 0x%llx\n", insn->code, insn->dst_reg, (unsigned long long)imm); } else { verbose("BUG_ld_%02x\n", insn->code); return; } } else if (class == BPF_JMP) { u8 opcode = BPF_OP(insn->code); if (opcode == BPF_CALL) { verbose("(%02x) call %s#%d\n", insn->code, func_id_name(insn->imm), insn->imm); } else if (insn->code == (BPF_JMP | BPF_JA)) { verbose("(%02x) goto pc%+d\n", insn->code, insn->off); } else if (insn->code == (BPF_JMP | BPF_EXIT)) { verbose("(%02x) exit\n", insn->code); } else if (BPF_SRC(insn->code) == BPF_X) { verbose("(%02x) if r%d %s r%d goto pc%+d\n", insn->code, insn->dst_reg, bpf_jmp_string[BPF_OP(insn->code) >> 4], insn->src_reg, insn->off); } else { verbose("(%02x) if r%d %s 0x%x goto pc%+d\n", insn->code, insn->dst_reg, bpf_jmp_string[BPF_OP(insn->code) >> 4], insn->imm, insn->off); } } else { verbose("(%02x) %s\n", insn->code, bpf_class_string[class]); } }
168,121
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int kvm_vm_ioctl_assign_device(struct kvm *kvm, struct kvm_assigned_pci_dev *assigned_dev) { int r = 0, idx; struct kvm_assigned_dev_kernel *match; struct pci_dev *dev; if (!(assigned_dev->flags & KVM_DEV_ASSIGN_ENABLE_IOMMU)) return -EINVAL; mutex_lock(&kvm->lock); idx = srcu_read_lock(&kvm->srcu); match = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head, assigned_dev->assigned_dev_id); if (match) { /* device already assigned */ r = -EEXIST; goto out; } match = kzalloc(sizeof(struct kvm_assigned_dev_kernel), GFP_KERNEL); if (match == NULL) { printk(KERN_INFO "%s: Couldn't allocate memory\n", __func__); r = -ENOMEM; goto out; } dev = pci_get_domain_bus_and_slot(assigned_dev->segnr, assigned_dev->busnr, assigned_dev->devfn); if (!dev) { printk(KERN_INFO "%s: host device not found\n", __func__); r = -EINVAL; goto out_free; } if (pci_enable_device(dev)) { printk(KERN_INFO "%s: Could not enable PCI device\n", __func__); r = -EBUSY; goto out_put; } r = pci_request_regions(dev, "kvm_assigned_device"); if (r) { printk(KERN_INFO "%s: Could not get access to device regions\n", __func__); goto out_disable; } pci_reset_function(dev); pci_save_state(dev); match->pci_saved_state = pci_store_saved_state(dev); if (!match->pci_saved_state) printk(KERN_DEBUG "%s: Couldn't store %s saved state\n", __func__, dev_name(&dev->dev)); match->assigned_dev_id = assigned_dev->assigned_dev_id; match->host_segnr = assigned_dev->segnr; match->host_busnr = assigned_dev->busnr; match->host_devfn = assigned_dev->devfn; match->flags = assigned_dev->flags; match->dev = dev; spin_lock_init(&match->intx_lock); match->irq_source_id = -1; match->kvm = kvm; match->ack_notifier.irq_acked = kvm_assigned_dev_ack_irq; list_add(&match->list, &kvm->arch.assigned_dev_head); if (!kvm->arch.iommu_domain) { r = kvm_iommu_map_guest(kvm); if (r) goto out_list_del; } r = kvm_assign_device(kvm, match); if (r) goto out_list_del; out: srcu_read_unlock(&kvm->srcu, idx); mutex_unlock(&kvm->lock); return r; out_list_del: if (pci_load_and_free_saved_state(dev, &match->pci_saved_state)) printk(KERN_INFO "%s: Couldn't reload %s saved state\n", __func__, dev_name(&dev->dev)); list_del(&match->list); pci_release_regions(dev); out_disable: pci_disable_device(dev); out_put: pci_dev_put(dev); out_free: kfree(match); srcu_read_unlock(&kvm->srcu, idx); mutex_unlock(&kvm->lock); return r; } Commit Message: KVM: Device assignment permission checks (cherry picked from commit 3d27e23b17010c668db311140b17bbbb70c78fb9) Only allow KVM device assignment to attach to devices which: - Are not bridges - Have BAR resources (assume others are special devices) - The user has permissions to use Assigning a bridge is a configuration error, it's not supported, and typically doesn't result in the behavior the user is expecting anyway. Devices without BAR resources are typically chipset components that also don't have host drivers. We don't want users to hold such devices captive or cause system problems by fencing them off into an iommu domain. We determine "permission to use" by testing whether the user has access to the PCI sysfs resource files. By default a normal user will not have access to these files, so it provides a good indication that an administration agent has granted the user access to the device. [Yang Bai: add missing #include] [avi: fix comment style] Signed-off-by: Alex Williamson <[email protected]> Signed-off-by: Yang Bai <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264
static int kvm_vm_ioctl_assign_device(struct kvm *kvm, struct kvm_assigned_pci_dev *assigned_dev) { int r = 0, idx; struct kvm_assigned_dev_kernel *match; struct pci_dev *dev; u8 header_type; if (!(assigned_dev->flags & KVM_DEV_ASSIGN_ENABLE_IOMMU)) return -EINVAL; mutex_lock(&kvm->lock); idx = srcu_read_lock(&kvm->srcu); match = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head, assigned_dev->assigned_dev_id); if (match) { /* device already assigned */ r = -EEXIST; goto out; } match = kzalloc(sizeof(struct kvm_assigned_dev_kernel), GFP_KERNEL); if (match == NULL) { printk(KERN_INFO "%s: Couldn't allocate memory\n", __func__); r = -ENOMEM; goto out; } dev = pci_get_domain_bus_and_slot(assigned_dev->segnr, assigned_dev->busnr, assigned_dev->devfn); if (!dev) { printk(KERN_INFO "%s: host device not found\n", __func__); r = -EINVAL; goto out_free; } /* Don't allow bridges to be assigned */ pci_read_config_byte(dev, PCI_HEADER_TYPE, &header_type); if ((header_type & PCI_HEADER_TYPE) != PCI_HEADER_TYPE_NORMAL) { r = -EPERM; goto out_put; } r = probe_sysfs_permissions(dev); if (r) goto out_put; if (pci_enable_device(dev)) { printk(KERN_INFO "%s: Could not enable PCI device\n", __func__); r = -EBUSY; goto out_put; } r = pci_request_regions(dev, "kvm_assigned_device"); if (r) { printk(KERN_INFO "%s: Could not get access to device regions\n", __func__); goto out_disable; } pci_reset_function(dev); pci_save_state(dev); match->pci_saved_state = pci_store_saved_state(dev); if (!match->pci_saved_state) printk(KERN_DEBUG "%s: Couldn't store %s saved state\n", __func__, dev_name(&dev->dev)); match->assigned_dev_id = assigned_dev->assigned_dev_id; match->host_segnr = assigned_dev->segnr; match->host_busnr = assigned_dev->busnr; match->host_devfn = assigned_dev->devfn; match->flags = assigned_dev->flags; match->dev = dev; spin_lock_init(&match->intx_lock); match->irq_source_id = -1; match->kvm = kvm; match->ack_notifier.irq_acked = kvm_assigned_dev_ack_irq; list_add(&match->list, &kvm->arch.assigned_dev_head); if (!kvm->arch.iommu_domain) { r = kvm_iommu_map_guest(kvm); if (r) goto out_list_del; } r = kvm_assign_device(kvm, match); if (r) goto out_list_del; out: srcu_read_unlock(&kvm->srcu, idx); mutex_unlock(&kvm->lock); return r; out_list_del: if (pci_load_and_free_saved_state(dev, &match->pci_saved_state)) printk(KERN_INFO "%s: Couldn't reload %s saved state\n", __func__, dev_name(&dev->dev)); list_del(&match->list); pci_release_regions(dev); out_disable: pci_disable_device(dev); out_put: pci_dev_put(dev); out_free: kfree(match); srcu_read_unlock(&kvm->srcu, idx); mutex_unlock(&kvm->lock); return r; }
166,209
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport MagickBooleanType DrawClipPath(Image *image, const DrawInfo *draw_info,const char *name,ExceptionInfo *exception) { char filename[MagickPathExtent]; Image *clip_mask; const char *value; DrawInfo *clone_info; MagickStatusType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); (void) FormatLocaleString(filename,MagickPathExtent,"%s",name); value=GetImageArtifact(image,filename); if (value == (const char *) NULL) return(MagickFalse); clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (clip_mask == (Image *) NULL) return(MagickFalse); (void) QueryColorCompliance("#0000",AllCompliance, &clip_mask->background_color,exception); clip_mask->background_color.alpha=(Quantum) TransparentAlpha; (void) SetImageBackgroundColor(clip_mask,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s", draw_info->clip_mask); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,value); (void) QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill, exception); clone_info->clip_mask=(char *) NULL; status=NegateImage(clip_mask,MagickFalse,exception); (void) SetImageMask(image,ReadPixelMask,clip_mask,exception); clip_mask=DestroyImage(clip_mask); status&=DrawImage(image,clone_info,exception); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path"); return(status != 0 ? MagickTrue : MagickFalse); } Commit Message: Prevent buffer overflow in magick/draw.c CWE ID: CWE-119
MagickExport MagickBooleanType DrawClipPath(Image *image, const DrawInfo *draw_info,const char *name,ExceptionInfo *exception) { char filename[MagickPathExtent]; Image *clip_mask; const char *value; DrawInfo *clone_info; MagickStatusType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); (void) FormatLocaleString(filename,MagickPathExtent,"%s",name); value=GetImageArtifact(image,filename); if (value == (const char *) NULL) return(MagickFalse); clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (clip_mask == (Image *) NULL) return(MagickFalse); (void) QueryColorCompliance("#0000",AllCompliance, &clip_mask->background_color,exception); clip_mask->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(clip_mask,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s", draw_info->clip_mask); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,value); (void) QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill, exception); clone_info->clip_mask=(char *) NULL; status=NegateImage(clip_mask,MagickFalse,exception); (void) SetImageMask(image,ReadPixelMask,clip_mask,exception); clip_mask=DestroyImage(clip_mask); status&=DrawImage(image,clone_info,exception); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path"); return(status != 0 ? MagickTrue : MagickFalse); }
167,243
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 wdm_in_callback(struct urb *urb) { struct wdm_device *desc = urb->context; int status = urb->status; spin_lock(&desc->iuspin); clear_bit(WDM_RESPONDING, &desc->flags); if (status) { switch (status) { case -ENOENT: dev_dbg(&desc->intf->dev, "nonzero urb status received: -ENOENT"); goto skip_error; case -ECONNRESET: dev_dbg(&desc->intf->dev, "nonzero urb status received: -ECONNRESET"); goto skip_error; case -ESHUTDOWN: dev_dbg(&desc->intf->dev, "nonzero urb status received: -ESHUTDOWN"); goto skip_error; case -EPIPE: dev_err(&desc->intf->dev, "nonzero urb status received: -EPIPE\n"); break; default: dev_err(&desc->intf->dev, "Unexpected error %d\n", status); break; } } desc->rerr = status; desc->reslength = urb->actual_length; memmove(desc->ubuf + desc->length, desc->inbuf, desc->reslength); desc->length += desc->reslength; skip_error: wake_up(&desc->wait); set_bit(WDM_READ, &desc->flags); spin_unlock(&desc->iuspin); } Commit Message: USB: cdc-wdm: fix buffer overflow The buffer for responses must not overflow. If this would happen, set a flag, drop the data and return an error after user space has read all remaining data. Signed-off-by: Oliver Neukum <[email protected]> CC: [email protected] Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-119
static void wdm_in_callback(struct urb *urb) { struct wdm_device *desc = urb->context; int status = urb->status; int length = urb->actual_length; spin_lock(&desc->iuspin); clear_bit(WDM_RESPONDING, &desc->flags); if (status) { switch (status) { case -ENOENT: dev_dbg(&desc->intf->dev, "nonzero urb status received: -ENOENT"); goto skip_error; case -ECONNRESET: dev_dbg(&desc->intf->dev, "nonzero urb status received: -ECONNRESET"); goto skip_error; case -ESHUTDOWN: dev_dbg(&desc->intf->dev, "nonzero urb status received: -ESHUTDOWN"); goto skip_error; case -EPIPE: dev_err(&desc->intf->dev, "nonzero urb status received: -EPIPE\n"); break; default: dev_err(&desc->intf->dev, "Unexpected error %d\n", status); break; } } desc->rerr = status; if (length + desc->length > desc->wMaxCommand) { /* The buffer would overflow */ set_bit(WDM_OVERFLOW, &desc->flags); } else { /* we may already be in overflow */ if (!test_bit(WDM_OVERFLOW, &desc->flags)) { memmove(desc->ubuf + desc->length, desc->inbuf, length); desc->length += length; desc->reslength = length; } } skip_error: wake_up(&desc->wait); set_bit(WDM_READ, &desc->flags); spin_unlock(&desc->iuspin); }
166,103
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebRtcAudioRenderer::Initialize(WebRtcAudioRendererSource* source) { base::AutoLock auto_lock(lock_); DCHECK_EQ(state_, UNINITIALIZED); DCHECK(source); DCHECK(!sink_); DCHECK(!source_); sink_ = AudioDeviceFactory::NewOutputDevice(); DCHECK(sink_); int sample_rate = GetAudioOutputSampleRate(); DVLOG(1) << "Audio output hardware sample rate: " << sample_rate; UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputSampleRate", sample_rate, media::kUnexpectedAudioSampleRate); if (std::find(&kValidOutputRates[0], &kValidOutputRates[0] + arraysize(kValidOutputRates), sample_rate) == &kValidOutputRates[arraysize(kValidOutputRates)]) { DLOG(ERROR) << sample_rate << " is not a supported output rate."; return false; } media::ChannelLayout channel_layout = media::CHANNEL_LAYOUT_STEREO; int buffer_size = 0; #if defined(OS_WIN) channel_layout = media::CHANNEL_LAYOUT_STEREO; if (sample_rate == 96000 || sample_rate == 48000) { buffer_size = (sample_rate / 100); } else { buffer_size = 2 * 440; } if (base::win::GetVersion() < base::win::VERSION_VISTA) { buffer_size = 3 * buffer_size; DLOG(WARNING) << "Extending the output buffer size by a factor of three " << "since Windows XP has been detected."; } #elif defined(OS_MACOSX) channel_layout = media::CHANNEL_LAYOUT_MONO; if (sample_rate == 48000) { buffer_size = 480; } else { buffer_size = 440; } #elif defined(OS_LINUX) || defined(OS_OPENBSD) channel_layout = media::CHANNEL_LAYOUT_MONO; buffer_size = 480; #else DLOG(ERROR) << "Unsupported platform"; return false; #endif params_.Reset(media::AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout, sample_rate, 16, buffer_size); buffer_.reset(new int16[params_.frames_per_buffer() * params_.channels()]); source_ = source; source->SetRenderFormat(params_); sink_->Initialize(params_, this); sink_->SetSourceRenderView(source_render_view_id_); sink_->Start(); state_ = PAUSED; UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputChannelLayout", channel_layout, media::CHANNEL_LAYOUT_MAX); UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputFramesPerBuffer", buffer_size, kUnexpectedAudioBufferSize); AddHistogramFramesPerBuffer(buffer_size); return true; } Commit Message: Avoids crash in WebRTC audio clients for 96kHz render rate on Mac OSX. TBR=xians BUG=166523 TEST=Misc set of WebRTC audio clients on Mac. Review URL: https://codereview.chromium.org/11773017 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@175323 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool WebRtcAudioRenderer::Initialize(WebRtcAudioRendererSource* source) { base::AutoLock auto_lock(lock_); DCHECK_EQ(state_, UNINITIALIZED); DCHECK(source); DCHECK(!sink_); DCHECK(!source_); sink_ = AudioDeviceFactory::NewOutputDevice(); DCHECK(sink_); int sample_rate = GetAudioOutputSampleRate(); DVLOG(1) << "Audio output hardware sample rate: " << sample_rate; UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputSampleRate", sample_rate, media::kUnexpectedAudioSampleRate); if (std::find(&kValidOutputRates[0], &kValidOutputRates[0] + arraysize(kValidOutputRates), sample_rate) == &kValidOutputRates[arraysize(kValidOutputRates)]) { DLOG(ERROR) << sample_rate << " is not a supported output rate."; return false; } media::ChannelLayout channel_layout = media::CHANNEL_LAYOUT_STEREO; int buffer_size = 0; #if defined(OS_WIN) channel_layout = media::CHANNEL_LAYOUT_STEREO; if (sample_rate == 96000 || sample_rate == 48000) { buffer_size = (sample_rate / 100); } else { buffer_size = 2 * 440; } if (base::win::GetVersion() < base::win::VERSION_VISTA) { buffer_size = 3 * buffer_size; DLOG(WARNING) << "Extending the output buffer size by a factor of three " << "since Windows XP has been detected."; } #elif defined(OS_MACOSX) channel_layout = media::CHANNEL_LAYOUT_MONO; // frame size to use for 96kHz, 48kHz and 44.1kHz. if (sample_rate == 96000 || sample_rate == 48000) { buffer_size = (sample_rate / 100); } else { buffer_size = 440; } #elif defined(OS_LINUX) || defined(OS_OPENBSD) channel_layout = media::CHANNEL_LAYOUT_MONO; buffer_size = 480; #else DLOG(ERROR) << "Unsupported platform"; return false; #endif params_.Reset(media::AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout, sample_rate, 16, buffer_size); buffer_.reset(new int16[params_.frames_per_buffer() * params_.channels()]); source_ = source; source->SetRenderFormat(params_); sink_->Initialize(params_, this); sink_->SetSourceRenderView(source_render_view_id_); sink_->Start(); state_ = PAUSED; UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputChannelLayout", channel_layout, media::CHANNEL_LAYOUT_MAX); UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputFramesPerBuffer", buffer_size, kUnexpectedAudioBufferSize); AddHistogramFramesPerBuffer(buffer_size); return true; }
171,502
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_string_2_svc(sstring_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY, arg->princ, NULL)) { ret.code = KADM5_AUTH_MODIFY; log_unauth("kadm5_mod_strings", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_set_string((void *)handle, arg->princ, arg->key, arg->value); if (ret.code != 0) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_mod_strings", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
set_string_2_svc(sstring_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY, arg->princ, NULL)) { ret.code = KADM5_AUTH_MODIFY; log_unauth("kadm5_mod_strings", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_set_string((void *)handle, arg->princ, arg->key, arg->value); if (ret.code != 0) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_mod_strings", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,524
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 InputEngine::ProcessText(const std::string& message, ProcessTextCallback callback) { NOTIMPLEMENTED(); // Text message not used in the rulebased engine. } Commit Message: ime-service: Delete InputEngine.ProcessText. It is deprecated and no longer used. Bug: 1009903 Change-Id: I6774a4506bd0bb41a5d1a5909a40a2a781564b16 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1833029 Auto-Submit: Darren Shen <[email protected]> Reviewed-by: Chris Palmer <[email protected]> Reviewed-by: Keith Lee <[email protected]> Reviewed-by: Shu Chen <[email protected]> Commit-Queue: Darren Shen <[email protected]> Cr-Commit-Position: refs/heads/master@{#705445} CWE ID: CWE-125
void InputEngine::ProcessText(const std::string& message,
172,406
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ExtensionDevToolsClientHost::InfoBarDismissed() { detach_reason_ = api::debugger::DETACH_REASON_CANCELED_BY_USER; SendDetachedEvent(); Close(); } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. [email protected] Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20
void ExtensionDevToolsClientHost::InfoBarDismissed() { detach_reason_ = api::debugger::DETACH_REASON_CANCELED_BY_USER; RespondDetachedToPendingRequests(); SendDetachedEvent(); Close(); }
173,238
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ProxyLocaltimeCallToBrowser(time_t input, struct tm* output, char* timezone_out, size_t timezone_out_len) { base::Pickle request; request.WriteInt(LinuxSandbox::METHOD_LOCALTIME); request.WriteString( std::string(reinterpret_cast<char*>(&input), sizeof(input))); uint8_t reply_buf[512]; const ssize_t r = base::UnixDomainSocket::SendRecvMsg( GetSandboxFD(), reply_buf, sizeof(reply_buf), NULL, request); if (r == -1) { memset(output, 0, sizeof(struct tm)); return; } base::Pickle reply(reinterpret_cast<char*>(reply_buf), r); base::PickleIterator iter(reply); std::string result; std::string timezone; if (!iter.ReadString(&result) || !iter.ReadString(&timezone) || result.size() != sizeof(struct tm)) { memset(output, 0, sizeof(struct tm)); return; } memcpy(output, result.data(), sizeof(struct tm)); if (timezone_out_len) { const size_t copy_len = std::min(timezone_out_len - 1, timezone.size()); memcpy(timezone_out, timezone.data(), copy_len); timezone_out[copy_len] = 0; output->tm_zone = timezone_out; } else { base::AutoLock lock(g_timezones_lock.Get()); auto ret_pair = g_timezones.Get().insert(timezone); output->tm_zone = ret_pair.first->c_str(); } } Commit Message: Serialize struct tm in a safe way. BUG=765512 Change-Id: If235b8677eb527be2ac0fe621fc210e4116a7566 Reviewed-on: https://chromium-review.googlesource.com/679441 Commit-Queue: Chris Palmer <[email protected]> Reviewed-by: Julien Tinnes <[email protected]> Cr-Commit-Position: refs/heads/master@{#503948} CWE ID: CWE-119
static void ProxyLocaltimeCallToBrowser(time_t input, struct tm* output, char* timezone_out, size_t timezone_out_len) { base::Pickle request; request.WriteInt(LinuxSandbox::METHOD_LOCALTIME); request.WriteString( std::string(reinterpret_cast<char*>(&input), sizeof(input))); memset(output, 0, sizeof(struct tm)); uint8_t reply_buf[512]; const ssize_t r = base::UnixDomainSocket::SendRecvMsg( GetSandboxFD(), reply_buf, sizeof(reply_buf), NULL, request); if (r == -1) { return; } base::Pickle reply(reinterpret_cast<char*>(reply_buf), r); base::PickleIterator iter(reply); if (!ReadTimeStruct(&iter, output, timezone_out, timezone_out_len)) { memset(output, 0, sizeof(struct tm)); } }
172,926
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize, size_t pos, PNG_CONST char *msg) { if (pp != NULL && pp == ps->pread) { /* Reading a file */ pos = safecat(buffer, bufsize, pos, "read: "); if (ps->current != NULL) { pos = safecat(buffer, bufsize, pos, ps->current->name); pos = safecat(buffer, bufsize, pos, sep); } } else if (pp != NULL && pp == ps->pwrite) { /* Writing a file */ pos = safecat(buffer, bufsize, pos, "write: "); pos = safecat(buffer, bufsize, pos, ps->wname); pos = safecat(buffer, bufsize, pos, sep); } else { /* Neither reading nor writing (or a memory error in struct delete) */ pos = safecat(buffer, bufsize, pos, "pngvalid: "); } if (ps->test[0] != 0) { pos = safecat(buffer, bufsize, pos, ps->test); pos = safecat(buffer, bufsize, pos, sep); } pos = safecat(buffer, bufsize, pos, msg); return pos; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize, size_t pos, const char *msg) { if (pp != NULL && pp == ps->pread) { /* Reading a file */ pos = safecat(buffer, bufsize, pos, "read: "); if (ps->current != NULL) { pos = safecat(buffer, bufsize, pos, ps->current->name); pos = safecat(buffer, bufsize, pos, sep); } } else if (pp != NULL && pp == ps->pwrite) { /* Writing a file */ pos = safecat(buffer, bufsize, pos, "write: "); pos = safecat(buffer, bufsize, pos, ps->wname); pos = safecat(buffer, bufsize, pos, sep); } else { /* Neither reading nor writing (or a memory error in struct delete) */ pos = safecat(buffer, bufsize, pos, "pngvalid: "); } if (ps->test[0] != 0) { pos = safecat(buffer, bufsize, pos, ps->test); pos = safecat(buffer, bufsize, pos, sep); } pos = safecat(buffer, bufsize, pos, msg); return pos; }
173,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: static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFContext *mxf = arg; int item_num = avio_rb32(pb); int item_len = avio_rb32(pb); if (item_len != 18) { avpriv_request_sample(pb, "Primer pack item length %d", item_len); return AVERROR_PATCHWELCOME; } if (item_num > 65536) { av_log(mxf->fc, AV_LOG_ERROR, "item_num %d is too large\n", item_num); return AVERROR_INVALIDDATA; } if (mxf->local_tags) av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple primer packs\n"); av_free(mxf->local_tags); mxf->local_tags_count = 0; mxf->local_tags = av_calloc(item_num, item_len); if (!mxf->local_tags) return AVERROR(ENOMEM); mxf->local_tags_count = item_num; avio_read(pb, mxf->local_tags, item_num*item_len); return 0; } Commit Message: avformat/mxfdec: Fix Sign error in mxf_read_primer_pack() Fixes: 20170829B.mxf Co-Author: 张洪亮(望初)" <[email protected]> Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-20
static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFContext *mxf = arg; int item_num = avio_rb32(pb); int item_len = avio_rb32(pb); if (item_len != 18) { avpriv_request_sample(pb, "Primer pack item length %d", item_len); return AVERROR_PATCHWELCOME; } if (item_num > 65536 || item_num < 0) { av_log(mxf->fc, AV_LOG_ERROR, "item_num %d is too large\n", item_num); return AVERROR_INVALIDDATA; } if (mxf->local_tags) av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple primer packs\n"); av_free(mxf->local_tags); mxf->local_tags_count = 0; mxf->local_tags = av_calloc(item_num, item_len); if (!mxf->local_tags) return AVERROR(ENOMEM); mxf->local_tags_count = item_num; avio_read(pb, mxf->local_tags, item_num*item_len); return 0; }
167,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: static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int entries, i, j; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_rb32(pb); // version + flags entries = avio_rb32(pb); if (entries >= UINT_MAX / sizeof(*sc->drefs)) return AVERROR_INVALIDDATA; av_free(sc->drefs); sc->drefs = av_mallocz(entries * sizeof(*sc->drefs)); if (!sc->drefs) return AVERROR(ENOMEM); sc->drefs_count = entries; for (i = 0; i < sc->drefs_count; i++) { MOVDref *dref = &sc->drefs[i]; uint32_t size = avio_rb32(pb); int64_t next = avio_tell(pb) + size - 4; if (size < 12) return AVERROR_INVALIDDATA; dref->type = avio_rl32(pb); avio_rb32(pb); // version + flags av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size); if (dref->type == MKTAG('a','l','i','s') && size > 150) { /* macintosh alias record */ uint16_t volume_len, len; int16_t type; avio_skip(pb, 10); volume_len = avio_r8(pb); volume_len = FFMIN(volume_len, 27); avio_read(pb, dref->volume, 27); dref->volume[volume_len] = 0; av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len); avio_skip(pb, 12); len = avio_r8(pb); len = FFMIN(len, 63); avio_read(pb, dref->filename, 63); dref->filename[len] = 0; av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len); avio_skip(pb, 16); /* read next level up_from_alias/down_to_target */ dref->nlvl_from = avio_rb16(pb); dref->nlvl_to = avio_rb16(pb); av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n", dref->nlvl_from, dref->nlvl_to); avio_skip(pb, 16); for (type = 0; type != -1 && avio_tell(pb) < next; ) { if(url_feof(pb)) return AVERROR_EOF; type = avio_rb16(pb); len = avio_rb16(pb); av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len); if (len&1) len += 1; if (type == 2) { // absolute path av_free(dref->path); dref->path = av_mallocz(len+1); if (!dref->path) return AVERROR(ENOMEM); avio_read(pb, dref->path, len); if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) { len -= volume_len; memmove(dref->path, dref->path+volume_len, len); dref->path[len] = 0; } for (j = 0; j < len; j++) if (dref->path[j] == ':') dref->path[j] = '/'; av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path); } else if (type == 0) { // directory name av_free(dref->dir); dref->dir = av_malloc(len+1); if (!dref->dir) return AVERROR(ENOMEM); avio_read(pb, dref->dir, len); dref->dir[len] = 0; for (j = 0; j < len; j++) if (dref->dir[j] == ':') dref->dir[j] = '/'; av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir); } else avio_skip(pb, len); } } avio_seek(pb, next, SEEK_SET); } return 0; } Commit Message: mov: reset dref_count on realloc to keep values consistent. This fixes a potential crash. Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int entries, i, j; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_rb32(pb); // version + flags entries = avio_rb32(pb); if (entries >= UINT_MAX / sizeof(*sc->drefs)) return AVERROR_INVALIDDATA; av_free(sc->drefs); sc->drefs_count = 0; sc->drefs = av_mallocz(entries * sizeof(*sc->drefs)); if (!sc->drefs) return AVERROR(ENOMEM); sc->drefs_count = entries; for (i = 0; i < sc->drefs_count; i++) { MOVDref *dref = &sc->drefs[i]; uint32_t size = avio_rb32(pb); int64_t next = avio_tell(pb) + size - 4; if (size < 12) return AVERROR_INVALIDDATA; dref->type = avio_rl32(pb); avio_rb32(pb); // version + flags av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size); if (dref->type == MKTAG('a','l','i','s') && size > 150) { /* macintosh alias record */ uint16_t volume_len, len; int16_t type; avio_skip(pb, 10); volume_len = avio_r8(pb); volume_len = FFMIN(volume_len, 27); avio_read(pb, dref->volume, 27); dref->volume[volume_len] = 0; av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len); avio_skip(pb, 12); len = avio_r8(pb); len = FFMIN(len, 63); avio_read(pb, dref->filename, 63); dref->filename[len] = 0; av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len); avio_skip(pb, 16); /* read next level up_from_alias/down_to_target */ dref->nlvl_from = avio_rb16(pb); dref->nlvl_to = avio_rb16(pb); av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n", dref->nlvl_from, dref->nlvl_to); avio_skip(pb, 16); for (type = 0; type != -1 && avio_tell(pb) < next; ) { if(url_feof(pb)) return AVERROR_EOF; type = avio_rb16(pb); len = avio_rb16(pb); av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len); if (len&1) len += 1; if (type == 2) { // absolute path av_free(dref->path); dref->path = av_mallocz(len+1); if (!dref->path) return AVERROR(ENOMEM); avio_read(pb, dref->path, len); if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) { len -= volume_len; memmove(dref->path, dref->path+volume_len, len); dref->path[len] = 0; } for (j = 0; j < len; j++) if (dref->path[j] == ':') dref->path[j] = '/'; av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path); } else if (type == 0) { // directory name av_free(dref->dir); dref->dir = av_malloc(len+1); if (!dref->dir) return AVERROR(ENOMEM); avio_read(pb, dref->dir, len); dref->dir[len] = 0; for (j = 0; j < len; j++) if (dref->dir[j] == ':') dref->dir[j] = '/'; av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir); } else avio_skip(pb, len); } } avio_seek(pb, next, SEEK_SET); } return 0; }
167,385
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vfio_msi_enable(struct vfio_pci_device *vdev, int nvec, bool msix) { struct pci_dev *pdev = vdev->pdev; unsigned int flag = msix ? PCI_IRQ_MSIX : PCI_IRQ_MSI; int ret; if (!is_irq_none(vdev)) return -EINVAL; vdev->ctx = kzalloc(nvec * sizeof(struct vfio_pci_irq_ctx), GFP_KERNEL); if (!vdev->ctx) return -ENOMEM; /* return the number of supported vectors if we can't get all: */ ret = pci_alloc_irq_vectors(pdev, 1, nvec, flag); if (ret < nvec) { if (ret > 0) pci_free_irq_vectors(pdev); kfree(vdev->ctx); return ret; } vdev->num_ctx = nvec; vdev->irq_type = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX; if (!msix) { /* * Compute the virtual hardware field for max msi vectors - * it is the log base 2 of the number of vectors. */ vdev->msi_qmax = fls(nvec * 2 - 1) - 1; } return 0; } Commit Message: vfio/pci: Fix integer overflows, bitmask check The VFIO_DEVICE_SET_IRQS ioctl did not sufficiently sanitize user-supplied integers, potentially allowing memory corruption. This patch adds appropriate integer overflow checks, checks the range bounds for VFIO_IRQ_SET_DATA_NONE, and also verifies that only single element in the VFIO_IRQ_SET_DATA_TYPE_MASK bitmask is set. VFIO_IRQ_SET_ACTION_TYPE_MASK is already correctly checked later in vfio_pci_set_irqs_ioctl(). Furthermore, a kzalloc is changed to a kcalloc because the use of a kzalloc with an integer multiplication allowed an integer overflow condition to be reached without this patch. kcalloc checks for overflow and should prevent a similar occurrence. Signed-off-by: Vlad Tsyrklevich <[email protected]> Signed-off-by: Alex Williamson <[email protected]> CWE ID: CWE-190
static int vfio_msi_enable(struct vfio_pci_device *vdev, int nvec, bool msix) { struct pci_dev *pdev = vdev->pdev; unsigned int flag = msix ? PCI_IRQ_MSIX : PCI_IRQ_MSI; int ret; if (!is_irq_none(vdev)) return -EINVAL; vdev->ctx = kcalloc(nvec, sizeof(struct vfio_pci_irq_ctx), GFP_KERNEL); if (!vdev->ctx) return -ENOMEM; /* return the number of supported vectors if we can't get all: */ ret = pci_alloc_irq_vectors(pdev, 1, nvec, flag); if (ret < nvec) { if (ret > 0) pci_free_irq_vectors(pdev); kfree(vdev->ctx); return ret; } vdev->num_ctx = nvec; vdev->irq_type = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX; if (!msix) { /* * Compute the virtual hardware field for max msi vectors - * it is the log base 2 of the number of vectors. */ vdev->msi_qmax = fls(nvec * 2 - 1) - 1; } return 0; }
166,901
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int snd_hrtimer_stop(struct snd_timer *t) { struct snd_hrtimer *stime = t->private_data; atomic_set(&stime->running, 0); return 0; } Commit Message: ALSA: hrtimer: Fix stall by hrtimer_cancel() hrtimer_cancel() waits for the completion from the callback, thus it must not be called inside the callback itself. This was already a problem in the past with ALSA hrtimer driver, and the early commit [fcfdebe70759: ALSA: hrtimer - Fix lock-up] tried to address it. However, the previous fix is still insufficient: it may still cause a lockup when the ALSA timer instance reprograms itself in its callback. Then it invokes the start function even in snd_timer_interrupt() that is called in hrtimer callback itself, results in a CPU stall. This is no hypothetical problem but actually triggered by syzkaller fuzzer. This patch tries to fix the issue again. Now we call hrtimer_try_to_cancel() at both start and stop functions so that it won't fall into a deadlock, yet giving some chance to cancel the queue if the functions have been called outside the callback. The proper hrtimer_cancel() is called in anyway at closing, so this should be enough. Reported-and-tested-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-20
static int snd_hrtimer_stop(struct snd_timer *t) { struct snd_hrtimer *stime = t->private_data; atomic_set(&stime->running, 0); hrtimer_try_to_cancel(&stime->hrt); return 0; }
167,399
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 find_source_vc(char **ret_path, unsigned *ret_idx) { _cleanup_free_ char *path = NULL; int r, err = 0; unsigned i; path = new(char, sizeof("/dev/tty63")); if (!path) return log_oom(); for (i = 1; i <= 63; i++) { _cleanup_close_ int fd = -1; r = verify_vc_allocation(i); if (r < 0) { if (!err) err = -r; continue; } sprintf(path, "/dev/tty%u", i); fd = open_terminal(path, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd < 0) { if (!err) err = -fd; continue; } r = verify_vc_kbmode(fd); if (r < 0) { if (!err) err = -r; continue; } /* all checks passed, return this one as a source console */ *ret_idx = i; *ret_path = TAKE_PTR(path); return TAKE_FD(fd); } return log_error_errno(err, "No usable source console found: %m"); } Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check VT kbd reset check CWE ID: CWE-255
static int find_source_vc(char **ret_path, unsigned *ret_idx) { _cleanup_free_ char *path = NULL; int r, err = 0; unsigned i; path = new(char, sizeof("/dev/tty63")); if (!path) return log_oom(); for (i = 1; i <= 63; i++) { _cleanup_close_ int fd = -1; r = verify_vc_allocation(i); if (r < 0) { if (!err) err = -r; continue; } sprintf(path, "/dev/tty%u", i); fd = open_terminal(path, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd < 0) { if (!err) err = -fd; continue; } r = vt_verify_kbmode(fd); if (r < 0) { if (!err) err = -r; continue; } /* all checks passed, return this one as a source console */ *ret_idx = i; *ret_path = TAKE_PTR(path); return TAKE_FD(fd); } return log_error_errno(err, "No usable source console found: %m"); }
169,777
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 proc_connectinfo(struct usb_dev_state *ps, void __user *arg) { struct usbdevfs_connectinfo ci = { .devnum = ps->dev->devnum, .slow = ps->dev->speed == USB_SPEED_LOW }; if (copy_to_user(arg, &ci, sizeof(ci))) return -EFAULT; return 0; } Commit Message: USB: usbfs: fix potential infoleak in devio The stack object “ci” has a total size of 8 bytes. Its last 3 bytes are padding bytes which are not initialized and leaked to userland via “copy_to_user”. Signed-off-by: Kangjie Lu <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-200
static int proc_connectinfo(struct usb_dev_state *ps, void __user *arg) { struct usbdevfs_connectinfo ci; memset(&ci, 0, sizeof(ci)); ci.devnum = ps->dev->devnum; ci.slow = ps->dev->speed == USB_SPEED_LOW; if (copy_to_user(arg, &ci, sizeof(ci))) return -EFAULT; return 0; }
167,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: do_command (unsigned char c) { static int dtr_up = 0; int newbaud, newflow, newparity, newbits; const char *xfr_cmd; char *fname; int r; switch (c) { case KEY_EXIT: return 1; case KEY_QUIT: term_set_hupcl(tty_fd, 0); term_flush(tty_fd); term_apply(tty_fd); term_erase(tty_fd); return 1; case KEY_STATUS: show_status(dtr_up); break; case KEY_PULSE: fd_printf(STO, "\r\n*** pulse DTR ***\r\n"); if ( term_pulse_dtr(tty_fd) < 0 ) fd_printf(STO, "*** FAILED\r\n"); break; case KEY_TOGGLE: if ( dtr_up ) r = term_lower_dtr(tty_fd); else r = term_raise_dtr(tty_fd); if ( r >= 0 ) dtr_up = ! dtr_up; fd_printf(STO, "\r\n*** DTR: %s ***\r\n", dtr_up ? "up" : "down"); break; case KEY_BAUD_UP: case KEY_BAUD_DN: if (c == KEY_BAUD_UP) opts.baud = baud_up(opts.baud); else opts.baud = baud_down(opts.baud); term_set_baudrate(tty_fd, opts.baud); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newbaud = term_get_baudrate(tty_fd, NULL); if ( opts.baud != newbaud ) { fd_printf(STO, "\r\n*** baud: %d (%d) ***\r\n", opts.baud, newbaud); } else { fd_printf(STO, "\r\n*** baud: %d ***\r\n", opts.baud); } set_tty_write_sz(newbaud); break; case KEY_FLOW: opts.flow = flow_next(opts.flow); term_set_flowcntrl(tty_fd, opts.flow); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newflow = term_get_flowcntrl(tty_fd); if ( opts.flow != newflow ) { fd_printf(STO, "\r\n*** flow: %s (%s) ***\r\n", flow_str[opts.flow], flow_str[newflow]); } else { fd_printf(STO, "\r\n*** flow: %s ***\r\n", flow_str[opts.flow]); } break; case KEY_PARITY: opts.parity = parity_next(opts.parity); term_set_parity(tty_fd, opts.parity); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newparity = term_get_parity(tty_fd); if (opts.parity != newparity ) { fd_printf(STO, "\r\n*** parity: %s (%s) ***\r\n", parity_str[opts.parity], parity_str[newparity]); } else { fd_printf(STO, "\r\n*** parity: %s ***\r\n", parity_str[opts.parity]); } break; case KEY_BITS: opts.databits = bits_next(opts.databits); term_set_databits(tty_fd, opts.databits); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newbits = term_get_databits(tty_fd); if (opts.databits != newbits ) { fd_printf(STO, "\r\n*** databits: %d (%d) ***\r\n", opts.databits, newbits); } else { fd_printf(STO, "\r\n*** databits: %d ***\r\n", opts.databits); } break; case KEY_LECHO: opts.lecho = ! opts.lecho; fd_printf(STO, "\r\n*** local echo: %s ***\r\n", opts.lecho ? "yes" : "no"); break; case KEY_SEND: case KEY_RECEIVE: xfr_cmd = (c == KEY_SEND) ? opts.send_cmd : opts.receive_cmd; if ( xfr_cmd[0] == '\0' ) { fd_printf(STO, "\r\n*** command disabled ***\r\n"); break; } fname = read_filename(); if (fname == NULL) { fd_printf(STO, "*** cannot read filename ***\r\n"); break; } run_cmd(tty_fd, xfr_cmd, fname, NULL); free(fname); break; case KEY_BREAK: term_break(tty_fd); fd_printf(STO, "\r\n*** break sent ***\r\n"); break; default: break; } return 0; } Commit Message: Do not use "/bin/sh" to run external commands. Picocom no longer uses /bin/sh to run external commands for file-transfer operations. Parsing the command line and spliting it into arguments is now performed internally by picocom, using quoting rules very similar to those of the Unix shell. Hopefully, this makes it impossible to inject shell-commands when supplying filenames or extra arguments to the send- and receive-file commands. CWE ID: CWE-77
do_command (unsigned char c) { static int dtr_up = 0; int newbaud, newflow, newparity, newbits; const char *xfr_cmd; char *fname; int r; switch (c) { case KEY_EXIT: return 1; case KEY_QUIT: term_set_hupcl(tty_fd, 0); term_flush(tty_fd); term_apply(tty_fd); term_erase(tty_fd); return 1; case KEY_STATUS: show_status(dtr_up); break; case KEY_PULSE: fd_printf(STO, "\r\n*** pulse DTR ***\r\n"); if ( term_pulse_dtr(tty_fd) < 0 ) fd_printf(STO, "*** FAILED\r\n"); break; case KEY_TOGGLE: if ( dtr_up ) r = term_lower_dtr(tty_fd); else r = term_raise_dtr(tty_fd); if ( r >= 0 ) dtr_up = ! dtr_up; fd_printf(STO, "\r\n*** DTR: %s ***\r\n", dtr_up ? "up" : "down"); break; case KEY_BAUD_UP: case KEY_BAUD_DN: if (c == KEY_BAUD_UP) opts.baud = baud_up(opts.baud); else opts.baud = baud_down(opts.baud); term_set_baudrate(tty_fd, opts.baud); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newbaud = term_get_baudrate(tty_fd, NULL); if ( opts.baud != newbaud ) { fd_printf(STO, "\r\n*** baud: %d (%d) ***\r\n", opts.baud, newbaud); } else { fd_printf(STO, "\r\n*** baud: %d ***\r\n", opts.baud); } set_tty_write_sz(newbaud); break; case KEY_FLOW: opts.flow = flow_next(opts.flow); term_set_flowcntrl(tty_fd, opts.flow); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newflow = term_get_flowcntrl(tty_fd); if ( opts.flow != newflow ) { fd_printf(STO, "\r\n*** flow: %s (%s) ***\r\n", flow_str[opts.flow], flow_str[newflow]); } else { fd_printf(STO, "\r\n*** flow: %s ***\r\n", flow_str[opts.flow]); } break; case KEY_PARITY: opts.parity = parity_next(opts.parity); term_set_parity(tty_fd, opts.parity); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newparity = term_get_parity(tty_fd); if (opts.parity != newparity ) { fd_printf(STO, "\r\n*** parity: %s (%s) ***\r\n", parity_str[opts.parity], parity_str[newparity]); } else { fd_printf(STO, "\r\n*** parity: %s ***\r\n", parity_str[opts.parity]); } break; case KEY_BITS: opts.databits = bits_next(opts.databits); term_set_databits(tty_fd, opts.databits); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newbits = term_get_databits(tty_fd); if (opts.databits != newbits ) { fd_printf(STO, "\r\n*** databits: %d (%d) ***\r\n", opts.databits, newbits); } else { fd_printf(STO, "\r\n*** databits: %d ***\r\n", opts.databits); } break; case KEY_LECHO: opts.lecho = ! opts.lecho; fd_printf(STO, "\r\n*** local echo: %s ***\r\n", opts.lecho ? "yes" : "no"); break; case KEY_SEND: case KEY_RECEIVE: xfr_cmd = (c == KEY_SEND) ? opts.send_cmd : opts.receive_cmd; if ( xfr_cmd[0] == '\0' ) { fd_printf(STO, "\r\n*** command disabled ***\r\n"); break; } fname = read_filename(); if (fname == NULL) { fd_printf(STO, "*** cannot read filename ***\r\n"); break; } run_cmd(tty_fd, xfr_cmd, fname); free(fname); break; case KEY_BREAK: term_break(tty_fd); fd_printf(STO, "\r\n*** break sent ***\r\n"); break; default: break; } return 0; }
168,849
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: char **XGetFontPath( register Display *dpy, int *npaths) /* RETURN */ { xGetFontPathReply rep; unsigned long nbytes = 0; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; LockDisplay(dpy); GetEmptyReq (GetFontPath, req); (void) _XReply (dpy, (xReply *) &rep, 0, xFalse); if (rep.nPaths) { flist = Xmalloc(rep.nPaths * sizeof (char *)); if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long) rep.length << 2; ch = Xmalloc (nbytes + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, nbytes); /* * unpack into null terminated strings. */ chend = ch + nbytes; length = *ch; for (i = 0; i < rep.nPaths; i++) { if (ch + length < chend) { flist[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ length = *ch; *ch = '\0'; /* and replace with null-termination */ count++; } else flist[i] = NULL; } } *npaths = count; UnlockDisplay(dpy); SyncHandle(); return (flist); } Commit Message: CWE ID: CWE-787
char **XGetFontPath( register Display *dpy, int *npaths) /* RETURN */ { xGetFontPathReply rep; unsigned long nbytes = 0; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; LockDisplay(dpy); GetEmptyReq (GetFontPath, req); (void) _XReply (dpy, (xReply *) &rep, 0, xFalse); if (rep.nPaths) { flist = Xmalloc(rep.nPaths * sizeof (char *)); if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long) rep.length << 2; ch = Xmalloc (nbytes + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, nbytes); /* * unpack into null terminated strings. */ chend = ch + nbytes; length = *(unsigned char *)ch; for (i = 0; i < rep.nPaths; i++) { if (ch + length < chend) { flist[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ length = *(unsigned char *)ch; *ch = '\0'; /* and replace with null-termination */ count++; } else flist[i] = NULL; } } *npaths = count; UnlockDisplay(dpy); SyncHandle(); return (flist); }
164,745
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ChromeRenderProcessObserver::OnControlMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(ChromeRenderProcessObserver, message) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetIsIncognitoProcess, OnSetIsIncognitoProcess) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetCacheCapacities, OnSetCacheCapacities) IPC_MESSAGE_HANDLER(ChromeViewMsg_ClearCache, OnClearCache) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetFieldTrialGroup, OnSetFieldTrialGroup) #if defined(USE_TCMALLOC) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetTcmallocHeapProfiling, OnSetTcmallocHeapProfiling) IPC_MESSAGE_HANDLER(ChromeViewMsg_WriteTcmallocHeapProfile, OnWriteTcmallocHeapProfile) #endif IPC_MESSAGE_HANDLER(ChromeViewMsg_GetV8HeapStats, OnGetV8HeapStats) IPC_MESSAGE_HANDLER(ChromeViewMsg_GetCacheResourceStats, OnGetCacheResourceStats) IPC_MESSAGE_HANDLER(ChromeViewMsg_PurgeMemory, OnPurgeMemory) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetContentSettingRules, OnSetContentSettingRules) IPC_MESSAGE_HANDLER(ChromeViewMsg_ToggleWebKitSharedTimer, OnToggleWebKitSharedTimer) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } Commit Message: Disable tcmalloc profile files. BUG=154983 [email protected] NOTRY=true Review URL: https://chromiumcodereview.appspot.com/11087041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ChromeRenderProcessObserver::OnControlMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(ChromeRenderProcessObserver, message) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetIsIncognitoProcess, OnSetIsIncognitoProcess) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetCacheCapacities, OnSetCacheCapacities) IPC_MESSAGE_HANDLER(ChromeViewMsg_ClearCache, OnClearCache) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetFieldTrialGroup, OnSetFieldTrialGroup) IPC_MESSAGE_HANDLER(ChromeViewMsg_GetV8HeapStats, OnGetV8HeapStats) IPC_MESSAGE_HANDLER(ChromeViewMsg_GetCacheResourceStats, OnGetCacheResourceStats) IPC_MESSAGE_HANDLER(ChromeViewMsg_PurgeMemory, OnPurgeMemory) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetContentSettingRules, OnSetContentSettingRules) IPC_MESSAGE_HANDLER(ChromeViewMsg_ToggleWebKitSharedTimer, OnToggleWebKitSharedTimer) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; }
170,665
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 xt_table_info *xt_alloc_table_info(unsigned int size) { struct xt_table_info *info = NULL; size_t sz = sizeof(*info) + size; /* Pedantry: prevent them from hitting BUG() in vmalloc.c --RR */ if ((SMP_ALIGN(size) >> PAGE_SHIFT) + 2 > totalram_pages) return NULL; if (sz <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) info = kmalloc(sz, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY); if (!info) { info = vmalloc(sz); if (!info) return NULL; } memset(info, 0, sizeof(*info)); info->size = size; return info; } Commit Message: netfilter: x_tables: check for size overflow Ben Hawkes says: integer overflow in xt_alloc_table_info, which on 32-bit systems can lead to small structure allocation and a copy_from_user based heap corruption. Reported-by: Ben Hawkes <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-189
struct xt_table_info *xt_alloc_table_info(unsigned int size) { struct xt_table_info *info = NULL; size_t sz = sizeof(*info) + size; if (sz < sizeof(*info)) return NULL; /* Pedantry: prevent them from hitting BUG() in vmalloc.c --RR */ if ((SMP_ALIGN(size) >> PAGE_SHIFT) + 2 > totalram_pages) return NULL; if (sz <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) info = kmalloc(sz, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY); if (!info) { info = vmalloc(sz); if (!info) return NULL; } memset(info, 0, sizeof(*info)); info->size = size; return info; }
167,362
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ExtensionTtsController::SetPlatformImpl( ExtensionTtsPlatformImpl* platform_impl) { platform_impl_ = platform_impl; } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ExtensionTtsController::SetPlatformImpl(
170,386
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __exit void sctp_exit(void) { /* BUG. This should probably do something useful like clean * up all the remaining associations and all that memory. */ /* Unregister with inet6/inet layers. */ sctp_v6_del_protocol(); sctp_v4_del_protocol(); unregister_pernet_subsys(&sctp_net_ops); /* Free protosw registrations */ sctp_v6_protosw_exit(); sctp_v4_protosw_exit(); /* Unregister with socket layer. */ sctp_v6_pf_exit(); sctp_v4_pf_exit(); sctp_sysctl_unregister(); free_pages((unsigned long)sctp_assoc_hashtable, get_order(sctp_assoc_hashsize * sizeof(struct sctp_hashbucket))); kfree(sctp_ep_hashtable); free_pages((unsigned long)sctp_port_hashtable, get_order(sctp_port_hashsize * sizeof(struct sctp_bind_hashbucket))); percpu_counter_destroy(&sctp_sockets_allocated); rcu_barrier(); /* Wait for completion of call_rcu()'s */ kmem_cache_destroy(sctp_chunk_cachep); kmem_cache_destroy(sctp_bucket_cachep); } Commit Message: sctp: fix race on protocol/netns initialization Consider sctp module is unloaded and is being requested because an user is creating a sctp socket. During initialization, sctp will add the new protocol type and then initialize pernet subsys: status = sctp_v4_protosw_init(); if (status) goto err_protosw_init; status = sctp_v6_protosw_init(); if (status) goto err_v6_protosw_init; status = register_pernet_subsys(&sctp_net_ops); The problem is that after those calls to sctp_v{4,6}_protosw_init(), it is possible for userspace to create SCTP sockets like if the module is already fully loaded. If that happens, one of the possible effects is that we will have readers for net->sctp.local_addr_list list earlier than expected and sctp_net_init() does not take precautions while dealing with that list, leading to a potential panic but not limited to that, as sctp_sock_init() will copy a bunch of blank/partially initialized values from net->sctp. The race happens like this: CPU 0 | CPU 1 socket() | __sock_create | socket() inet_create | __sock_create list_for_each_entry_rcu( | answer, &inetsw[sock->type], | list) { | inet_create /* no hits */ | if (unlikely(err)) { | ... | request_module() | /* socket creation is blocked | * the module is fully loaded | */ | sctp_init | sctp_v4_protosw_init | inet_register_protosw | list_add_rcu(&p->list, | last_perm); | | list_for_each_entry_rcu( | answer, &inetsw[sock->type], sctp_v6_protosw_init | list) { | /* hit, so assumes protocol | * is already loaded | */ | /* socket creation continues | * before netns is initialized | */ register_pernet_subsys | Simply inverting the initialization order between register_pernet_subsys() and sctp_v4_protosw_init() is not possible because register_pernet_subsys() will create a control sctp socket, so the protocol must be already visible by then. Deferring the socket creation to a work-queue is not good specially because we loose the ability to handle its errors. So, as suggested by Vlad, the fix is to split netns initialization in two moments: defaults and control socket, so that the defaults are already loaded by when we register the protocol, while control socket initialization is kept at the same moment it is today. Fixes: 4db67e808640 ("sctp: Make the address lists per network namespace") Signed-off-by: Vlad Yasevich <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119
static __exit void sctp_exit(void) { /* BUG. This should probably do something useful like clean * up all the remaining associations and all that memory. */ /* Unregister with inet6/inet layers. */ sctp_v6_del_protocol(); sctp_v4_del_protocol(); unregister_pernet_subsys(&sctp_ctrlsock_ops); /* Free protosw registrations */ sctp_v6_protosw_exit(); sctp_v4_protosw_exit(); unregister_pernet_subsys(&sctp_defaults_ops); /* Unregister with socket layer. */ sctp_v6_pf_exit(); sctp_v4_pf_exit(); sctp_sysctl_unregister(); free_pages((unsigned long)sctp_assoc_hashtable, get_order(sctp_assoc_hashsize * sizeof(struct sctp_hashbucket))); kfree(sctp_ep_hashtable); free_pages((unsigned long)sctp_port_hashtable, get_order(sctp_port_hashsize * sizeof(struct sctp_bind_hashbucket))); percpu_counter_destroy(&sctp_sockets_allocated); rcu_barrier(); /* Wait for completion of call_rcu()'s */ kmem_cache_destroy(sctp_chunk_cachep); kmem_cache_destroy(sctp_bucket_cachep); }
166,605
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RenderWidgetHostViewGtk::AcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params, int gpu_host_id) { RenderWidgetHostImpl::AcknowledgeBufferPresent( params.route_id, gpu_host_id, true, 0); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewGtk::AcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params, int gpu_host_id) { RenderWidgetHostImpl::AcknowledgeBufferPresent( params.route_id, gpu_host_id, params.surface_handle, 0); }
171,390
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 _moddeinit(module_unload_intent_t intent) { service_named_unbind_command("chanserv", &cs_flags); } Commit Message: chanserv/flags: make Anope FLAGS compatibility an option Previously, ChanServ FLAGS behavior could be modified by registering or dropping the keyword nicks "LIST", "CLEAR", and "MODIFY". Now, a configuration option is available that when turned on (default), disables registration of these keyword nicks and enables this compatibility feature. When turned off, registration of these keyword nicks is possible, and compatibility to Anope's FLAGS command is disabled. Fixes atheme/atheme#397 CWE ID: CWE-284
void _moddeinit(module_unload_intent_t intent) { service_named_unbind_command("chanserv", &cs_flags); hook_del_nick_can_register(check_registration_keywords); hook_del_user_can_register(check_registration_keywords); del_conf_item("ANOPE_FLAGS_COMPAT", &chansvs.me->conf_table); }
167,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: void TabletModeWindowManager::Shutdown() { base::flat_map<aura::Window*, WindowStateType> windows_in_splitview = GetCarryOverWindowsInSplitView(); SplitViewController* split_view_controller = Shell::Get()->split_view_controller(); if (split_view_controller->InSplitViewMode()) { OverviewController* overview_controller = Shell::Get()->overview_controller(); if (!overview_controller->InOverviewSession() || overview_controller->overview_session()->IsEmpty()) { Shell::Get()->split_view_controller()->EndSplitView( SplitViewController::EndReason::kExitTabletMode); overview_controller->EndOverview(); } } for (aura::Window* window : added_windows_) window->RemoveObserver(this); added_windows_.clear(); Shell::Get()->RemoveShellObserver(this); Shell::Get()->session_controller()->RemoveObserver(this); Shell::Get()->overview_controller()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); RemoveWindowCreationObservers(); ScopedObserveWindowAnimation scoped_observe(GetTopWindow(), this, /*exiting_tablet_mode=*/true); ArrangeWindowsForClamshellMode(windows_in_splitview); } Commit Message: Fix the crash after clamshell -> tablet transition in overview mode. This CL just reverted some changes that were made in https://chromium-review.googlesource.com/c/chromium/src/+/1658955. In that CL, we changed the clamshell <-> tablet transition when clamshell split view mode is enabled, however, we should keep the old behavior unchanged if the feature is not enabled, i.e., overview should be ended if it's active before the transition. Otherwise, it will cause a nullptr dereference crash since |split_view_drag_indicators_| is not created in clamshell overview and will be used in tablet overview. Bug: 982507 Change-Id: I238fe9472648a446cff4ab992150658c228714dd Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1705474 Commit-Queue: Xiaoqian Dai <[email protected]> Reviewed-by: Mitsuru Oshima (Slow - on/off site) <[email protected]> Cr-Commit-Position: refs/heads/master@{#679306} CWE ID: CWE-362
void TabletModeWindowManager::Shutdown() { base::flat_map<aura::Window*, WindowStateType> carryover_windows_in_splitview; const bool was_in_overview = Shell::Get()->overview_controller()->InOverviewSession(); // If clamshell split view mode is not enabled, still keep the old behavior: // End overview if overview is active and restore all windows' window states // to their previous window states. if (!IsClamshellSplitViewModeEnabled()) { Shell::Get()->overview_controller()->EndOverview(); } else { // If clamshell split view mode is enabled, there are 4 cases when exiting // tablet mode: // 1) overview is active but split view is inactive: keep overview active in // clamshell mode. // 2) overview and splitview are both active: keep overview and splitview // both // active in clamshell mode, unless if it's single split state, splitview // and overview will both be ended. // 3) overview is inactive but split view is active (two snapped windows): // split view is no longer active. But the two snapped windows will still // keep snapped in clamshell mode. // 4) overview and splitview are both inactive: keep the current behavior, // i.e., restore all windows to its window state before entering tablet // mode. // TODO(xdai): Instead of caching snapped windows and their state here, we // should try to see if it can be done in the WindowState::State impl. carryover_windows_in_splitview = GetCarryOverWindowsInSplitView(); // For case 2 and 3: End splitview mode for two snapped windows case or // single split case to match the clamshell split view behavior. (there is // no both snapped state or single split state in clamshell split view). The // windows will still be kept snapped though. SplitViewController* split_view_controller = Shell::Get()->split_view_controller(); if (split_view_controller->InSplitViewMode()) { OverviewController* overview_controller = Shell::Get()->overview_controller(); if (!overview_controller->InOverviewSession() || overview_controller->overview_session()->IsEmpty()) { Shell::Get()->split_view_controller()->EndSplitView( SplitViewController::EndReason::kExitTabletMode); overview_controller->EndOverview(); } } } for (aura::Window* window : added_windows_) window->RemoveObserver(this); added_windows_.clear(); Shell::Get()->RemoveShellObserver(this); Shell::Get()->session_controller()->RemoveObserver(this); Shell::Get()->overview_controller()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); RemoveWindowCreationObservers(); ScopedObserveWindowAnimation scoped_observe(GetTopWindow(), this, /*exiting_tablet_mode=*/true); ArrangeWindowsForClamshellMode(carryover_windows_in_splitview, was_in_overview); }
172,402
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long follow_hugetlb_page(struct mm_struct *mm, struct vm_area_struct *vma, struct page **pages, struct vm_area_struct **vmas, unsigned long *position, unsigned long *nr_pages, long i, unsigned int flags, int *nonblocking) { unsigned long pfn_offset; unsigned long vaddr = *position; unsigned long remainder = *nr_pages; struct hstate *h = hstate_vma(vma); int err = -EFAULT; while (vaddr < vma->vm_end && remainder) { pte_t *pte; spinlock_t *ptl = NULL; int absent; struct page *page; /* * If we have a pending SIGKILL, don't keep faulting pages and * potentially allocating memory. */ if (fatal_signal_pending(current)) { remainder = 0; break; } /* * Some archs (sparc64, sh*) have multiple pte_ts to * each hugepage. We have to make sure we get the * first, for the page indexing below to work. * * Note that page table lock is not held when pte is null. */ pte = huge_pte_offset(mm, vaddr & huge_page_mask(h), huge_page_size(h)); if (pte) ptl = huge_pte_lock(h, mm, pte); absent = !pte || huge_pte_none(huge_ptep_get(pte)); /* * When coredumping, it suits get_dump_page if we just return * an error where there's an empty slot with no huge pagecache * to back it. This way, we avoid allocating a hugepage, and * the sparse dumpfile avoids allocating disk blocks, but its * huge holes still show up with zeroes where they need to be. */ if (absent && (flags & FOLL_DUMP) && !hugetlbfs_pagecache_present(h, vma, vaddr)) { if (pte) spin_unlock(ptl); remainder = 0; break; } /* * We need call hugetlb_fault for both hugepages under migration * (in which case hugetlb_fault waits for the migration,) and * hwpoisoned hugepages (in which case we need to prevent the * caller from accessing to them.) In order to do this, we use * here is_swap_pte instead of is_hugetlb_entry_migration and * is_hugetlb_entry_hwpoisoned. This is because it simply covers * both cases, and because we can't follow correct pages * directly from any kind of swap entries. */ if (absent || is_swap_pte(huge_ptep_get(pte)) || ((flags & FOLL_WRITE) && !huge_pte_write(huge_ptep_get(pte)))) { vm_fault_t ret; unsigned int fault_flags = 0; if (pte) spin_unlock(ptl); if (flags & FOLL_WRITE) fault_flags |= FAULT_FLAG_WRITE; if (nonblocking) fault_flags |= FAULT_FLAG_ALLOW_RETRY; if (flags & FOLL_NOWAIT) fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT; if (flags & FOLL_TRIED) { VM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_ALLOW_RETRY); fault_flags |= FAULT_FLAG_TRIED; } ret = hugetlb_fault(mm, vma, vaddr, fault_flags); if (ret & VM_FAULT_ERROR) { err = vm_fault_to_errno(ret, flags); remainder = 0; break; } if (ret & VM_FAULT_RETRY) { if (nonblocking && !(fault_flags & FAULT_FLAG_RETRY_NOWAIT)) *nonblocking = 0; *nr_pages = 0; /* * VM_FAULT_RETRY must not return an * error, it will return zero * instead. * * No need to update "position" as the * caller will not check it after * *nr_pages is set to 0. */ return i; } continue; } pfn_offset = (vaddr & ~huge_page_mask(h)) >> PAGE_SHIFT; page = pte_page(huge_ptep_get(pte)); same_page: if (pages) { pages[i] = mem_map_offset(page, pfn_offset); get_page(pages[i]); } if (vmas) vmas[i] = vma; vaddr += PAGE_SIZE; ++pfn_offset; --remainder; ++i; if (vaddr < vma->vm_end && remainder && pfn_offset < pages_per_huge_page(h)) { /* * We use pfn_offset to avoid touching the pageframes * of this compound page. */ goto same_page; } spin_unlock(ptl); } *nr_pages = remainder; /* * setting position is actually required only if remainder is * not zero but it's faster not to add a "if (remainder)" * branch. */ *position = vaddr; return i ? i : err; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416
long follow_hugetlb_page(struct mm_struct *mm, struct vm_area_struct *vma, struct page **pages, struct vm_area_struct **vmas, unsigned long *position, unsigned long *nr_pages, long i, unsigned int flags, int *nonblocking) { unsigned long pfn_offset; unsigned long vaddr = *position; unsigned long remainder = *nr_pages; struct hstate *h = hstate_vma(vma); int err = -EFAULT; while (vaddr < vma->vm_end && remainder) { pte_t *pte; spinlock_t *ptl = NULL; int absent; struct page *page; /* * If we have a pending SIGKILL, don't keep faulting pages and * potentially allocating memory. */ if (fatal_signal_pending(current)) { remainder = 0; break; } /* * Some archs (sparc64, sh*) have multiple pte_ts to * each hugepage. We have to make sure we get the * first, for the page indexing below to work. * * Note that page table lock is not held when pte is null. */ pte = huge_pte_offset(mm, vaddr & huge_page_mask(h), huge_page_size(h)); if (pte) ptl = huge_pte_lock(h, mm, pte); absent = !pte || huge_pte_none(huge_ptep_get(pte)); /* * When coredumping, it suits get_dump_page if we just return * an error where there's an empty slot with no huge pagecache * to back it. This way, we avoid allocating a hugepage, and * the sparse dumpfile avoids allocating disk blocks, but its * huge holes still show up with zeroes where they need to be. */ if (absent && (flags & FOLL_DUMP) && !hugetlbfs_pagecache_present(h, vma, vaddr)) { if (pte) spin_unlock(ptl); remainder = 0; break; } /* * We need call hugetlb_fault for both hugepages under migration * (in which case hugetlb_fault waits for the migration,) and * hwpoisoned hugepages (in which case we need to prevent the * caller from accessing to them.) In order to do this, we use * here is_swap_pte instead of is_hugetlb_entry_migration and * is_hugetlb_entry_hwpoisoned. This is because it simply covers * both cases, and because we can't follow correct pages * directly from any kind of swap entries. */ if (absent || is_swap_pte(huge_ptep_get(pte)) || ((flags & FOLL_WRITE) && !huge_pte_write(huge_ptep_get(pte)))) { vm_fault_t ret; unsigned int fault_flags = 0; if (pte) spin_unlock(ptl); if (flags & FOLL_WRITE) fault_flags |= FAULT_FLAG_WRITE; if (nonblocking) fault_flags |= FAULT_FLAG_ALLOW_RETRY; if (flags & FOLL_NOWAIT) fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT; if (flags & FOLL_TRIED) { VM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_ALLOW_RETRY); fault_flags |= FAULT_FLAG_TRIED; } ret = hugetlb_fault(mm, vma, vaddr, fault_flags); if (ret & VM_FAULT_ERROR) { err = vm_fault_to_errno(ret, flags); remainder = 0; break; } if (ret & VM_FAULT_RETRY) { if (nonblocking && !(fault_flags & FAULT_FLAG_RETRY_NOWAIT)) *nonblocking = 0; *nr_pages = 0; /* * VM_FAULT_RETRY must not return an * error, it will return zero * instead. * * No need to update "position" as the * caller will not check it after * *nr_pages is set to 0. */ return i; } continue; } pfn_offset = (vaddr & ~huge_page_mask(h)) >> PAGE_SHIFT; page = pte_page(huge_ptep_get(pte)); /* * Instead of doing 'try_get_page()' below in the same_page * loop, just check the count once here. */ if (unlikely(page_count(page) <= 0)) { if (pages) { spin_unlock(ptl); remainder = 0; err = -ENOMEM; break; } } same_page: if (pages) { pages[i] = mem_map_offset(page, pfn_offset); get_page(pages[i]); } if (vmas) vmas[i] = vma; vaddr += PAGE_SIZE; ++pfn_offset; --remainder; ++i; if (vaddr < vma->vm_end && remainder && pfn_offset < pages_per_huge_page(h)) { /* * We use pfn_offset to avoid touching the pageframes * of this compound page. */ goto same_page; } spin_unlock(ptl); } *nr_pages = remainder; /* * setting position is actually required only if remainder is * not zero but it's faster not to add a "if (remainder)" * branch. */ *position = vaddr; return i ? i : err; }
170,229
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_video::allocate_output_buffer( OMX_IN OMX_HANDLETYPE hComp, OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr, OMX_IN OMX_U32 port, OMX_IN OMX_PTR appData, OMX_IN OMX_U32 bytes) { (void)hComp, (void)port; OMX_ERRORTYPE eRet = OMX_ErrorNone; OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header unsigned i= 0; // Temporary counter #ifdef _MSM8974_ int align_size; #endif DEBUG_PRINT_HIGH("allocate_output_buffer()for %u bytes", (unsigned int)bytes); if (!m_out_mem_ptr) { int nBufHdrSize = 0; DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__, (unsigned int)m_sOutPortDef.nBufferSize, (unsigned int)m_sOutPortDef.nBufferCountActual); nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE); /* * Memory for output side involves the following: * 1. Array of Buffer Headers * 2. Bitmask array to hold the buffer allocation details * In order to minimize the memory management entire allocation * is done in one step. */ m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1); #ifdef USE_ION m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual); if (m_pOutput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion"); return OMX_ErrorInsufficientResources; } #endif m_pOutput_pmem = (struct pmem *) calloc(sizeof(struct pmem), m_sOutPortDef.nBufferCountActual); if (m_pOutput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem"); return OMX_ErrorInsufficientResources; } if (m_out_mem_ptr && m_pOutput_pmem) { bufHdr = m_out_mem_ptr; for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) { bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE); bufHdr->nVersion.nVersion = OMX_SPEC_VERSION; bufHdr->nAllocLen = bytes; bufHdr->nFilledLen = 0; bufHdr->pAppPrivate = appData; bufHdr->nOutputPortIndex = PORT_INDEX_OUT; bufHdr->pOutputPortPrivate = (OMX_PTR)&m_pOutput_pmem[i]; bufHdr->pBuffer = NULL; bufHdr++; m_pOutput_pmem[i].fd = -1; #ifdef USE_ION m_pOutput_ion[i].ion_device_fd =-1; m_pOutput_ion[i].fd_ion_data.fd=-1; m_pOutput_ion[i].ion_alloc_data.handle = 0; #endif } } else { DEBUG_PRINT_ERROR("ERROR: calloc() failed for m_out_mem_ptr/m_pOutput_pmem"); eRet = OMX_ErrorInsufficientResources; } } DEBUG_PRINT_HIGH("actual cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountActual); for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_out_bm_count,i)) { DEBUG_PRINT_LOW("Found a Free Output Buffer %d",i); break; } } if (eRet == OMX_ErrorNone) { if (i < m_sOutPortDef.nBufferCountActual) { #ifdef USE_ION #ifdef _MSM8974_ align_size = ((m_sOutPortDef.nBufferSize + 4095)/4096) * 4096; m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data, ION_FLAG_CACHED); #else m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sOutPortDef.nBufferSize, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pOutput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd; #else m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pOutput_pmem[i].fd == 0) { m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pOutput_pmem[i].fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() failed"); return OMX_ErrorInsufficientResources; } #endif m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize; m_pOutput_pmem[i].offset = 0; m_pOutput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; if(!secure_session) { #ifdef _MSM8974_ m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, align_size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #else m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #endif if (m_pOutput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: MMAP_FAILED in o/p alloc buffer"); close (m_pOutput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pOutput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } else { m_pOutput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*)); native_handle_t *handle = native_handle_create(1, 0); handle->data[0] = m_pOutput_pmem[i].fd; char *data = (char*) m_pOutput_pmem[i].buffer; OMX_U32 type = 1; memcpy(data, &type, sizeof(OMX_U32)); memcpy(data + sizeof(OMX_U32), &handle, sizeof(native_handle_t*)); } *bufferHdr = (m_out_mem_ptr + i ); (*bufferHdr)->pBuffer = (OMX_U8 *)m_pOutput_pmem[i].buffer; (*bufferHdr)->pAppPrivate = appData; BITMASK_SET(&m_out_bm_count,i); if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for o/p buf"); return OMX_ErrorInsufficientResources; } } else { DEBUG_PRINT_ERROR("ERROR: All o/p buffers are allocated, invalid allocate buf call" "for index [%d] actual: %u", i, (unsigned int)m_sOutPortDef.nBufferCountActual); } } return eRet; } Commit Message: DO NOT MERGE Fix wrong nAllocLen Set nAllocLen to the size of the opaque handle itself. Bug: 28816964 Bug: 28816827 Change-Id: Id410e324bee291d4a0018dddb97eda9bbcded099 CWE ID: CWE-119
OMX_ERRORTYPE omx_video::allocate_output_buffer( OMX_IN OMX_HANDLETYPE hComp, OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr, OMX_IN OMX_U32 port, OMX_IN OMX_PTR appData, OMX_IN OMX_U32 bytes) { (void)hComp, (void)port; OMX_ERRORTYPE eRet = OMX_ErrorNone; OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header unsigned i= 0; // Temporary counter #ifdef _MSM8974_ int align_size; #endif DEBUG_PRINT_HIGH("allocate_output_buffer()for %u bytes", (unsigned int)bytes); if (!m_out_mem_ptr) { int nBufHdrSize = 0; DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__, (unsigned int)m_sOutPortDef.nBufferSize, (unsigned int)m_sOutPortDef.nBufferCountActual); nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE); /* * Memory for output side involves the following: * 1. Array of Buffer Headers * 2. Bitmask array to hold the buffer allocation details * In order to minimize the memory management entire allocation * is done in one step. */ m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1); #ifdef USE_ION m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual); if (m_pOutput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion"); return OMX_ErrorInsufficientResources; } #endif m_pOutput_pmem = (struct pmem *) calloc(sizeof(struct pmem), m_sOutPortDef.nBufferCountActual); if (m_pOutput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem"); return OMX_ErrorInsufficientResources; } if (m_out_mem_ptr && m_pOutput_pmem) { bufHdr = m_out_mem_ptr; for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) { bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE); bufHdr->nVersion.nVersion = OMX_SPEC_VERSION; bufHdr->nAllocLen = bytes; bufHdr->nFilledLen = 0; bufHdr->pAppPrivate = appData; bufHdr->nOutputPortIndex = PORT_INDEX_OUT; bufHdr->pOutputPortPrivate = (OMX_PTR)&m_pOutput_pmem[i]; bufHdr->pBuffer = NULL; bufHdr++; m_pOutput_pmem[i].fd = -1; #ifdef USE_ION m_pOutput_ion[i].ion_device_fd =-1; m_pOutput_ion[i].fd_ion_data.fd=-1; m_pOutput_ion[i].ion_alloc_data.handle = 0; #endif } } else { DEBUG_PRINT_ERROR("ERROR: calloc() failed for m_out_mem_ptr/m_pOutput_pmem"); eRet = OMX_ErrorInsufficientResources; } } DEBUG_PRINT_HIGH("actual cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountActual); for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_out_bm_count,i)) { DEBUG_PRINT_LOW("Found a Free Output Buffer %d",i); break; } } if (eRet == OMX_ErrorNone) { if (i < m_sOutPortDef.nBufferCountActual) { #ifdef USE_ION #ifdef _MSM8974_ align_size = ((m_sOutPortDef.nBufferSize + 4095)/4096) * 4096; m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data, ION_FLAG_CACHED); #else m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sOutPortDef.nBufferSize, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pOutput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd; #else m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pOutput_pmem[i].fd == 0) { m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pOutput_pmem[i].fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() failed"); return OMX_ErrorInsufficientResources; } #endif m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize; m_pOutput_pmem[i].offset = 0; m_pOutput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; if(!secure_session) { #ifdef _MSM8974_ m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, align_size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #else m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #endif if (m_pOutput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: MMAP_FAILED in o/p alloc buffer"); close (m_pOutput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pOutput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } else { m_pOutput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*)); (*bufferHdr)->nAllocLen = sizeof(OMX_U32) + sizeof(native_handle_t*); native_handle_t *handle = native_handle_create(1, 0); handle->data[0] = m_pOutput_pmem[i].fd; char *data = (char*) m_pOutput_pmem[i].buffer; OMX_U32 type = 1; memcpy(data, &type, sizeof(OMX_U32)); memcpy(data + sizeof(OMX_U32), &handle, sizeof(native_handle_t*)); } *bufferHdr = (m_out_mem_ptr + i ); (*bufferHdr)->pBuffer = (OMX_U8 *)m_pOutput_pmem[i].buffer; (*bufferHdr)->pAppPrivate = appData; BITMASK_SET(&m_out_bm_count,i); if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for o/p buf"); return OMX_ErrorInsufficientResources; } } else { DEBUG_PRINT_ERROR("ERROR: All o/p buffers are allocated, invalid allocate buf call" "for index [%d] actual: %u", i, (unsigned int)m_sOutPortDef.nBufferCountActual); } } return eRet; }
173,520
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebMediaPlayerMS::HasSingleSecurityOrigin() const { DCHECK(thread_checker_.CalledOnValidThread()); return true; } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732
bool WebMediaPlayerMS::HasSingleSecurityOrigin() const {
172,622
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 IsValidURL(const GURL& url, PortPermission port_permission) { return url.is_valid() && url.SchemeIsHTTPOrHTTPS() && (url.port().empty() || (port_permission == ALLOW_NON_STANDARD_PORTS)); } Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service. The functionality worked, as part of converting DICE, however the test code didn't work since it depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to better match production, which removes the dependency on net/. Also: -make GetFilePathWithReplacements replace strings in the mock headers if they're present -add a global to google_util to ignore ports; that way other tests can be converted without having to modify each callsite to google_util Bug: 881976 Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058 Reviewed-on: https://chromium-review.googlesource.com/c/1328142 Commit-Queue: John Abd-El-Malek <[email protected]> Reviewed-by: Ramin Halavati <[email protected]> Reviewed-by: Maks Orlovich <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#607652} CWE ID:
bool IsValidURL(const GURL& url, PortPermission port_permission) { return url.is_valid() && url.SchemeIsHTTPOrHTTPS() && (url.port().empty() || g_ignore_port_numbers || (port_permission == ALLOW_NON_STANDARD_PORTS)); }
172,584
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sock *cookie_v6_check(struct sock *sk, struct sk_buff *skb) { struct tcp_options_received tcp_opt; struct inet_request_sock *ireq; struct tcp_request_sock *treq; struct ipv6_pinfo *np = inet6_sk(sk); struct tcp_sock *tp = tcp_sk(sk); const struct tcphdr *th = tcp_hdr(skb); __u32 cookie = ntohl(th->ack_seq) - 1; struct sock *ret = sk; struct request_sock *req; int mss; struct dst_entry *dst; __u8 rcv_wscale; if (!sysctl_tcp_syncookies || !th->ack || th->rst) goto out; if (tcp_synq_no_recent_overflow(sk)) goto out; mss = __cookie_v6_check(ipv6_hdr(skb), th, cookie); if (mss == 0) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESFAILED); goto out; } NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESRECV); /* check for timestamp cookie support */ memset(&tcp_opt, 0, sizeof(tcp_opt)); tcp_parse_options(skb, &tcp_opt, 0, NULL); if (!cookie_timestamp_decode(&tcp_opt)) goto out; ret = NULL; req = inet_reqsk_alloc(&tcp6_request_sock_ops, sk, false); if (!req) goto out; ireq = inet_rsk(req); treq = tcp_rsk(req); treq->tfo_listener = false; if (security_inet_conn_request(sk, skb, req)) goto out_free; req->mss = mss; ireq->ir_rmt_port = th->source; ireq->ir_num = ntohs(th->dest); ireq->ir_v6_rmt_addr = ipv6_hdr(skb)->saddr; ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr; if (ipv6_opt_accepted(sk, skb, &TCP_SKB_CB(skb)->header.h6) || np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo || np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) { atomic_inc(&skb->users); ireq->pktopts = skb; } ireq->ir_iif = sk->sk_bound_dev_if; /* So that link locals have meaning */ if (!sk->sk_bound_dev_if && ipv6_addr_type(&ireq->ir_v6_rmt_addr) & IPV6_ADDR_LINKLOCAL) ireq->ir_iif = tcp_v6_iif(skb); ireq->ir_mark = inet_request_mark(sk, skb); req->num_retrans = 0; ireq->snd_wscale = tcp_opt.snd_wscale; ireq->sack_ok = tcp_opt.sack_ok; ireq->wscale_ok = tcp_opt.wscale_ok; ireq->tstamp_ok = tcp_opt.saw_tstamp; req->ts_recent = tcp_opt.saw_tstamp ? tcp_opt.rcv_tsval : 0; treq->snt_synack.v64 = 0; treq->rcv_isn = ntohl(th->seq) - 1; treq->snt_isn = cookie; /* * We need to lookup the dst_entry to get the correct window size. * This is taken from tcp_v6_syn_recv_sock. Somebody please enlighten * me if there is a preferred way. */ { struct in6_addr *final_p, final; struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = IPPROTO_TCP; fl6.daddr = ireq->ir_v6_rmt_addr; final_p = fl6_update_dst(&fl6, np->opt, &final); fl6.saddr = ireq->ir_v6_loc_addr; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = ireq->ir_mark; fl6.fl6_dport = ireq->ir_rmt_port; fl6.fl6_sport = inet_sk(sk)->inet_sport; security_req_classify_flow(req, flowi6_to_flowi(&fl6)); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) goto out_free; } req->rsk_window_clamp = tp->window_clamp ? :dst_metric(dst, RTAX_WINDOW); tcp_select_initial_window(tcp_full_space(sk), req->mss, &req->rsk_rcv_wnd, &req->rsk_window_clamp, ireq->wscale_ok, &rcv_wscale, dst_metric(dst, RTAX_INITRWND)); ireq->rcv_wscale = rcv_wscale; ireq->ecn_ok = cookie_ecn_ok(&tcp_opt, sock_net(sk), dst); ret = tcp_get_cookie_sock(sk, skb, req, dst); out: return ret; out_free: reqsk_free(req); return NULL; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
struct sock *cookie_v6_check(struct sock *sk, struct sk_buff *skb) { struct tcp_options_received tcp_opt; struct inet_request_sock *ireq; struct tcp_request_sock *treq; struct ipv6_pinfo *np = inet6_sk(sk); struct tcp_sock *tp = tcp_sk(sk); const struct tcphdr *th = tcp_hdr(skb); __u32 cookie = ntohl(th->ack_seq) - 1; struct sock *ret = sk; struct request_sock *req; int mss; struct dst_entry *dst; __u8 rcv_wscale; if (!sysctl_tcp_syncookies || !th->ack || th->rst) goto out; if (tcp_synq_no_recent_overflow(sk)) goto out; mss = __cookie_v6_check(ipv6_hdr(skb), th, cookie); if (mss == 0) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESFAILED); goto out; } NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESRECV); /* check for timestamp cookie support */ memset(&tcp_opt, 0, sizeof(tcp_opt)); tcp_parse_options(skb, &tcp_opt, 0, NULL); if (!cookie_timestamp_decode(&tcp_opt)) goto out; ret = NULL; req = inet_reqsk_alloc(&tcp6_request_sock_ops, sk, false); if (!req) goto out; ireq = inet_rsk(req); treq = tcp_rsk(req); treq->tfo_listener = false; if (security_inet_conn_request(sk, skb, req)) goto out_free; req->mss = mss; ireq->ir_rmt_port = th->source; ireq->ir_num = ntohs(th->dest); ireq->ir_v6_rmt_addr = ipv6_hdr(skb)->saddr; ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr; if (ipv6_opt_accepted(sk, skb, &TCP_SKB_CB(skb)->header.h6) || np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo || np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) { atomic_inc(&skb->users); ireq->pktopts = skb; } ireq->ir_iif = sk->sk_bound_dev_if; /* So that link locals have meaning */ if (!sk->sk_bound_dev_if && ipv6_addr_type(&ireq->ir_v6_rmt_addr) & IPV6_ADDR_LINKLOCAL) ireq->ir_iif = tcp_v6_iif(skb); ireq->ir_mark = inet_request_mark(sk, skb); req->num_retrans = 0; ireq->snd_wscale = tcp_opt.snd_wscale; ireq->sack_ok = tcp_opt.sack_ok; ireq->wscale_ok = tcp_opt.wscale_ok; ireq->tstamp_ok = tcp_opt.saw_tstamp; req->ts_recent = tcp_opt.saw_tstamp ? tcp_opt.rcv_tsval : 0; treq->snt_synack.v64 = 0; treq->rcv_isn = ntohl(th->seq) - 1; treq->snt_isn = cookie; /* * We need to lookup the dst_entry to get the correct window size. * This is taken from tcp_v6_syn_recv_sock. Somebody please enlighten * me if there is a preferred way. */ { struct in6_addr *final_p, final; struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = IPPROTO_TCP; fl6.daddr = ireq->ir_v6_rmt_addr; final_p = fl6_update_dst(&fl6, rcu_dereference(np->opt), &final); fl6.saddr = ireq->ir_v6_loc_addr; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = ireq->ir_mark; fl6.fl6_dport = ireq->ir_rmt_port; fl6.fl6_sport = inet_sk(sk)->inet_sport; security_req_classify_flow(req, flowi6_to_flowi(&fl6)); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) goto out_free; } req->rsk_window_clamp = tp->window_clamp ? :dst_metric(dst, RTAX_WINDOW); tcp_select_initial_window(tcp_full_space(sk), req->mss, &req->rsk_rcv_wnd, &req->rsk_window_clamp, ireq->wscale_ok, &rcv_wscale, dst_metric(dst, RTAX_INITRWND)); ireq->rcv_wscale = rcv_wscale; ireq->ecn_ok = cookie_ecn_ok(&tcp_opt, sock_net(sk), dst); ret = tcp_get_cookie_sock(sk, skb, req, dst); out: return ret; out_free: reqsk_free(req); return NULL; }
167,339
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline long object_common1(UNSERIALIZE_PARAMETER, zend_class_entry *ce) { long elements; elements = parse_iv2((*p) + 2, p); (*p) += 2; if (ce->serialize == NULL) { object_init_ex(*rval, ce); } else { /* If this class implements Serializable, it should not land here but in object_custom(). The passed string obviously doesn't descend from the regular serializer. */ zend_error(E_WARNING, "Erroneous data format for unserializing '%s'", ce->name); return 0; } return elements; } Commit Message: Fix bug #73825 - Heap out of bounds read on unserialize in finish_nested_data() CWE ID: CWE-125
static inline long object_common1(UNSERIALIZE_PARAMETER, zend_class_entry *ce) { long elements; if( *p >= max - 2) { zend_error(E_WARNING, "Bad unserialize data"); return -1; } elements = parse_iv2((*p) + 2, p); (*p) += 2; if (ce->serialize == NULL) { object_init_ex(*rval, ce); } else { /* If this class implements Serializable, it should not land here but in object_custom(). The passed string obviously doesn't descend from the regular serializer. */ zend_error(E_WARNING, "Erroneous data format for unserializing '%s'", ce->name); return -1; } return elements; }
168,514
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BrowserContextImpl::~BrowserContextImpl() { CHECK(!otr_context_); } Commit Message: CWE ID: CWE-20
BrowserContextImpl::~BrowserContextImpl() {
165,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 PaymentRequest::AreRequestedMethodsSupportedCallback( bool methods_supported) { if (methods_supported) { if (SatisfiesSkipUIConstraints()) { skipped_payment_request_ui_ = true; Pay(); } } else { journey_logger_.SetNotShown( JourneyLogger::NOT_SHOWN_REASON_NO_SUPPORTED_PAYMENT_METHOD); client_->OnError(mojom::PaymentErrorReason::NOT_SUPPORTED); if (observer_for_testing_) observer_for_testing_->OnNotSupportedError(); OnConnectionTerminated(); } } Commit Message: [Payment Request][Desktop] Prevent use after free. Before this patch, a compromised renderer on desktop could make IPC methods into Payment Request in an unexpected ordering and cause use after free in the browser. This patch will disconnect the IPC pipes if: - Init() is called more than once. - Any other method is called before Init(). - Show() is called more than once. - Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or Complete() are called before Show(). This patch re-orders the IPC methods in payment_request.cc to match the order in payment_request.h, which eases verifying correctness of their error handling. This patch prints more errors to the developer console, if available, to improve debuggability by web developers, who rarely check where LOG prints. After this patch, unexpected ordering of calls into the Payment Request IPC from the renderer to the browser on desktop will print an error in the developer console and disconnect the IPC pipes. The binary might increase slightly in size because more logs are included in the release version instead of being stripped at compile time. Bug: 912947 Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a Reviewed-on: https://chromium-review.googlesource.com/c/1370198 Reviewed-by: anthonyvd <[email protected]> Commit-Queue: Rouslan Solomakhin <[email protected]> Cr-Commit-Position: refs/heads/master@{#616822} CWE ID: CWE-189
void PaymentRequest::AreRequestedMethodsSupportedCallback( void PaymentRequest::UpdateWith(mojom::PaymentDetailsPtr details) { if (!IsInitialized()) { log_.Error("Attempted updateWith without initialization"); OnConnectionTerminated(); return; }
173,079
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: make_errors(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type, int bdlo, int PNG_CONST bdhi) { for (; bdlo <= bdhi; ++bdlo) { int interlace_type; for (interlace_type = PNG_INTERLACE_NONE; interlace_type < INTERLACE_LAST; ++interlace_type) { unsigned int test; char name[FILE_NAME_SIZE]; standard_name(name, sizeof name, 0, colour_type, 1<<bdlo, 0, interlace_type, 0, 0, 0); for (test=0; test<(sizeof error_test)/(sizeof error_test[0]); ++test) { make_error(&pm->this, colour_type, DEPTH(bdlo), interlace_type, test, name); if (fail(pm)) return 0; } } } return 1; /* keep going */ } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
make_errors(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type, make_errors(png_modifier* const pm, png_byte const colour_type, int bdlo, int const bdhi) { for (; bdlo <= bdhi; ++bdlo) { int interlace_type; for (interlace_type = PNG_INTERLACE_NONE; interlace_type < INTERLACE_LAST; ++interlace_type) { unsigned int test; char name[FILE_NAME_SIZE]; standard_name(name, sizeof name, 0, colour_type, 1<<bdlo, 0, interlace_type, 0, 0, do_own_interlace); for (test=0; test<ARRAY_SIZE(error_test); ++test) { make_error(&pm->this, colour_type, DEPTH(bdlo), interlace_type, test, name); if (fail(pm)) return 0; } } } return 1; /* keep going */ }
173,662
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 P2PQuicStreamImpl::Finish() { DCHECK(!fin_sent()); quic::QuicStream::WriteOrBufferData("", /*fin=*/true, nullptr); } 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 P2PQuicStreamImpl::Finish() { void P2PQuicStreamImpl::WriteData(std::vector<uint8_t> data, bool fin) { // It is up to the delegate to not write more data than the // |write_buffer_size_|. DCHECK_GE(write_buffer_size_, data.size() + write_buffered_amount_); write_buffered_amount_ += data.size(); QuicStream::WriteOrBufferData( quic::QuicStringPiece(reinterpret_cast<const char*>(data.data()), data.size()), fin, nullptr); }
172,261
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebContentsImpl::DidCallFocus() { if (IsFullscreenForCurrentTab()) ExitFullscreen(true); } Commit Message: Security drop fullscreen for any nested WebContents level. This relands 3dcaec6e30feebefc11e with a fix to the test. BUG=873080 TEST=as in bug Change-Id: Ie68b197fc6b92447e9633f233354a68fefcf20c7 Reviewed-on: https://chromium-review.googlesource.com/1175925 Reviewed-by: Sidney San Martín <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#583335} CWE ID: CWE-20
void WebContentsImpl::DidCallFocus() { ForSecurityDropFullscreen(); }
172,661
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_get_hash (MyObject *obj, GHashTable **ret, GError **error) { GHashTable *table; table = g_hash_table_new (g_str_hash, g_str_equal); g_hash_table_insert (table, "foo", "bar"); g_hash_table_insert (table, "baz", "whee"); g_hash_table_insert (table, "cow", "crack"); *ret = table; return TRUE; } Commit Message: CWE ID: CWE-264
my_object_get_hash (MyObject *obj, GHashTable **ret, GError **error)
165,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: static void setup_test_dir(char *tmp_dir, const char *files, ...) { va_list ap; assert_se(mkdtemp(tmp_dir) != NULL); va_start(ap, files); while (files != NULL) { _cleanup_free_ char *path = strappend(tmp_dir, files); assert_se(touch_file(path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, 0) == 0); files = va_arg(ap, const char *); } va_end(ap); } Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere CWE ID: CWE-264
static void setup_test_dir(char *tmp_dir, const char *files, ...) { va_list ap; assert_se(mkdtemp(tmp_dir) != NULL); va_start(ap, files); while (files != NULL) { _cleanup_free_ char *path = strappend(tmp_dir, files); assert_se(touch_file(path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID) == 0); files = va_arg(ap, const char *); } va_end(ap); }
170,108
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GetNetworkList(NetworkInterfaceList* networks, int policy) { if (networks == NULL) return false; base::ThreadRestrictions::AssertIOAllowed(); ifaddrs* interfaces; if (getifaddrs(&interfaces) < 0) { PLOG(ERROR) << "getifaddrs"; return false; } std::unique_ptr<internal::IPAttributesGetter> ip_attributes_getter; #if defined(OS_MACOSX) && !defined(OS_IOS) ip_attributes_getter = base::MakeUnique<internal::IPAttributesGetterMac>(); #endif bool result = internal::IfaddrsToNetworkInterfaceList( policy, interfaces, ip_attributes_getter.get(), networks); freeifaddrs(interfaces); return result; } 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
bool GetNetworkList(NetworkInterfaceList* networks, int policy) { if (networks == NULL) return false; base::ThreadRestrictions::AssertIOAllowed(); ifaddrs* interfaces; if (getifaddrs(&interfaces) < 0) { PLOG(ERROR) << "getifaddrs"; return false; } std::unique_ptr<internal::IPAttributesGetter> ip_attributes_getter; #if defined(OS_MACOSX) && !defined(OS_IOS) ip_attributes_getter = std::make_unique<internal::IPAttributesGetterMac>(); #endif bool result = internal::IfaddrsToNetworkInterfaceList( policy, interfaces, ip_attributes_getter.get(), networks); freeifaddrs(interfaces); return result; }
173,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: SPL_METHOD(DirectoryIterator, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *suffix = 0, *fname; int slen = 0; size_t flen; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(DirectoryIterator, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *suffix = 0, *fname; int slen = 0; size_t flen; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); }
167,034
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 V8LazyEventListener::prepareListenerObject(ExecutionContext* executionContext) { if (!executionContext) return; v8::HandleScope handleScope(toIsolate(executionContext)); v8::Local<v8::Context> v8Context = toV8Context(executionContext, world()); if (v8Context.IsEmpty()) return; ScriptState* scriptState = ScriptState::from(v8Context); if (!scriptState->contextIsValid()) return; if (executionContext->isDocument() && !toDocument(executionContext)->allowInlineEventHandlers(m_node, this, m_sourceURL, m_position.m_line)) { clearListenerObject(); return; } if (hasExistingListenerObject()) return; ASSERT(executionContext->isDocument()); ScriptState::Scope scope(scriptState); String listenerSource = InspectorInstrumentation::preprocessEventListener(toDocument(executionContext)->frame(), m_code, m_sourceURL, m_functionName); String code = "(function() {" "with (this[2]) {" "with (this[1]) {" "with (this[0]) {" "return function(" + m_eventParameterName + ") {" + listenerSource + "\n" // Insert '\n' otherwise //-style comments could break the handler. "};" "}}}})"; v8::Handle<v8::String> codeExternalString = v8String(isolate(), code); v8::Local<v8::Value> result = V8ScriptRunner::compileAndRunInternalScript(codeExternalString, isolate(), m_sourceURL, m_position); if (result.IsEmpty()) return; ASSERT(result->IsFunction()); v8::Local<v8::Function> intermediateFunction = result.As<v8::Function>(); HTMLFormElement* formElement = 0; if (m_node && m_node->isHTMLElement()) formElement = toHTMLElement(m_node)->formOwner(); v8::Handle<v8::Object> nodeWrapper = toObjectWrapper<Node>(m_node, scriptState); v8::Handle<v8::Object> formWrapper = toObjectWrapper<HTMLFormElement>(formElement, scriptState); v8::Handle<v8::Object> documentWrapper = toObjectWrapper<Document>(m_node ? m_node->ownerDocument() : 0, scriptState); v8::Local<v8::Object> thisObject = v8::Object::New(isolate()); if (thisObject.IsEmpty()) return; if (!thisObject->ForceSet(v8::Integer::New(isolate(), 0), nodeWrapper)) return; if (!thisObject->ForceSet(v8::Integer::New(isolate(), 1), formWrapper)) return; if (!thisObject->ForceSet(v8::Integer::New(isolate(), 2), documentWrapper)) return; v8::Local<v8::Value> innerValue = V8ScriptRunner::callInternalFunction(intermediateFunction, thisObject, 0, 0, isolate()); if (innerValue.IsEmpty() || !innerValue->IsFunction()) return; v8::Local<v8::Function> wrappedFunction = innerValue.As<v8::Function>(); v8::Local<v8::Function> toStringFunction = v8::Function::New(isolate(), V8LazyEventListenerToString); ASSERT(!toStringFunction.IsEmpty()); String toStringString = "function " + m_functionName + "(" + m_eventParameterName + ") {\n " + m_code + "\n}"; V8HiddenValue::setHiddenValue(isolate(), wrappedFunction, V8HiddenValue::toStringString(isolate()), v8String(isolate(), toStringString)); wrappedFunction->Set(v8AtomicString(isolate(), "toString"), toStringFunction); wrappedFunction->SetName(v8String(isolate(), m_functionName)); setListenerObject(wrappedFunction); } Commit Message: Turn a bunch of ASSERTs into graceful failures when compiling listeners BUG=456192 [email protected] Review URL: https://codereview.chromium.org/906193002 git-svn-id: svn://svn.chromium.org/blink/trunk@189796 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-17
void V8LazyEventListener::prepareListenerObject(ExecutionContext* executionContext) { if (!executionContext) return; v8::HandleScope handleScope(toIsolate(executionContext)); v8::Local<v8::Context> v8Context = toV8Context(executionContext, world()); if (v8Context.IsEmpty()) return; ScriptState* scriptState = ScriptState::from(v8Context); if (!scriptState->contextIsValid()) return; if (!executionContext->isDocument()) return; if (!toDocument(executionContext)->allowInlineEventHandlers(m_node, this, m_sourceURL, m_position.m_line)) { clearListenerObject(); return; } if (hasExistingListenerObject()) return; ScriptState::Scope scope(scriptState); String listenerSource = InspectorInstrumentation::preprocessEventListener(toDocument(executionContext)->frame(), m_code, m_sourceURL, m_functionName); String code = "(function() {" "with (this[2]) {" "with (this[1]) {" "with (this[0]) {" "return function(" + m_eventParameterName + ") {" + listenerSource + "\n" // Insert '\n' otherwise //-style comments could break the handler. "};" "}}}})"; v8::Handle<v8::String> codeExternalString = v8String(isolate(), code); v8::Local<v8::Value> result = V8ScriptRunner::compileAndRunInternalScript(codeExternalString, isolate(), m_sourceURL, m_position); if (result.IsEmpty()) return; if (!result->IsFunction()) return; v8::Local<v8::Function> intermediateFunction = result.As<v8::Function>(); HTMLFormElement* formElement = 0; if (m_node && m_node->isHTMLElement()) formElement = toHTMLElement(m_node)->formOwner(); v8::Handle<v8::Object> nodeWrapper = toObjectWrapper<Node>(m_node, scriptState); v8::Handle<v8::Object> formWrapper = toObjectWrapper<HTMLFormElement>(formElement, scriptState); v8::Handle<v8::Object> documentWrapper = toObjectWrapper<Document>(m_node ? m_node->ownerDocument() : 0, scriptState); v8::Local<v8::Object> thisObject = v8::Object::New(isolate()); if (thisObject.IsEmpty()) return; if (!thisObject->ForceSet(v8::Integer::New(isolate(), 0), nodeWrapper)) return; if (!thisObject->ForceSet(v8::Integer::New(isolate(), 1), formWrapper)) return; if (!thisObject->ForceSet(v8::Integer::New(isolate(), 2), documentWrapper)) return; v8::Local<v8::Value> innerValue = V8ScriptRunner::callInternalFunction(intermediateFunction, thisObject, 0, 0, isolate()); if (innerValue.IsEmpty() || !innerValue->IsFunction()) return; v8::Local<v8::Function> wrappedFunction = innerValue.As<v8::Function>(); v8::Local<v8::Function> toStringFunction = v8::Function::New(isolate(), V8LazyEventListenerToString); ASSERT(!toStringFunction.IsEmpty()); String toStringString = "function " + m_functionName + "(" + m_eventParameterName + ") {\n " + m_code + "\n}"; V8HiddenValue::setHiddenValue(isolate(), wrappedFunction, V8HiddenValue::toStringString(isolate()), v8String(isolate(), toStringString)); wrappedFunction->Set(v8AtomicString(isolate(), "toString"), toStringFunction); wrappedFunction->SetName(v8String(isolate(), m_functionName)); setListenerObject(wrappedFunction); }
172,025
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: rdpdr_process(STREAM s) { uint32 handle; uint16 vmin; uint16 component; uint16 pakid; logger(Protocol, Debug, "rdpdr_process()"); /* hexdump(s->p, s->end - s->p); */ in_uint16(s, component); in_uint16(s, pakid); if (component == RDPDR_CTYP_CORE) { switch (pakid) { case PAKID_CORE_DEVICE_IOREQUEST: rdpdr_process_irp(s); break; case PAKID_CORE_SERVER_ANNOUNCE: /* DR_CORE_SERVER_ANNOUNCE_REQ */ in_uint8s(s, 2); /* skip versionMajor */ in_uint16_le(s, vmin); /* VersionMinor */ in_uint32_le(s, g_client_id); /* ClientID */ /* The RDP client is responsibility to provide a random client id if server version is < 12 */ if (vmin < 0x000c) g_client_id = 0x815ed39d; /* IP address (use 127.0.0.1) 0x815ed39d */ g_epoch++; #if WITH_SCARD /* * We need to release all SCARD contexts to end all * current transactions and pending calls */ scard_release_all_contexts(); /* * According to [MS-RDPEFS] 3.2.5.1.2: * * If this packet appears after a sequence of other packets, * it is a signal that the server has reconnected to a new session * and the whole sequence has been reset. The client MUST treat * this packet as the beginning of a new sequence. * The client MUST also cancel all outstanding requests and release * previous references to all devices. * * If any problem arises in the future, please, pay attention to the * "If this packet appears after a sequence of other packets" part * */ #endif rdpdr_send_client_announce_reply(); rdpdr_send_client_name_request(); break; case PAKID_CORE_CLIENTID_CONFIRM: rdpdr_send_client_device_list_announce(); break; case PAKID_CORE_DEVICE_REPLY: in_uint32(s, handle); logger(Protocol, Debug, "rdpdr_process(), server connected to resource %d", handle); break; case PAKID_CORE_SERVER_CAPABILITY: rdpdr_send_client_capability_response(); break; default: logger(Protocol, Debug, "rdpdr_process(), pakid 0x%x of component 0x%x", pakid, component); break; } } else if (component == RDPDR_CTYP_PRN) { if (pakid == PAKID_PRN_CACHE_DATA) printercache_process(s); } else logger(Protocol, Warning, "rdpdr_process(), unhandled component 0x%x", component); } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
rdpdr_process(STREAM s) { uint32 handle; uint16 vmin; uint16 component; uint16 pakid; struct stream packet = *s; logger(Protocol, Debug, "rdpdr_process()"); /* hexdump(s->p, s->end - s->p); */ in_uint16(s, component); in_uint16(s, pakid); if (component == RDPDR_CTYP_CORE) { switch (pakid) { case PAKID_CORE_DEVICE_IOREQUEST: rdpdr_process_irp(s); break; case PAKID_CORE_SERVER_ANNOUNCE: /* DR_CORE_SERVER_ANNOUNCE_REQ */ in_uint8s(s, 2); /* skip versionMajor */ in_uint16_le(s, vmin); /* VersionMinor */ in_uint32_le(s, g_client_id); /* ClientID */ /* g_client_id is sent back to server, so lets check that we actually got valid data from stream to prevent that we leak back data to server */ if (!s_check(s)) { rdp_protocol_error("rdpdr_process(), consume of g_client_id from stream did overrun", &packet); } /* The RDP client is responsibility to provide a random client id if server version is < 12 */ if (vmin < 0x000c) g_client_id = 0x815ed39d; /* IP address (use 127.0.0.1) 0x815ed39d */ g_epoch++; #if WITH_SCARD /* * We need to release all SCARD contexts to end all * current transactions and pending calls */ scard_release_all_contexts(); /* * According to [MS-RDPEFS] 3.2.5.1.2: * * If this packet appears after a sequence of other packets, * it is a signal that the server has reconnected to a new session * and the whole sequence has been reset. The client MUST treat * this packet as the beginning of a new sequence. * The client MUST also cancel all outstanding requests and release * previous references to all devices. * * If any problem arises in the future, please, pay attention to the * "If this packet appears after a sequence of other packets" part * */ #endif rdpdr_send_client_announce_reply(); rdpdr_send_client_name_request(); break; case PAKID_CORE_CLIENTID_CONFIRM: rdpdr_send_client_device_list_announce(); break; case PAKID_CORE_DEVICE_REPLY: in_uint32(s, handle); logger(Protocol, Debug, "rdpdr_process(), server connected to resource %d", handle); break; case PAKID_CORE_SERVER_CAPABILITY: rdpdr_send_client_capability_response(); break; default: logger(Protocol, Debug, "rdpdr_process(), pakid 0x%x of component 0x%x", pakid, component); break; } } else if (component == RDPDR_CTYP_PRN) { if (pakid == PAKID_PRN_CACHE_DATA) printercache_process(s); } else logger(Protocol, Warning, "rdpdr_process(), unhandled component 0x%x", component); }
169,805
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string* GetTestingDMToken() { static std::string dm_token; return &dm_token; } Commit Message: Migrate download_protection code to new DM token class. Migrates RetrieveDMToken calls to use the new BrowserDMToken class. Bug: 1020296 Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234 Commit-Queue: Dominique Fauteux-Chapleau <[email protected]> Reviewed-by: Tien Mai <[email protected]> Reviewed-by: Daniel Rubery <[email protected]> Cr-Commit-Position: refs/heads/master@{#714196} CWE ID: CWE-20
std::string* GetTestingDMToken() { const char** GetTestingDMTokenStorage() { static const char* dm_token = ""; return &dm_token; }
172,354
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: EBMLHeader::~EBMLHeader() { delete[] m_docType; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
EBMLHeader::~EBMLHeader() void EBMLHeader::Init() { m_version = 1; m_readVersion = 1; m_maxIdLength = 4; m_maxSizeLength = 8; if (m_docType) { delete[] m_docType; m_docType = NULL; } m_docTypeVersion = 1; m_docTypeReadVersion = 1; }
174,465
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Track::GetNext(const BlockEntry* pCurrEntry, const BlockEntry*& pNextEntry) const { assert(pCurrEntry); assert(!pCurrEntry->EOS()); //? const Block* const pCurrBlock = pCurrEntry->GetBlock(); assert(pCurrBlock && pCurrBlock->GetTrackNumber() == m_info.number); if (!pCurrBlock || pCurrBlock->GetTrackNumber() != m_info.number) return -1; const Cluster* pCluster = pCurrEntry->GetCluster(); assert(pCluster); assert(!pCluster->EOS()); long status = pCluster->GetNext(pCurrEntry, pNextEntry); if (status < 0) // error return status; for (int i = 0;;) { while (pNextEntry) { const Block* const pNextBlock = pNextEntry->GetBlock(); assert(pNextBlock); if (pNextBlock->GetTrackNumber() == m_info.number) return 0; pCurrEntry = pNextEntry; status = pCluster->GetNext(pCurrEntry, pNextEntry); if (status < 0) // error return status; } pCluster = m_pSegment->GetNext(pCluster); if (pCluster == NULL) { pNextEntry = GetEOS(); return 1; } if (pCluster->EOS()) { #if 0 if (m_pSegment->Unparsed() <= 0) //all clusters have been loaded { pNextEntry = GetEOS(); return 1; } #else if (m_pSegment->DoneParsing()) { pNextEntry = GetEOS(); return 1; } #endif pNextEntry = NULL; return E_BUFFER_NOT_FULL; } status = pCluster->GetFirst(pNextEntry); if (status < 0) // error return status; if (pNextEntry == NULL) // empty cluster continue; ++i; if (i >= 100) break; } pNextEntry = GetEOS(); // so we can return a non-NULL value return 1; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long Track::GetNext(const BlockEntry* pCurrEntry, const BlockEntry*& pNextEntry) const { assert(pCurrEntry); assert(!pCurrEntry->EOS()); //? const Block* const pCurrBlock = pCurrEntry->GetBlock(); assert(pCurrBlock && pCurrBlock->GetTrackNumber() == m_info.number); if (!pCurrBlock || pCurrBlock->GetTrackNumber() != m_info.number) return -1; const Cluster* pCluster = pCurrEntry->GetCluster(); assert(pCluster); assert(!pCluster->EOS()); long status = pCluster->GetNext(pCurrEntry, pNextEntry); if (status < 0) // error return status; for (int i = 0;;) { while (pNextEntry) { const Block* const pNextBlock = pNextEntry->GetBlock(); assert(pNextBlock); if (pNextBlock->GetTrackNumber() == m_info.number) return 0; pCurrEntry = pNextEntry; status = pCluster->GetNext(pCurrEntry, pNextEntry); if (status < 0) // error return status; } pCluster = m_pSegment->GetNext(pCluster); if (pCluster == NULL) { pNextEntry = GetEOS(); return 1; } if (pCluster->EOS()) { if (m_pSegment->DoneParsing()) { pNextEntry = GetEOS(); return 1; } pNextEntry = NULL; return E_BUFFER_NOT_FULL; } status = pCluster->GetFirst(pNextEntry); if (status < 0) // error return status; if (pNextEntry == NULL) // empty cluster continue; ++i; if (i >= 100) break; } pNextEntry = GetEOS(); // so we can return a non-NULL value return 1; }
173,823
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: InstallVerifyFrame::InstallVerifyFrame(const wxString& lDmodFilePath) : InstallVerifyFrame_Base(NULL, wxID_ANY, _T("")) { mConfig = Config::GetConfig(); prepareDialog(); int flags = wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_REMAINING_TIME; wxProgressDialog lPrepareProgress(_("Preparing"), _("The D-Mod archive is being decompressed in a temporary file."), 100, this, flags); BZip lBZip(lDmodFilePath); mTarFilePath = lBZip.Extract(&lPrepareProgress); if (mTarFilePath.Len() != 0) { Tar lTar(mTarFilePath); lTar.ReadHeaders(); wxString lDmodDescription = lTar.getmDmodDescription(); "\n" "The D-Mod will be installed in subdirectory '%s'."), lTar.getInstalledDmodDirectory().c_str()); } else { int lBreakChar = lDmodDescription.Find( '\r' ); if ( lBreakChar <= 0 ) { lBreakChar = lDmodDescription.Find( '\n' ); } mDmodName = lDmodDescription.SubString( 0, lBreakChar - 1 ); this->SetTitle(_("DFArc - Install D-Mod - ") + mDmodName); } mDmodDescription->SetValue(lDmodDescription); mInstallButton->Enable(true); } Commit Message: CWE ID: CWE-22
InstallVerifyFrame::InstallVerifyFrame(const wxString& lDmodFilePath) : InstallVerifyFrame_Base(NULL, wxID_ANY, _T("")) { mConfig = Config::GetConfig(); prepareDialog(); int flags = wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_REMAINING_TIME; wxProgressDialog lPrepareProgress(_("Preparing"), _("The D-Mod archive is being decompressed in a temporary file."), 100, this, flags); BZip lBZip(lDmodFilePath); mTarFilePath = lBZip.Extract(&lPrepareProgress); if (mTarFilePath.Len() != 0) { Tar lTar(mTarFilePath); if (lTar.ReadHeaders() == 1) { this->EndModal(wxID_CANCEL); return; } wxString lDmodDescription = lTar.getmDmodDescription(); "\n" "The D-Mod will be installed in subdirectory '%s'."), lTar.getInstalledDmodDirectory().c_str()); } else { int lBreakChar = lDmodDescription.Find( '\r' ); if ( lBreakChar <= 0 ) { lBreakChar = lDmodDescription.Find( '\n' ); } mDmodName = lDmodDescription.SubString( 0, lBreakChar - 1 ); this->SetTitle(_("DFArc - Install D-Mod - ") + mDmodName); } mDmodDescription->SetValue(lDmodDescription); mInstallButton->Enable(true); }
165,346
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SiteInstance* parent_site_instance() const { return parent_site_instance_.get(); } Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper This CL is for the most part a mechanical change which extracts almost all the frame-based MimeHandlerView code out of ExtensionsGuestViewMessageFilter. This change both removes the current clutter form EGVMF as well as fixesa race introduced when the frame-based logic was added to EGVMF. The reason for the race was that EGVMF is destroyed on IO thread but all the access to it (for frame-based MHV) are from UI. [email protected],[email protected] Bug: 659750, 896679, 911161, 918861 Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda Reviewed-on: https://chromium-review.googlesource.com/c/1401451 Commit-Queue: Ehsan Karamad <[email protected]> Reviewed-by: James MacLean <[email protected]> Reviewed-by: Ehsan Karamad <[email protected]> Cr-Commit-Position: refs/heads/master@{#621155} CWE ID: CWE-362
SiteInstance* parent_site_instance() const {
173,050
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int unicode_cp_is_allowed(unsigned uni_cp, int document_type) { /* XML 1.0 HTML 4.01 HTML 5 * 0x09..0x0A 0x09..0x0A 0x09..0x0A * 0x0D 0x0D 0x0C..0x0D * 0x0020..0xD7FF 0x20..0x7E 0x20..0x7E * 0x00A0..0xD7FF 0x00A0..0xD7FF * 0xE000..0xFFFD 0xE000..0x10FFFF 0xE000..0xFDCF * 0x010000..0x10FFFF 0xFDF0..0x10FFFF (*) * * (*) exclude code points where ((code & 0xFFFF) >= 0xFFFE) * * References: * XML 1.0: <http://www.w3.org/TR/REC-xml/#charsets> * HTML 4.01: <http://www.w3.org/TR/1999/PR-html40-19990824/sgml/sgmldecl.html> * HTML 5: <http://dev.w3.org/html5/spec/Overview.html#preprocessing-the-input-stream> * * Not sure this is the relevant part for HTML 5, though. I opted to * disallow the characters that would result in a parse error when * preprocessing of the input stream. See also section 8.1.3. * * It's unclear if XHTML 1.0 allows C1 characters. I'll opt to apply to * XHTML 1.0 the same rules as for XML 1.0. * See <http://cmsmcq.com/2007/C1.xml>. */ switch (document_type) { case ENT_HTML_DOC_HTML401: return (uni_cp >= 0x20 && uni_cp <= 0x7E) || (uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) || (uni_cp >= 0xA0 && uni_cp <= 0xD7FF) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF); case ENT_HTML_DOC_HTML5: return (uni_cp >= 0x20 && uni_cp <= 0x7E) || (uni_cp >= 0x09 && uni_cp <= 0x0D && uni_cp != 0x0B) || /* form feed U+0C allowed */ (uni_cp >= 0xA0 && uni_cp <= 0xD7FF) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && ((uni_cp & 0xFFFF) < 0xFFFE) && /* last two of each plane (nonchars) disallowed */ (uni_cp < 0xFDD0 || uni_cp > 0xFDEF)); /* U+FDD0-U+FDEF (nonchars) disallowed */ case ENT_HTML_DOC_XHTML: case ENT_HTML_DOC_XML1: return (uni_cp >= 0x20 && uni_cp <= 0xD7FF) || (uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && uni_cp != 0xFFFE && uni_cp != 0xFFFF); default: return 1; } } Commit Message: Fix bug #72135 - don't create strings with lengths outside int range CWE ID: CWE-190
static inline int unicode_cp_is_allowed(unsigned uni_cp, int document_type) { /* XML 1.0 HTML 4.01 HTML 5 * 0x09..0x0A 0x09..0x0A 0x09..0x0A * 0x0D 0x0D 0x0C..0x0D * 0x0020..0xD7FF 0x20..0x7E 0x20..0x7E * 0x00A0..0xD7FF 0x00A0..0xD7FF * 0xE000..0xFFFD 0xE000..0x10FFFF 0xE000..0xFDCF * 0x010000..0x10FFFF 0xFDF0..0x10FFFF (*) * * (*) exclude code points where ((code & 0xFFFF) >= 0xFFFE) * * References: * XML 1.0: <http://www.w3.org/TR/REC-xml/#charsets> * HTML 4.01: <http://www.w3.org/TR/1999/PR-html40-19990824/sgml/sgmldecl.html> * HTML 5: <http://dev.w3.org/html5/spec/Overview.html#preprocessing-the-input-stream> * * Not sure this is the relevant part for HTML 5, though. I opted to * disallow the characters that would result in a parse error when * preprocessing of the input stream. See also section 8.1.3. * * It's unclear if XHTML 1.0 allows C1 characters. I'll opt to apply to * XHTML 1.0 the same rules as for XML 1.0. * See <http://cmsmcq.com/2007/C1.xml>. */ switch (document_type) { case ENT_HTML_DOC_HTML401: return (uni_cp >= 0x20 && uni_cp <= 0x7E) || (uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) || (uni_cp >= 0xA0 && uni_cp <= 0xD7FF) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF); case ENT_HTML_DOC_HTML5: return (uni_cp >= 0x20 && uni_cp <= 0x7E) || (uni_cp >= 0x09 && uni_cp <= 0x0D && uni_cp != 0x0B) || /* form feed U+0C allowed */ (uni_cp >= 0xA0 && uni_cp <= 0xD7FF) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && ((uni_cp & 0xFFFF) < 0xFFFE) && /* last two of each plane (nonchars) disallowed */ (uni_cp < 0xFDD0 || uni_cp > 0xFDEF)); /* U+FDD0-U+FDEF (nonchars) disallowed */ case ENT_HTML_DOC_XHTML: case ENT_HTML_DOC_XML1: return (uni_cp >= 0x20 && uni_cp <= 0xD7FF) || (uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && uni_cp != 0xFFFE && uni_cp != 0xFFFF); default: return 1; } }
167,179
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BGD_DECLARE(gdImagePtr) gdImageCropThreshold(gdImagePtr im, const unsigned int color, const float threshold) { const int width = gdImageSX(im); const int height = gdImageSY(im); int x,y; int match; gdRect crop; crop.x = 0; crop.y = 0; crop.width = 0; crop.height = 0; /* Pierre: crop everything sounds bad */ if (threshold > 100.0) { return NULL; } /* TODO: Add gdImageGetRowPtr and works with ptr at the row level * for the true color and palette images * new formats will simply work with ptr */ match = 1; for (y = 0; match && y < height; y++) { for (x = 0; match && x < width; x++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0; } } /* Pierre * Nothing to do > bye * Duplicate the image? */ if (y == height - 1) { return NULL; } crop.y = y -1; match = 1; for (y = height - 1; match && y >= 0; y--) { for (x = 0; match && x < width; x++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x, y), threshold)) > 0; } } if (y == 0) { crop.height = height - crop.y + 1; } else { crop.height = y - crop.y + 2; } match = 1; for (x = 0; match && x < width; x++) { for (y = 0; match && y < crop.y + crop.height - 1; y++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0; } } crop.x = x - 1; match = 1; for (x = width - 1; match && x >= 0; x--) { for (y = 0; match && y < crop.y + crop.height - 1; y++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0; } } crop.width = x - crop.x + 2; return gdImageCrop(im, &crop); } Commit Message: fix php 72494, invalid color index not handled, can lead to crash CWE ID: CWE-20
BGD_DECLARE(gdImagePtr) gdImageCropThreshold(gdImagePtr im, const unsigned int color, const float threshold) { const int width = gdImageSX(im); const int height = gdImageSY(im); int x,y; int match; gdRect crop; crop.x = 0; crop.y = 0; crop.width = 0; crop.height = 0; /* Pierre: crop everything sounds bad */ if (threshold > 100.0) { return NULL; } if (color < 0 || (!gdImageTrueColor(im) && color >= gdImageColorsTotal(im))) { return NULL; } /* TODO: Add gdImageGetRowPtr and works with ptr at the row level * for the true color and palette images * new formats will simply work with ptr */ match = 1; for (y = 0; match && y < height; y++) { for (x = 0; match && x < width; x++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0; } } /* Pierre * Nothing to do > bye * Duplicate the image? */ if (y == height - 1) { return NULL; } crop.y = y -1; match = 1; for (y = height - 1; match && y >= 0; y--) { for (x = 0; match && x < width; x++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x, y), threshold)) > 0; } } if (y == 0) { crop.height = height - crop.y + 1; } else { crop.height = y - crop.y + 2; } match = 1; for (x = 0; match && x < width; x++) { for (y = 0; match && y < crop.y + crop.height - 1; y++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0; } } crop.x = x - 1; match = 1; for (x = width - 1; match && x >= 0; x--) { for (y = 0; match && y < crop.y + crop.height - 1; y++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0; } } crop.width = x - crop.x + 2; return gdImageCrop(im, &crop); }
169,944
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ObjectBackedNativeHandler::RouteFunction( const std::string& name, const std::string& feature_name, const HandlerFunction& handler_function) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope(context_->v8_context()); v8::Local<v8::Object> data = v8::Object::New(isolate); SetPrivate(data, kHandlerFunction, v8::External::New(isolate, new HandlerFunction(handler_function))); SetPrivate(data, kFeatureName, v8_helpers::ToV8StringUnsafe(isolate, feature_name)); v8::Local<v8::FunctionTemplate> function_template = v8::FunctionTemplate::New(isolate, Router, data); v8::Local<v8::ObjectTemplate>::New(isolate, object_template_) ->Set(isolate, name.c_str(), function_template); router_data_.Append(data); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID:
void ObjectBackedNativeHandler::RouteFunction( const std::string& name, const std::string& feature_name, const HandlerFunction& handler_function) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope(context_->v8_context()); v8::Local<v8::Object> data = v8::Object::New(isolate); SetPrivate(data, kHandlerFunction, v8::External::New(isolate, new HandlerFunction(handler_function))); DCHECK(feature_name.empty() || ExtensionAPI::GetSharedInstance()->GetFeatureDependency(feature_name)) << feature_name; SetPrivate(data, kFeatureName, v8_helpers::ToV8StringUnsafe(isolate, feature_name)); v8::Local<v8::FunctionTemplate> function_template = v8::FunctionTemplate::New(isolate, Router, data); v8::Local<v8::ObjectTemplate>::New(isolate, object_template_) ->Set(isolate, name.c_str(), function_template); router_data_.Append(data); }
173,278
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: get_strings_2_svc(gstrings_arg *arg, struct svc_req *rqstp) { static gstrings_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_gstrings_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (! cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) && (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_INQUIRE, arg->princ, NULL))) { ret.code = KADM5_AUTH_GET; log_unauth("kadm5_get_strings", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_get_strings((void *)handle, arg->princ, &ret.strings, &ret.count); if (ret.code != 0) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_get_strings", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
get_strings_2_svc(gstrings_arg *arg, struct svc_req *rqstp) { static gstrings_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_gstrings_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (! cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) && (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_INQUIRE, arg->princ, NULL))) { ret.code = KADM5_AUTH_GET; log_unauth("kadm5_get_strings", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_get_strings((void *)handle, arg->princ, &ret.strings, &ret.count); if (ret.code != 0) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_get_strings", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,518
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. 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). CWE ID: CWE-125
ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; }
167,802
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 btif_config_save(void) { assert(alarm_timer != NULL); assert(config != NULL); alarm_set(alarm_timer, CONFIG_SETTLE_PERIOD_MS, timer_config_save, NULL); } Commit Message: Fix crashes with lots of discovered LE devices When loads of devices are discovered a config file which is too large can be written out, which causes the BT daemon to crash on startup. This limits the number of config entries for unpaired devices which are initialized, and prevents a large number from being saved to the filesystem. Bug: 26071376 Change-Id: I4a74094f57a82b17f94e99a819974b8bc8082184 CWE ID: CWE-119
void btif_config_save(void) { assert(alarm_timer != NULL); assert(config != NULL); alarm_set(alarm_timer, CONFIG_SETTLE_PERIOD_MS, timer_config_save_cb, NULL); }
173,929
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mm_release(struct task_struct *tsk, struct mm_struct *mm) { struct completion *vfork_done = tsk->vfork_done; /* Get rid of any cached register state */ deactivate_mm(tsk, mm); /* notify parent sleeping on vfork() */ if (vfork_done) { tsk->vfork_done = NULL; complete(vfork_done); } /* * If we're exiting normally, clear a user-space tid field if * requested. We leave this alone when dying by signal, to leave * the value intact in a core dump, and to save the unnecessary * trouble otherwise. Userland only wants this done for a sys_exit. */ if (tsk->clear_child_tid && !(tsk->flags & PF_SIGNALED) && atomic_read(&mm->mm_users) > 1) { u32 __user * tidptr = tsk->clear_child_tid; tsk->clear_child_tid = NULL; /* * We don't check the error code - if userspace has * not set up a proper pointer then tough luck. */ put_user(0, tidptr); sys_futex(tidptr, FUTEX_WAKE, 1, NULL, NULL, 0); } } Commit Message: Move "exit_robust_list" into mm_release() We don't want to get rid of the futexes just at exit() time, we want to drop them when doing an execve() too, since that gets rid of the previous VM image too. Doing it at mm_release() time means that we automatically always do it when we disassociate a VM map from the task. Reported-by: [email protected] Cc: Andrew Morton <[email protected]> Cc: Nick Piggin <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: Brad Spengler <[email protected]> Cc: Alex Efros <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Oleg Nesterov <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
void mm_release(struct task_struct *tsk, struct mm_struct *mm) { struct completion *vfork_done = tsk->vfork_done; /* Get rid of any futexes when releasing the mm */ #ifdef CONFIG_FUTEX if (unlikely(tsk->robust_list)) exit_robust_list(tsk); #ifdef CONFIG_COMPAT if (unlikely(tsk->compat_robust_list)) compat_exit_robust_list(tsk); #endif #endif /* Get rid of any cached register state */ deactivate_mm(tsk, mm); /* notify parent sleeping on vfork() */ if (vfork_done) { tsk->vfork_done = NULL; complete(vfork_done); } /* * If we're exiting normally, clear a user-space tid field if * requested. We leave this alone when dying by signal, to leave * the value intact in a core dump, and to save the unnecessary * trouble otherwise. Userland only wants this done for a sys_exit. */ if (tsk->clear_child_tid && !(tsk->flags & PF_SIGNALED) && atomic_read(&mm->mm_users) > 1) { u32 __user * tidptr = tsk->clear_child_tid; tsk->clear_child_tid = NULL; /* * We don't check the error code - if userspace has * not set up a proper pointer then tough luck. */ put_user(0, tidptr); sys_futex(tidptr, FUTEX_WAKE, 1, NULL, NULL, 0); } }
165,668
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 seticc(i_ctx_t * i_ctx_p, int ncomps, ref *ICCdict, float *range_buff) { int code, k; gs_color_space * pcs; ref * pstrmval; stream * s = 0L; cmm_profile_t *picc_profile = NULL; int i, expected = 0; ref * pnameval; static const char *const icc_std_profile_names[] = { GSICC_STANDARD_PROFILES }; static const char *const icc_std_profile_keys[] = { GSICC_STANDARD_PROFILES_KEYS }; /* verify the DataSource entry */ if (dict_find_string(ICCdict, "DataSource", &pstrmval) <= 0) return_error(gs_error_undefined); check_read_file(i_ctx_p, s, pstrmval); /* build the color space object */ code = gs_cspace_build_ICC(&pcs, NULL, gs_gstate_memory(igs)); if (code < 0) return gs_rethrow(code, "building color space object"); /* For now, dump the profile into a buffer and obtain handle from the buffer when we need it. We may want to change this later. This depends to some degree on what the CMS is capable of doing. I don't want to get bogged down on stream I/O at this point. Note also, if we are going to be putting these into the clist we will want to have this buffer. */ /* Check if we have the /Name entry. This is used to associate with specs that have enumerated types to indicate sRGB sGray etc */ if (dict_find_string(ICCdict, "Name", &pnameval) > 0){ uint size = r_size(pnameval); char *str = (char *)gs_alloc_bytes(gs_gstate_memory(igs), size+1, "seticc"); memcpy(str, (const char *)pnameval->value.bytes, size); str[size] = 0; /* Compare this to the standard profile names */ for (k = 0; k < GSICC_NUMBER_STANDARD_PROFILES; k++) { if ( strcmp( str, icc_std_profile_keys[k] ) == 0 ) { picc_profile = gsicc_get_profile_handle_file(icc_std_profile_names[k], strlen(icc_std_profile_names[k]), gs_gstate_memory(igs)); break; } } gs_free_object(gs_gstate_memory(igs), str, "seticc"); } else { picc_profile = gsicc_profile_new(s, gs_gstate_memory(igs), NULL, 0); if (picc_profile == NULL) return gs_throw(gs_error_VMerror, "Creation of ICC profile failed"); /* We have to get the profile handle due to the fact that we need to know if it has a data space that is CIELAB */ picc_profile->profile_handle = gsicc_get_profile_handle_buffer(picc_profile->buffer, picc_profile->buffer_size, gs_gstate_memory(igs)); } if (picc_profile == NULL || picc_profile->profile_handle == NULL) { /* Free up everything, the profile is not valid. We will end up going ahead and using a default based upon the number of components */ rc_decrement(picc_profile,"seticc"); rc_decrement(pcs,"seticc"); return -1; } code = gsicc_set_gscs_profile(pcs, picc_profile, gs_gstate_memory(igs)); if (code < 0) { rc_decrement(picc_profile,"seticc"); rc_decrement(pcs,"seticc"); return code; } picc_profile->num_comps = ncomps; picc_profile->data_cs = gscms_get_profile_data_space(picc_profile->profile_handle, picc_profile->memory); switch (picc_profile->data_cs) { case gsCIEXYZ: case gsCIELAB: case gsRGB: expected = 3; break; case gsGRAY: expected = 1; break; case gsCMYK: expected = 4; break; case gsNCHANNEL: case gsNAMED: /* Silence warnings */ case gsUNDEFINED: /* Silence warnings */ break; } if (!expected || ncomps != expected) { rc_decrement(picc_profile,"seticc"); rc_decrement(pcs,"seticc"); return_error(gs_error_rangecheck); } /* Lets go ahead and get the hash code and check if we match one of the default spaces */ /* Later we may want to delay this, but for now lets go ahead and do it */ gsicc_init_hash_cs(picc_profile, igs); /* Set the range according to the data type that is associated with the ICC input color type. Occasionally, we will run into CIELAB to CIELAB profiles for spot colors in PDF documents. These spot colors are typically described as separation colors with tint transforms that go from a tint value to a linear mapping between the CIELAB white point and the CIELAB tint color. This results in a CIELAB value that we need to use to fill. We need to detect this to make sure we do the proper scaling of the data. For CIELAB images in PDF, the source is always normal 8 or 16 bit encoded data in the range from 0 to 255 or 0 to 65535. In that case, there should not be any encoding and decoding to CIELAB. The PDF content will not include an ICC profile but will set the color space to \Lab. In this case, we use our seticc_lab operation to install the LAB to LAB profile, but we detect that we did that through the use of the is_lab flag in the profile descriptor. When then avoid the CIELAB encode and decode */ if (picc_profile->data_cs == gsCIELAB) { /* If the input space to this profile is CIELAB, then we need to adjust the limits */ /* See ICC spec ICC.1:2004-10 Section 6.3.4.2 and 6.4. I don't believe we need to worry about CIEXYZ profiles or any of the other odds ones. Need to check that though at some point. */ picc_profile->Range.ranges[0].rmin = 0.0; picc_profile->Range.ranges[0].rmax = 100.0; picc_profile->Range.ranges[1].rmin = -128.0; picc_profile->Range.ranges[1].rmax = 127.0; picc_profile->Range.ranges[2].rmin = -128.0; picc_profile->Range.ranges[2].rmax = 127.0; picc_profile->islab = true; } else { for (i = 0; i < ncomps; i++) { picc_profile->Range.ranges[i].rmin = range_buff[2 * i]; picc_profile->Range.ranges[i].rmax = range_buff[2 * i + 1]; } } /* Now see if we are in an overide situation. We have to wait until now in case this is an LAB profile which we will not overide */ if (gs_currentoverrideicc(igs) && picc_profile->data_cs != gsCIELAB) { /* Free up the profile structure */ switch( picc_profile->data_cs ) { case gsRGB: pcs->cmm_icc_profile_data = igs->icc_manager->default_rgb; break; case gsGRAY: pcs->cmm_icc_profile_data = igs->icc_manager->default_gray; break; case gsCMYK: pcs->cmm_icc_profile_data = igs->icc_manager->default_cmyk; break; default: break; } /* Have one increment from the color space. Having these tied together is not really correct. Need to fix that. ToDo. MJV */ rc_adjust(picc_profile, -2, "seticc"); rc_increment(pcs->cmm_icc_profile_data); } /* Set the color space. We are done. No joint cache here... */ code = gs_setcolorspace(igs, pcs); /* The context has taken a reference to the colorspace. We no longer need * ours, so drop it. */ rc_decrement_only(pcs, "seticc"); /* In this case, we already have a ref count of 2 on the icc profile one for when it was created and one for when it was set. We really only want one here so adjust */ rc_decrement(picc_profile,"seticc"); /* Remove the ICC dict from the stack */ pop(1); return code; } Commit Message: CWE ID: CWE-704
int seticc(i_ctx_t * i_ctx_p, int ncomps, ref *ICCdict, float *range_buff) { int code, k; gs_color_space * pcs; ref * pstrmval; stream * s = 0L; cmm_profile_t *picc_profile = NULL; int i, expected = 0; ref * pnameval; static const char *const icc_std_profile_names[] = { GSICC_STANDARD_PROFILES }; static const char *const icc_std_profile_keys[] = { GSICC_STANDARD_PROFILES_KEYS }; /* verify the DataSource entry */ if (dict_find_string(ICCdict, "DataSource", &pstrmval) <= 0) return_error(gs_error_undefined); check_read_file(i_ctx_p, s, pstrmval); /* build the color space object */ code = gs_cspace_build_ICC(&pcs, NULL, gs_gstate_memory(igs)); if (code < 0) return gs_rethrow(code, "building color space object"); /* For now, dump the profile into a buffer and obtain handle from the buffer when we need it. We may want to change this later. This depends to some degree on what the CMS is capable of doing. I don't want to get bogged down on stream I/O at this point. Note also, if we are going to be putting these into the clist we will want to have this buffer. */ /* Check if we have the /Name entry. This is used to associate with specs that have enumerated types to indicate sRGB sGray etc */ if (dict_find_string(ICCdict, "Name", &pnameval) > 0 && r_has_type(pnameval, t_string)){ uint size = r_size(pnameval); char *str = (char *)gs_alloc_bytes(gs_gstate_memory(igs), size+1, "seticc"); memcpy(str, (const char *)pnameval->value.bytes, size); str[size] = 0; /* Compare this to the standard profile names */ for (k = 0; k < GSICC_NUMBER_STANDARD_PROFILES; k++) { if ( strcmp( str, icc_std_profile_keys[k] ) == 0 ) { picc_profile = gsicc_get_profile_handle_file(icc_std_profile_names[k], strlen(icc_std_profile_names[k]), gs_gstate_memory(igs)); break; } } gs_free_object(gs_gstate_memory(igs), str, "seticc"); } else { picc_profile = gsicc_profile_new(s, gs_gstate_memory(igs), NULL, 0); if (picc_profile == NULL) return gs_throw(gs_error_VMerror, "Creation of ICC profile failed"); /* We have to get the profile handle due to the fact that we need to know if it has a data space that is CIELAB */ picc_profile->profile_handle = gsicc_get_profile_handle_buffer(picc_profile->buffer, picc_profile->buffer_size, gs_gstate_memory(igs)); } if (picc_profile == NULL || picc_profile->profile_handle == NULL) { /* Free up everything, the profile is not valid. We will end up going ahead and using a default based upon the number of components */ rc_decrement(picc_profile,"seticc"); rc_decrement(pcs,"seticc"); return -1; } code = gsicc_set_gscs_profile(pcs, picc_profile, gs_gstate_memory(igs)); if (code < 0) { rc_decrement(picc_profile,"seticc"); rc_decrement(pcs,"seticc"); return code; } picc_profile->num_comps = ncomps; picc_profile->data_cs = gscms_get_profile_data_space(picc_profile->profile_handle, picc_profile->memory); switch (picc_profile->data_cs) { case gsCIEXYZ: case gsCIELAB: case gsRGB: expected = 3; break; case gsGRAY: expected = 1; break; case gsCMYK: expected = 4; break; case gsNCHANNEL: case gsNAMED: /* Silence warnings */ case gsUNDEFINED: /* Silence warnings */ break; } if (!expected || ncomps != expected) { rc_decrement(picc_profile,"seticc"); rc_decrement(pcs,"seticc"); return_error(gs_error_rangecheck); } /* Lets go ahead and get the hash code and check if we match one of the default spaces */ /* Later we may want to delay this, but for now lets go ahead and do it */ gsicc_init_hash_cs(picc_profile, igs); /* Set the range according to the data type that is associated with the ICC input color type. Occasionally, we will run into CIELAB to CIELAB profiles for spot colors in PDF documents. These spot colors are typically described as separation colors with tint transforms that go from a tint value to a linear mapping between the CIELAB white point and the CIELAB tint color. This results in a CIELAB value that we need to use to fill. We need to detect this to make sure we do the proper scaling of the data. For CIELAB images in PDF, the source is always normal 8 or 16 bit encoded data in the range from 0 to 255 or 0 to 65535. In that case, there should not be any encoding and decoding to CIELAB. The PDF content will not include an ICC profile but will set the color space to \Lab. In this case, we use our seticc_lab operation to install the LAB to LAB profile, but we detect that we did that through the use of the is_lab flag in the profile descriptor. When then avoid the CIELAB encode and decode */ if (picc_profile->data_cs == gsCIELAB) { /* If the input space to this profile is CIELAB, then we need to adjust the limits */ /* See ICC spec ICC.1:2004-10 Section 6.3.4.2 and 6.4. I don't believe we need to worry about CIEXYZ profiles or any of the other odds ones. Need to check that though at some point. */ picc_profile->Range.ranges[0].rmin = 0.0; picc_profile->Range.ranges[0].rmax = 100.0; picc_profile->Range.ranges[1].rmin = -128.0; picc_profile->Range.ranges[1].rmax = 127.0; picc_profile->Range.ranges[2].rmin = -128.0; picc_profile->Range.ranges[2].rmax = 127.0; picc_profile->islab = true; } else { for (i = 0; i < ncomps; i++) { picc_profile->Range.ranges[i].rmin = range_buff[2 * i]; picc_profile->Range.ranges[i].rmax = range_buff[2 * i + 1]; } } /* Now see if we are in an overide situation. We have to wait until now in case this is an LAB profile which we will not overide */ if (gs_currentoverrideicc(igs) && picc_profile->data_cs != gsCIELAB) { /* Free up the profile structure */ switch( picc_profile->data_cs ) { case gsRGB: pcs->cmm_icc_profile_data = igs->icc_manager->default_rgb; break; case gsGRAY: pcs->cmm_icc_profile_data = igs->icc_manager->default_gray; break; case gsCMYK: pcs->cmm_icc_profile_data = igs->icc_manager->default_cmyk; break; default: break; } /* Have one increment from the color space. Having these tied together is not really correct. Need to fix that. ToDo. MJV */ rc_adjust(picc_profile, -2, "seticc"); rc_increment(pcs->cmm_icc_profile_data); } /* Set the color space. We are done. No joint cache here... */ code = gs_setcolorspace(igs, pcs); /* The context has taken a reference to the colorspace. We no longer need * ours, so drop it. */ rc_decrement_only(pcs, "seticc"); /* In this case, we already have a ref count of 2 on the icc profile one for when it was created and one for when it was set. We really only want one here so adjust */ rc_decrement(picc_profile,"seticc"); /* Remove the ICC dict from the stack */ pop(1); return code; }
164,634
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltParseStylesheetAttributeSet(xsltStylesheetPtr style, xmlNodePtr cur) { const xmlChar *ncname; const xmlChar *prefix; xmlChar *value; xmlNodePtr child; xsltAttrElemPtr attrItems; if ((cur == NULL) || (style == NULL) || (cur->type != XML_ELEMENT_NODE)) return; value = xmlGetNsProp(cur, (const xmlChar *)"name", NULL); if (value == NULL) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : name is missing\n"); return; } ncname = xsltSplitQName(style->dict, value, &prefix); xmlFree(value); value = NULL; if (style->attributeSets == NULL) { #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "creating attribute set table\n"); #endif style->attributeSets = xmlHashCreate(10); } if (style->attributeSets == NULL) return; attrItems = xmlHashLookup2(style->attributeSets, ncname, prefix); /* * Parse the content. Only xsl:attribute elements are allowed. */ child = cur->children; while (child != NULL) { /* * Report invalid nodes. */ if ((child->type != XML_ELEMENT_NODE) || (child->ns == NULL) || (! IS_XSLT_ELEM(child))) { if (child->type == XML_ELEMENT_NODE) xsltTransformError(NULL, style, child, "xsl:attribute-set : unexpected child %s\n", child->name); else xsltTransformError(NULL, style, child, "xsl:attribute-set : child of unexpected type\n"); } else if (!IS_XSLT_NAME(child, "attribute")) { xsltTransformError(NULL, style, child, "xsl:attribute-set : unexpected child xsl:%s\n", child->name); } else { #ifdef XSLT_REFACTORED xsltAttrElemPtr nextAttr, curAttr; /* * Process xsl:attribute * --------------------- */ #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "add attribute to list %s\n", ncname); #endif /* * The following was taken over from * xsltAddAttrElemList(). */ if (attrItems == NULL) { attrItems = xsltNewAttrElem(child); } else { curAttr = attrItems; while (curAttr != NULL) { nextAttr = curAttr->next; if (curAttr->attr == child) { /* * URGENT TODO: Can somebody explain * why attrItems is set to curAttr * here? Is this somehow related to * avoidance of recursions? */ attrItems = curAttr; goto next_child; } if (curAttr->next == NULL) curAttr->next = xsltNewAttrElem(child); curAttr = nextAttr; } } /* * Parse the xsl:attribute and its content. */ xsltParseAnyXSLTElem(XSLT_CCTXT(style), child); #else #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "add attribute to list %s\n", ncname); #endif /* * OLD behaviour: */ attrItems = xsltAddAttrElemList(attrItems, child); #endif } #ifdef XSLT_REFACTORED next_child: #endif child = child->next; } /* * Process attribue "use-attribute-sets". */ /* TODO check recursion */ value = xmlGetNsProp(cur, (const xmlChar *)"use-attribute-sets", NULL); if (value != NULL) { const xmlChar *curval, *endval; curval = value; while (*curval != 0) { while (IS_BLANK(*curval)) curval++; if (*curval == 0) break; endval = curval; while ((*endval != 0) && (!IS_BLANK(*endval))) endval++; curval = xmlDictLookup(style->dict, curval, endval - curval); if (curval) { const xmlChar *ncname2 = NULL; const xmlChar *prefix2 = NULL; xsltAttrElemPtr refAttrItems; #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "xsl:attribute-set : %s adds use %s\n", ncname, curval); #endif ncname2 = xsltSplitQName(style->dict, curval, &prefix2); refAttrItems = xsltNewAttrElem(NULL); if (refAttrItems != NULL) { refAttrItems->set = ncname2; refAttrItems->ns = prefix2; attrItems = xsltMergeAttrElemList(style, attrItems, refAttrItems); xsltFreeAttrElem(refAttrItems); } } curval = endval; } xmlFree(value); value = NULL; } /* * Update the value */ /* * TODO: Why is this dummy entry needed.? */ if (attrItems == NULL) attrItems = xsltNewAttrElem(NULL); xmlHashUpdateEntry2(style->attributeSets, ncname, prefix, attrItems, NULL); #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "updated attribute list %s\n", ncname); #endif } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltParseStylesheetAttributeSet(xsltStylesheetPtr style, xmlNodePtr cur) { const xmlChar *ncname; const xmlChar *prefix; xmlChar *value; xmlNodePtr child; xsltAttrElemPtr attrItems; if ((cur == NULL) || (style == NULL) || (cur->type != XML_ELEMENT_NODE)) return; value = xmlGetNsProp(cur, (const xmlChar *)"name", NULL); if ((value == NULL) || (*value == 0)) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : name is missing\n"); if (value) xmlFree(value); return; } ncname = xsltSplitQName(style->dict, value, &prefix); xmlFree(value); value = NULL; if (style->attributeSets == NULL) { #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "creating attribute set table\n"); #endif style->attributeSets = xmlHashCreate(10); } if (style->attributeSets == NULL) return; attrItems = xmlHashLookup2(style->attributeSets, ncname, prefix); /* * Parse the content. Only xsl:attribute elements are allowed. */ child = cur->children; while (child != NULL) { /* * Report invalid nodes. */ if ((child->type != XML_ELEMENT_NODE) || (child->ns == NULL) || (! IS_XSLT_ELEM(child))) { if (child->type == XML_ELEMENT_NODE) xsltTransformError(NULL, style, child, "xsl:attribute-set : unexpected child %s\n", child->name); else xsltTransformError(NULL, style, child, "xsl:attribute-set : child of unexpected type\n"); } else if (!IS_XSLT_NAME(child, "attribute")) { xsltTransformError(NULL, style, child, "xsl:attribute-set : unexpected child xsl:%s\n", child->name); } else { #ifdef XSLT_REFACTORED xsltAttrElemPtr nextAttr, curAttr; /* * Process xsl:attribute * --------------------- */ #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "add attribute to list %s\n", ncname); #endif /* * The following was taken over from * xsltAddAttrElemList(). */ if (attrItems == NULL) { attrItems = xsltNewAttrElem(child); } else { curAttr = attrItems; while (curAttr != NULL) { nextAttr = curAttr->next; if (curAttr->attr == child) { /* * URGENT TODO: Can somebody explain * why attrItems is set to curAttr * here? Is this somehow related to * avoidance of recursions? */ attrItems = curAttr; goto next_child; } if (curAttr->next == NULL) curAttr->next = xsltNewAttrElem(child); curAttr = nextAttr; } } /* * Parse the xsl:attribute and its content. */ xsltParseAnyXSLTElem(XSLT_CCTXT(style), child); #else #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "add attribute to list %s\n", ncname); #endif /* * OLD behaviour: */ attrItems = xsltAddAttrElemList(attrItems, child); #endif } #ifdef XSLT_REFACTORED next_child: #endif child = child->next; } /* * Process attribue "use-attribute-sets". */ /* TODO check recursion */ value = xmlGetNsProp(cur, (const xmlChar *)"use-attribute-sets", NULL); if (value != NULL) { const xmlChar *curval, *endval; curval = value; while (*curval != 0) { while (IS_BLANK(*curval)) curval++; if (*curval == 0) break; endval = curval; while ((*endval != 0) && (!IS_BLANK(*endval))) endval++; curval = xmlDictLookup(style->dict, curval, endval - curval); if (curval) { const xmlChar *ncname2 = NULL; const xmlChar *prefix2 = NULL; xsltAttrElemPtr refAttrItems; #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "xsl:attribute-set : %s adds use %s\n", ncname, curval); #endif ncname2 = xsltSplitQName(style->dict, curval, &prefix2); refAttrItems = xsltNewAttrElem(NULL); if (refAttrItems != NULL) { refAttrItems->set = ncname2; refAttrItems->ns = prefix2; attrItems = xsltMergeAttrElemList(style, attrItems, refAttrItems); xsltFreeAttrElem(refAttrItems); } } curval = endval; } xmlFree(value); value = NULL; } /* * Update the value */ /* * TODO: Why is this dummy entry needed.? */ if (attrItems == NULL) attrItems = xsltNewAttrElem(NULL); xmlHashUpdateEntry2(style->attributeSets, ncname, prefix, attrItems, NULL); #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "updated attribute list %s\n", ncname); #endif }
173,298
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 HevcParameterSets::addNalUnit(const uint8_t* data, size_t size) { uint8_t nalUnitType = (data[0] >> 1) & 0x3f; status_t err = OK; switch (nalUnitType) { case 32: // VPS err = parseVps(data + 2, size - 2); break; case 33: // SPS err = parseSps(data + 2, size - 2); break; case 34: // PPS err = parsePps(data + 2, size - 2); break; case 39: // Prefix SEI case 40: // Suffix SEI break; default: ALOGE("Unrecognized NAL unit type."); return ERROR_MALFORMED; } if (err != OK) { return err; } sp<ABuffer> buffer = ABuffer::CreateAsCopy(data, size); buffer->setInt32Data(nalUnitType); mNalUnits.push(buffer); return OK; } Commit Message: Validate lengths in HEVC metadata parsing Add code to validate the size parameter passed to HecvParameterSets::addNalUnit(). Previously vulnerable to decrementing an unsigned past 0, yielding a huge result value. Bug: 35467107 Test: ran POC, no crash, emitted new "bad length" log entry Change-Id: Ia169b9edc1e0f7c5302e3c68aa90a54e8863d79e (cherry picked from commit e0dcf097cc029d056926029a29419e1650cbdf1b) CWE ID: CWE-476
status_t HevcParameterSets::addNalUnit(const uint8_t* data, size_t size) { if (size < 1) { ALOGE("empty NAL b/35467107"); return ERROR_MALFORMED; } uint8_t nalUnitType = (data[0] >> 1) & 0x3f; status_t err = OK; switch (nalUnitType) { case 32: // VPS if (size < 2) { ALOGE("invalid NAL/VPS size b/35467107"); return ERROR_MALFORMED; } err = parseVps(data + 2, size - 2); break; case 33: // SPS if (size < 2) { ALOGE("invalid NAL/SPS size b/35467107"); return ERROR_MALFORMED; } err = parseSps(data + 2, size - 2); break; case 34: // PPS if (size < 2) { ALOGE("invalid NAL/PPS size b/35467107"); return ERROR_MALFORMED; } err = parsePps(data + 2, size - 2); break; case 39: // Prefix SEI case 40: // Suffix SEI break; default: ALOGE("Unrecognized NAL unit type."); return ERROR_MALFORMED; } if (err != OK) { return err; } sp<ABuffer> buffer = ABuffer::CreateAsCopy(data, size); buffer->setInt32Data(nalUnitType); mNalUnits.push(buffer); return OK; }
174,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: xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ xmlNodePtr cur = NULL; long val; xmlChar str[30]; xmlDocPtr doc; if (nargs == 0) { cur = ctxt->context->node; } else if (nargs == 1) { xmlXPathObjectPtr obj; xmlNodeSetPtr nodelist; int i, ret; if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) { ctxt->error = XPATH_INVALID_TYPE; xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid arg expecting a node-set\n"); return; } obj = valuePop(ctxt); nodelist = obj->nodesetval; if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) { xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewCString("")); return; } cur = nodelist->nodeTab[0]; for (i = 1;i < nodelist->nodeNr;i++) { ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]); if (ret == -1) cur = nodelist->nodeTab[i]; } xmlXPathFreeObject(obj); } else { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid number of args %d\n", nargs); ctxt->error = XPATH_INVALID_ARITY; return; } /* * Okay this is ugly but should work, use the NodePtr address * to forge the ID */ if (cur->type != XML_NAMESPACE_DECL) doc = cur->doc; else { xmlNsPtr ns = (xmlNsPtr) cur; if (ns->context != NULL) doc = ns->context; else doc = ctxt->context->doc; } val = (long)((char *)cur - (char *)doc); if (val >= 0) { sprintf((char *)str, "idp%ld", val); } else { sprintf((char *)str, "idm%ld", -val); } valuePush(ctxt, xmlXPathNewString(str)); } Commit Message: Fix harmless memory error in generate-id. BUG=140368 Review URL: https://chromiumcodereview.appspot.com/10823168 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@149998 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ xmlNodePtr cur = NULL; xmlXPathObjectPtr obj = NULL; long val; xmlChar str[30]; xmlDocPtr doc; if (nargs == 0) { cur = ctxt->context->node; } else if (nargs == 1) { xmlNodeSetPtr nodelist; int i, ret; if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) { ctxt->error = XPATH_INVALID_TYPE; xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid arg expecting a node-set\n"); return; } obj = valuePop(ctxt); nodelist = obj->nodesetval; if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) { xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewCString("")); return; } cur = nodelist->nodeTab[0]; for (i = 1;i < nodelist->nodeNr;i++) { ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]); if (ret == -1) cur = nodelist->nodeTab[i]; } } else { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid number of args %d\n", nargs); ctxt->error = XPATH_INVALID_ARITY; return; } /* * Okay this is ugly but should work, use the NodePtr address * to forge the ID */ if (cur->type != XML_NAMESPACE_DECL) doc = cur->doc; else { xmlNsPtr ns = (xmlNsPtr) cur; if (ns->context != NULL) doc = ns->context; else doc = ctxt->context->doc; } if (obj) xmlXPathFreeObject(obj); val = (long)((char *)cur - (char *)doc); if (val >= 0) { sprintf((char *)str, "idp%ld", val); } else { sprintf((char *)str, "idm%ld", -val); } valuePush(ctxt, xmlXPathNewString(str)); }
170,903