instruction
stringclasses 1
value | input
stringlengths 90
9.3k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
|---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: InputMethodLibrary* CrosLibrary::GetInputMethodLibrary() {
return input_method_lib_.GetDefaultImpl(use_stub_impl_);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
|
InputMethodLibrary* CrosLibrary::GetInputMethodLibrary() {
| 170,623
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SeekHead::SeekHead(
Segment* pSegment,
long long start,
long long size_,
long long element_start,
long long element_size) :
m_pSegment(pSegment),
m_start(start),
m_size(size_),
m_element_start(element_start),
m_element_size(element_size),
m_entries(0),
m_entry_count(0),
m_void_elements(0),
m_void_element_count(0)
{
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
SeekHead::SeekHead(
// Outermost (level 0) segment object has been constructed,
// and pos designates start of payload. We need to find the
// inner (level 1) elements.
const long long header_status = ParseHeaders();
if (header_status < 0) // error
return static_cast<long>(header_status);
if (header_status > 0) // underflow
return E_BUFFER_NOT_FULL;
assert(m_pInfo);
assert(m_pTracks);
for (;;) {
const int status = LoadCluster();
if (status < 0) // error
return status;
if (status >= 1) // no more clusters
return 0;
}
}
| 174,437
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void js_RegExp_prototype_exec(js_State *J, js_Regexp *re, const char *text)
{
int i;
int opts;
Resub m;
opts = 0;
if (re->flags & JS_REGEXP_G) {
if (re->last > strlen(text)) {
re->last = 0;
js_pushnull(J);
return;
}
if (re->last > 0) {
text += re->last;
opts |= REG_NOTBOL;
}
}
if (!js_regexec(re->prog, text, &m, opts)) {
js_newarray(J);
js_pushstring(J, text);
js_setproperty(J, -2, "input");
js_pushnumber(J, js_utfptrtoidx(text, m.sub[0].sp));
js_setproperty(J, -2, "index");
for (i = 0; i < m.nsub; ++i) {
js_pushlstring(J, m.sub[i].sp, m.sub[i].ep - m.sub[i].sp);
js_setindex(J, -2, i);
}
if (re->flags & JS_REGEXP_G)
re->last = re->last + (m.sub[0].ep - text);
return;
}
if (re->flags & JS_REGEXP_G)
re->last = 0;
js_pushnull(J);
}
Commit Message: Bug 700937: Limit recursion in regexp matcher.
Also handle negative return code as an error in the JS bindings.
CWE ID: CWE-400
|
void js_RegExp_prototype_exec(js_State *J, js_Regexp *re, const char *text)
{
int result;
int i;
int opts;
Resub m;
opts = 0;
if (re->flags & JS_REGEXP_G) {
if (re->last > strlen(text)) {
re->last = 0;
js_pushnull(J);
return;
}
if (re->last > 0) {
text += re->last;
opts |= REG_NOTBOL;
}
}
result = js_regexec(re->prog, text, &m, opts);
if (result < 0)
js_error(J, "regexec failed");
if (result == 0) {
js_newarray(J);
js_pushstring(J, text);
js_setproperty(J, -2, "input");
js_pushnumber(J, js_utfptrtoidx(text, m.sub[0].sp));
js_setproperty(J, -2, "index");
for (i = 0; i < m.nsub; ++i) {
js_pushlstring(J, m.sub[i].sp, m.sub[i].ep - m.sub[i].sp);
js_setindex(J, -2, i);
}
if (re->flags & JS_REGEXP_G)
re->last = re->last + (m.sub[0].ep - text);
return;
}
if (re->flags & JS_REGEXP_G)
re->last = 0;
js_pushnull(J);
}
| 169,697
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ContentSuggestionsNotifierService::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterIntegerPref(
prefs::kContentSuggestionsConsecutiveIgnoredPrefName, 0);
registry->RegisterStringPref(kNotificationIDWithinCategory, std::string());
}
Commit Message: NTP: cap number of notifications/day
1 by default; Finch-configurable.
BUG=689465
Review-Url: https://codereview.chromium.org/2691023002
Cr-Commit-Position: refs/heads/master@{#450389}
CWE ID: CWE-399
|
void ContentSuggestionsNotifierService::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterIntegerPref(
prefs::kContentSuggestionsConsecutiveIgnoredPrefName, 0);
registry->RegisterIntegerPref(prefs::kContentSuggestionsNotificationsSentDay,
0);
registry->RegisterIntegerPref(
prefs::kContentSuggestionsNotificationsSentCount, 0);
registry->RegisterStringPref(kNotificationIDWithinCategory, std::string());
}
| 172,038
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params)
{
int i;
png_uint_16 freq[256];
/* libpng takes the count from the PLTE count; we don't check it here but we
* do set the array to 0 for unspecified entries.
*/
memset(freq, 0, sizeof freq);
for (i=0; i<nparams; ++i)
{
char *endptr = NULL;
unsigned long int l = strtoul(params[i], &endptr, 0/*base*/);
if (params[i][0] && *endptr == 0 && l <= 65535)
freq[i] = (png_uint_16)l;
else
{
fprintf(stderr, "hIST[%d]: %s: invalid frequency\n", i, params[i]);
exit(1);
}
}
png_set_hIST(png_ptr, info_ptr, freq);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params)
insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams,
png_charpp params)
{
int i;
png_uint_16 freq[256];
/* libpng takes the count from the PLTE count; we don't check it here but we
* do set the array to 0 for unspecified entries.
*/
memset(freq, 0, sizeof freq);
for (i=0; i<nparams; ++i)
{
char *endptr = NULL;
unsigned long int l = strtoul(params[i], &endptr, 0/*base*/);
if (params[i][0] && *endptr == 0 && l <= 65535)
freq[i] = (png_uint_16)l;
else
{
fprintf(stderr, "hIST[%d]: %s: invalid frequency\n", i, params[i]);
exit(1);
}
}
png_set_hIST(png_ptr, info_ptr, freq);
}
| 173,582
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 asn1_write_BOOLEAN(struct asn1_data *data, bool v)
{
asn1_push_tag(data, ASN1_BOOLEAN);
asn1_write_uint8(data, v ? 0xFF : 0);
asn1_pop_tag(data);
return !data->has_error;
}
Commit Message:
CWE ID: CWE-399
|
bool asn1_write_BOOLEAN(struct asn1_data *data, bool v)
{
if (!asn1_push_tag(data, ASN1_BOOLEAN)) return false;
if (!asn1_write_uint8(data, v ? 0xFF : 0)) return false;
return asn1_pop_tag(data);
}
| 164,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: AXObjectInclusion AXLayoutObject::defaultObjectInclusion(
IgnoredReasons* ignoredReasons) const {
if (!m_layoutObject) {
if (ignoredReasons)
ignoredReasons->push_back(IgnoredReason(AXNotRendered));
return IgnoreObject;
}
if (m_layoutObject->style()->visibility() != EVisibility::kVisible) {
if (equalIgnoringCase(getAttribute(aria_hiddenAttr), "false"))
return DefaultBehavior;
if (ignoredReasons)
ignoredReasons->push_back(IgnoredReason(AXNotVisible));
return IgnoreObject;
}
return AXObject::defaultObjectInclusion(ignoredReasons);
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
|
AXObjectInclusion AXLayoutObject::defaultObjectInclusion(
IgnoredReasons* ignoredReasons) const {
if (!m_layoutObject) {
if (ignoredReasons)
ignoredReasons->push_back(IgnoredReason(AXNotRendered));
return IgnoreObject;
}
if (m_layoutObject->style()->visibility() != EVisibility::kVisible) {
if (equalIgnoringASCIICase(getAttribute(aria_hiddenAttr), "false"))
return DefaultBehavior;
if (ignoredReasons)
ignoredReasons->push_back(IgnoredReason(AXNotVisible));
return IgnoreObject;
}
return AXObject::defaultObjectInclusion(ignoredReasons);
}
| 171,903
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static bool getCoverageFormat4(vector<uint32_t>& coverage, const uint8_t* data, size_t size) {
const size_t kSegCountOffset = 6;
const size_t kEndCountOffset = 14;
const size_t kHeaderSize = 16;
const size_t kSegmentSize = 8; // total size of array elements for one segment
if (kEndCountOffset > size) {
return false;
}
size_t segCount = readU16(data, kSegCountOffset) >> 1;
if (kHeaderSize + segCount * kSegmentSize > size) {
return false;
}
for (size_t i = 0; i < segCount; i++) {
uint32_t end = readU16(data, kEndCountOffset + 2 * i);
uint32_t start = readU16(data, kHeaderSize + 2 * (segCount + i));
if (end < start) {
return false;
}
uint32_t rangeOffset = readU16(data, kHeaderSize + 2 * (3 * segCount + i));
if (rangeOffset == 0) {
uint32_t delta = readU16(data, kHeaderSize + 2 * (2 * segCount + i));
if (((end + delta) & 0xffff) > end - start) {
addRange(coverage, start, end + 1);
} else {
for (uint32_t j = start; j < end + 1; j++) {
if (((j + delta) & 0xffff) != 0) {
addRange(coverage, j, j + 1);
}
}
}
} else {
for (uint32_t j = start; j < end + 1; j++) {
uint32_t actualRangeOffset = kHeaderSize + 6 * segCount + rangeOffset +
(i + j - start) * 2;
if (actualRangeOffset + 2 > size) {
continue;
}
uint32_t glyphId = readU16(data, actualRangeOffset);
if (glyphId != 0) {
addRange(coverage, j, j + 1);
}
}
}
}
return true;
}
Commit Message: Add error logging on invalid cmap - DO NOT MERGE
This patch logs instances of fonts with invalid cmap tables.
Bug: 25645298
Bug: 26413177
Change-Id: I183985e9784a97a2b4307a22e036382b1fc90e5e
CWE ID: CWE-20
|
static bool getCoverageFormat4(vector<uint32_t>& coverage, const uint8_t* data, size_t size) {
const size_t kSegCountOffset = 6;
const size_t kEndCountOffset = 14;
const size_t kHeaderSize = 16;
const size_t kSegmentSize = 8; // total size of array elements for one segment
if (kEndCountOffset > size) {
return false;
}
size_t segCount = readU16(data, kSegCountOffset) >> 1;
if (kHeaderSize + segCount * kSegmentSize > size) {
return false;
}
for (size_t i = 0; i < segCount; i++) {
uint32_t end = readU16(data, kEndCountOffset + 2 * i);
uint32_t start = readU16(data, kHeaderSize + 2 * (segCount + i));
if (end < start) {
android_errorWriteLog(0x534e4554, "26413177");
return false;
}
uint32_t rangeOffset = readU16(data, kHeaderSize + 2 * (3 * segCount + i));
if (rangeOffset == 0) {
uint32_t delta = readU16(data, kHeaderSize + 2 * (2 * segCount + i));
if (((end + delta) & 0xffff) > end - start) {
addRange(coverage, start, end + 1);
} else {
for (uint32_t j = start; j < end + 1; j++) {
if (((j + delta) & 0xffff) != 0) {
addRange(coverage, j, j + 1);
}
}
}
} else {
for (uint32_t j = start; j < end + 1; j++) {
uint32_t actualRangeOffset = kHeaderSize + 6 * segCount + rangeOffset +
(i + j - start) * 2;
if (actualRangeOffset + 2 > size) {
continue;
}
uint32_t glyphId = readU16(data, actualRangeOffset);
if (glyphId != 0) {
addRange(coverage, j, j + 1);
}
}
}
}
return true;
}
| 173,896
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE SoftVorbis::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioVorbis:
{
OMX_AUDIO_PARAM_VORBISTYPE *vorbisParams =
(OMX_AUDIO_PARAM_VORBISTYPE *)params;
if (vorbisParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
vorbisParams->nBitRate = 0;
vorbisParams->nMinBitRate = 0;
vorbisParams->nMaxBitRate = 0;
vorbisParams->nAudioBandWidth = 0;
vorbisParams->nQuality = 3;
vorbisParams->bManaged = OMX_FALSE;
vorbisParams->bDownmix = OMX_FALSE;
if (!isConfigured()) {
vorbisParams->nChannels = 1;
vorbisParams->nSampleRate = 44100;
} else {
vorbisParams->nChannels = mVi->channels;
vorbisParams->nSampleRate = mVi->rate;
vorbisParams->nBitRate = mVi->bitrate_nominal;
vorbisParams->nMinBitRate = mVi->bitrate_lower;
vorbisParams->nMaxBitRate = mVi->bitrate_upper;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
if (!isConfigured()) {
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = 44100;
} else {
pcmParams->nChannels = mVi->channels;
pcmParams->nSamplingRate = mVi->rate;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftVorbis::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioVorbis:
{
OMX_AUDIO_PARAM_VORBISTYPE *vorbisParams =
(OMX_AUDIO_PARAM_VORBISTYPE *)params;
if (!isValidOMXParam(vorbisParams)) {
return OMX_ErrorBadParameter;
}
if (vorbisParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
vorbisParams->nBitRate = 0;
vorbisParams->nMinBitRate = 0;
vorbisParams->nMaxBitRate = 0;
vorbisParams->nAudioBandWidth = 0;
vorbisParams->nQuality = 3;
vorbisParams->bManaged = OMX_FALSE;
vorbisParams->bDownmix = OMX_FALSE;
if (!isConfigured()) {
vorbisParams->nChannels = 1;
vorbisParams->nSampleRate = 44100;
} else {
vorbisParams->nChannels = mVi->channels;
vorbisParams->nSampleRate = mVi->rate;
vorbisParams->nBitRate = mVi->bitrate_nominal;
vorbisParams->nMinBitRate = mVi->bitrate_lower;
vorbisParams->nMaxBitRate = mVi->bitrate_upper;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
if (!isConfigured()) {
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = 44100;
} else {
pcmParams->nChannels = mVi->channels;
pcmParams->nSamplingRate = mVi->rate;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 174,220
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PepperMediaDeviceManager* PepperPlatformAudioInput::GetMediaDeviceManager() {
DCHECK(main_message_loop_proxy_->BelongsToCurrentThread());
RenderFrameImpl* const render_frame =
RenderFrameImpl::FromRoutingID(render_frame_id_);
return render_frame ?
PepperMediaDeviceManager::GetForRenderFrame(render_frame) : NULL;
}
Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr
Its lifetime is scoped to the RenderFrame, and it might go away before the
hosts that refer to it.
BUG=423030
Review URL: https://codereview.chromium.org/653243003
Cr-Commit-Position: refs/heads/master@{#299897}
CWE ID: CWE-399
|
PepperMediaDeviceManager* PepperPlatformAudioInput::GetMediaDeviceManager() {
DCHECK(main_message_loop_proxy_->BelongsToCurrentThread());
RenderFrameImpl* const render_frame =
RenderFrameImpl::FromRoutingID(render_frame_id_);
return render_frame ?
PepperMediaDeviceManager::GetForRenderFrame(render_frame).get() : NULL;
}
| 171,609
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cdrom_ioctl_drive_status(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_DRIVE_STATUS\n");
if (!(cdi->ops->capability & CDC_DRIVE_STATUS))
return -ENOSYS;
if (!CDROM_CAN(CDC_SELECT_DISC) ||
(arg == CDSL_CURRENT || arg == CDSL_NONE))
return cdi->ops->drive_status(cdi, CDSL_CURRENT);
if (((int)arg >= cdi->capacity))
return -EINVAL;
return cdrom_slot_status(cdi, arg);
}
Commit Message: cdrom: Fix info leak/OOB read in cdrom_ioctl_drive_status
Like d88b6d04: "cdrom: information leak in cdrom_ioctl_media_changed()"
There is another cast from unsigned long to int which causes
a bounds check to fail with specially crafted input. The value is
then used as an index in the slot array in cdrom_slot_status().
Signed-off-by: Scott Bauer <scott.bauer@intel.com>
Signed-off-by: Scott Bauer <sbauer@plzdonthack.me>
Cc: stable@vger.kernel.org
Signed-off-by: Jens Axboe <axboe@kernel.dk>
CWE ID: CWE-200
|
static int cdrom_ioctl_drive_status(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_DRIVE_STATUS\n");
if (!(cdi->ops->capability & CDC_DRIVE_STATUS))
return -ENOSYS;
if (!CDROM_CAN(CDC_SELECT_DISC) ||
(arg == CDSL_CURRENT || arg == CDSL_NONE))
return cdi->ops->drive_status(cdi, CDSL_CURRENT);
if (arg >= cdi->capacity)
return -EINVAL;
return cdrom_slot_status(cdi, arg);
}
| 169,035
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void CopyTransportDIBHandleForMessage(
const TransportDIB::Handle& handle_in,
TransportDIB::Handle* handle_out) {
#if defined(OS_MACOSX)
if ((handle_out->fd = HANDLE_EINTR(dup(handle_in.fd))) < 0) {
PLOG(ERROR) << "dup()";
return;
}
handle_out->auto_close = true;
#else
*handle_out = handle_in;
#endif
}
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:
|
static void CopyTransportDIBHandleForMessage(
const TransportDIB::Handle& handle_in,
TransportDIB::Handle* handle_out,
base::ProcessId peer_pid) {
#if defined(OS_MACOSX)
if ((handle_out->fd = HANDLE_EINTR(dup(handle_in.fd))) < 0) {
PLOG(ERROR) << "dup()";
return;
}
handle_out->auto_close = true;
#elif defined(OS_WIN)
// On Windows we need to duplicate the handle for the plugin process.
*handle_out = NULL;
sandbox::BrokerDuplicateHandle(handle_in, peer_pid, handle_out,
FILE_MAP_READ | FILE_MAP_WRITE, 0);
CHECK(*handle_out != NULL);
#else
*handle_out = handle_in;
#endif
}
| 170,955
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: status_t OMXNodeInstance::useBuffer(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
if (params == NULL || buffer == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size()) {
return BAD_VALUE;
}
BufferMeta *buffer_meta = new BufferMeta(params, portIndex);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_UseBuffer(
mHandle, &header, portIndex, buffer_meta,
allottedSize, static_cast<OMX_U8 *>(params->pointer()));
if (err != OMX_ErrorNone) {
CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER(
portIndex, (size_t)allottedSize, params->pointer()));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT(
*buffer, portIndex, "%u(%zu)@%p", allottedSize, params->size(), params->pointer()));
return OK;
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200
|
status_t OMXNodeInstance::useBuffer(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
if (params == NULL || buffer == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size() || portIndex >= NELEM(mNumPortBuffers)) {
return BAD_VALUE;
}
// metadata buffers are not connected cross process
// use a backup buffer instead of the actual buffer
BufferMeta *buffer_meta;
bool useBackup = mMetadataType[portIndex] != kMetadataBufferTypeInvalid;
OMX_U8 *data = static_cast<OMX_U8 *>(params->pointer());
// allocate backup buffer
if (useBackup) {
data = new (std::nothrow) OMX_U8[allottedSize];
if (data == NULL) {
return NO_MEMORY;
}
memset(data, 0, allottedSize);
// if we are not connecting the buffers, the sizes must match
if (allottedSize != params->size()) {
CLOG_ERROR(useBuffer, BAD_VALUE, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, data));
delete[] data;
return BAD_VALUE;
}
buffer_meta = new BufferMeta(
params, portIndex, false /* copyToOmx */, false /* copyFromOmx */, data);
} else {
buffer_meta = new BufferMeta(
params, portIndex, false /* copyFromOmx */, false /* copyToOmx */, NULL);
}
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_UseBuffer(
mHandle, &header, portIndex, buffer_meta,
allottedSize, data);
if (err != OMX_ErrorNone) {
CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER(
portIndex, (size_t)allottedSize, data));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT(
*buffer, portIndex, "%u(%zu)@%p", allottedSize, params->size(), params->pointer()));
return OK;
}
| 174,143
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void InputConnectionImpl::CommitText(const base::string16& text,
int new_cursor_pos) {
StartStateUpdateTimer();
std::string error;
if (!ime_engine_->ClearComposition(input_context_id_, &error))
LOG(ERROR) << "ClearComposition failed: error=\"" << error << "\"";
if (IsControlChar(text)) {
SendControlKeyEvent(text);
return;
}
if (!ime_engine_->CommitText(input_context_id_,
base::UTF16ToUTF8(text).c_str(), &error))
LOG(ERROR) << "CommitText failed: error=\"" << error << "\"";
}
Commit Message: Clear |composing_text_| after CommitText() is called.
|composing_text_| of InputConnectionImpl should be cleared after
CommitText() is called. Otherwise, FinishComposingText() will commit the
same text twice.
Bug: 899736
Test: unit_tests
Change-Id: Idb22d968ffe95d946789fbe62454e8e79cb0b384
Reviewed-on: https://chromium-review.googlesource.com/c/1304773
Commit-Queue: Yusuke Sato <yusukes@chromium.org>
Reviewed-by: Yusuke Sato <yusukes@chromium.org>
Cr-Commit-Position: refs/heads/master@{#603518}
CWE ID: CWE-119
|
void InputConnectionImpl::CommitText(const base::string16& text,
int new_cursor_pos) {
StartStateUpdateTimer();
std::string error;
if (!ime_engine_->ClearComposition(input_context_id_, &error))
LOG(ERROR) << "ClearComposition failed: error=\"" << error << "\"";
if (IsControlChar(text)) {
SendControlKeyEvent(text);
return;
}
if (!ime_engine_->CommitText(input_context_id_,
base::UTF16ToUTF8(text).c_str(), &error))
LOG(ERROR) << "CommitText failed: error=\"" << error << "\"";
composing_text_.clear();
}
| 173,333
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static ssize_t macvtap_get_user(struct macvtap_queue *q, struct msghdr *m,
const struct iovec *iv, unsigned long total_len,
size_t count, int noblock)
{
struct sk_buff *skb;
struct macvlan_dev *vlan;
unsigned long len = total_len;
int err;
struct virtio_net_hdr vnet_hdr = { 0 };
int vnet_hdr_len = 0;
int copylen;
bool zerocopy = false;
if (q->flags & IFF_VNET_HDR) {
vnet_hdr_len = q->vnet_hdr_sz;
err = -EINVAL;
if (len < vnet_hdr_len)
goto err;
len -= vnet_hdr_len;
err = memcpy_fromiovecend((void *)&vnet_hdr, iv, 0,
sizeof(vnet_hdr));
if (err < 0)
goto err;
if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 >
vnet_hdr.hdr_len)
vnet_hdr.hdr_len = vnet_hdr.csum_start +
vnet_hdr.csum_offset + 2;
err = -EINVAL;
if (vnet_hdr.hdr_len > len)
goto err;
}
err = -EINVAL;
if (unlikely(len < ETH_HLEN))
goto err;
if (m && m->msg_control && sock_flag(&q->sk, SOCK_ZEROCOPY))
zerocopy = true;
if (zerocopy) {
/* There are 256 bytes to be copied in skb, so there is enough
* room for skb expand head in case it is used.
* The rest buffer is mapped from userspace.
*/
copylen = vnet_hdr.hdr_len;
if (!copylen)
copylen = GOODCOPY_LEN;
} else
copylen = len;
skb = macvtap_alloc_skb(&q->sk, NET_IP_ALIGN, copylen,
vnet_hdr.hdr_len, noblock, &err);
if (!skb)
goto err;
if (zerocopy)
err = zerocopy_sg_from_iovec(skb, iv, vnet_hdr_len, count);
else
err = skb_copy_datagram_from_iovec(skb, 0, iv, vnet_hdr_len,
len);
if (err)
goto err_kfree;
skb_set_network_header(skb, ETH_HLEN);
skb_reset_mac_header(skb);
skb->protocol = eth_hdr(skb)->h_proto;
if (vnet_hdr_len) {
err = macvtap_skb_from_vnet_hdr(skb, &vnet_hdr);
if (err)
goto err_kfree;
}
rcu_read_lock_bh();
vlan = rcu_dereference_bh(q->vlan);
/* copy skb_ubuf_info for callback when skb has no error */
if (zerocopy) {
skb_shinfo(skb)->destructor_arg = m->msg_control;
skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
}
if (vlan)
macvlan_start_xmit(skb, vlan->dev);
else
kfree_skb(skb);
rcu_read_unlock_bh();
return total_len;
err_kfree:
kfree_skb(skb);
err:
rcu_read_lock_bh();
vlan = rcu_dereference_bh(q->vlan);
if (vlan)
vlan->dev->stats.tx_dropped++;
rcu_read_unlock_bh();
return err;
}
Commit Message: macvtap: zerocopy: validate vectors before building skb
There're several reasons that the vectors need to be validated:
- Return error when caller provides vectors whose num is greater than UIO_MAXIOV.
- Linearize part of skb when userspace provides vectors grater than MAX_SKB_FRAGS.
- Return error when userspace provides vectors whose total length may exceed
- MAX_SKB_FRAGS * PAGE_SIZE.
Signed-off-by: Jason Wang <jasowang@redhat.com>
Signed-off-by: Michael S. Tsirkin <mst@redhat.com>
CWE ID: CWE-119
|
static ssize_t macvtap_get_user(struct macvtap_queue *q, struct msghdr *m,
const struct iovec *iv, unsigned long total_len,
size_t count, int noblock)
{
struct sk_buff *skb;
struct macvlan_dev *vlan;
unsigned long len = total_len;
int err;
struct virtio_net_hdr vnet_hdr = { 0 };
int vnet_hdr_len = 0;
int copylen = 0;
bool zerocopy = false;
if (q->flags & IFF_VNET_HDR) {
vnet_hdr_len = q->vnet_hdr_sz;
err = -EINVAL;
if (len < vnet_hdr_len)
goto err;
len -= vnet_hdr_len;
err = memcpy_fromiovecend((void *)&vnet_hdr, iv, 0,
sizeof(vnet_hdr));
if (err < 0)
goto err;
if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 >
vnet_hdr.hdr_len)
vnet_hdr.hdr_len = vnet_hdr.csum_start +
vnet_hdr.csum_offset + 2;
err = -EINVAL;
if (vnet_hdr.hdr_len > len)
goto err;
}
err = -EINVAL;
if (unlikely(len < ETH_HLEN))
goto err;
err = -EMSGSIZE;
if (unlikely(count > UIO_MAXIOV))
goto err;
if (m && m->msg_control && sock_flag(&q->sk, SOCK_ZEROCOPY))
zerocopy = true;
if (zerocopy) {
/* Userspace may produce vectors with count greater than
* MAX_SKB_FRAGS, so we need to linearize parts of the skb
* to let the rest of data to be fit in the frags.
*/
if (count > MAX_SKB_FRAGS) {
copylen = iov_length(iv, count - MAX_SKB_FRAGS);
if (copylen < vnet_hdr_len)
copylen = 0;
else
copylen -= vnet_hdr_len;
}
/* There are 256 bytes to be copied in skb, so there is enough
* room for skb expand head in case it is used.
* The rest buffer is mapped from userspace.
*/
if (copylen < vnet_hdr.hdr_len)
copylen = vnet_hdr.hdr_len;
if (!copylen)
copylen = GOODCOPY_LEN;
} else
copylen = len;
skb = macvtap_alloc_skb(&q->sk, NET_IP_ALIGN, copylen,
vnet_hdr.hdr_len, noblock, &err);
if (!skb)
goto err;
if (zerocopy)
err = zerocopy_sg_from_iovec(skb, iv, vnet_hdr_len, count);
else
err = skb_copy_datagram_from_iovec(skb, 0, iv, vnet_hdr_len,
len);
if (err)
goto err_kfree;
skb_set_network_header(skb, ETH_HLEN);
skb_reset_mac_header(skb);
skb->protocol = eth_hdr(skb)->h_proto;
if (vnet_hdr_len) {
err = macvtap_skb_from_vnet_hdr(skb, &vnet_hdr);
if (err)
goto err_kfree;
}
rcu_read_lock_bh();
vlan = rcu_dereference_bh(q->vlan);
/* copy skb_ubuf_info for callback when skb has no error */
if (zerocopy) {
skb_shinfo(skb)->destructor_arg = m->msg_control;
skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
}
if (vlan)
macvlan_start_xmit(skb, vlan->dev);
else
kfree_skb(skb);
rcu_read_unlock_bh();
return total_len;
err_kfree:
kfree_skb(skb);
err:
rcu_read_lock_bh();
vlan = rcu_dereference_bh(q->vlan);
if (vlan)
vlan->dev->stats.tx_dropped++;
rcu_read_unlock_bh();
return err;
}
| 166,204
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from,
int offset, size_t count)
{
int len = iov_length(from, count) - offset;
int copy = skb_headlen(skb);
int size, offset1 = 0;
int i = 0;
/* Skip over from offset */
while (count && (offset >= from->iov_len)) {
offset -= from->iov_len;
++from;
--count;
}
/* copy up to skb headlen */
while (count && (copy > 0)) {
size = min_t(unsigned int, copy, from->iov_len - offset);
if (copy_from_user(skb->data + offset1, from->iov_base + offset,
size))
return -EFAULT;
if (copy > size) {
++from;
--count;
offset = 0;
} else
offset += size;
copy -= size;
offset1 += size;
}
if (len == offset1)
return 0;
while (count--) {
struct page *page[MAX_SKB_FRAGS];
int num_pages;
unsigned long base;
unsigned long truesize;
len = from->iov_len - offset;
if (!len) {
offset = 0;
++from;
continue;
}
base = (unsigned long)from->iov_base + offset;
size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT;
num_pages = get_user_pages_fast(base, size, 0, &page[i]);
if ((num_pages != size) ||
(num_pages > MAX_SKB_FRAGS - skb_shinfo(skb)->nr_frags)) {
for (i = 0; i < num_pages; i++)
put_page(page[i]);
return -EFAULT;
}
truesize = size * PAGE_SIZE;
skb->data_len += len;
skb->len += len;
skb->truesize += truesize;
atomic_add(truesize, &skb->sk->sk_wmem_alloc);
while (len) {
int off = base & ~PAGE_MASK;
int size = min_t(int, len, PAGE_SIZE - off);
__skb_fill_page_desc(skb, i, page[i], off, size);
skb_shinfo(skb)->nr_frags++;
/* increase sk_wmem_alloc */
base += size;
len -= size;
i++;
}
offset = 0;
++from;
}
return 0;
}
Commit Message: macvtap: zerocopy: validate vectors before building skb
There're several reasons that the vectors need to be validated:
- Return error when caller provides vectors whose num is greater than UIO_MAXIOV.
- Linearize part of skb when userspace provides vectors grater than MAX_SKB_FRAGS.
- Return error when userspace provides vectors whose total length may exceed
- MAX_SKB_FRAGS * PAGE_SIZE.
Signed-off-by: Jason Wang <jasowang@redhat.com>
Signed-off-by: Michael S. Tsirkin <mst@redhat.com>
CWE ID: CWE-119
|
static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from,
int offset, size_t count)
{
int len = iov_length(from, count) - offset;
int copy = skb_headlen(skb);
int size, offset1 = 0;
int i = 0;
/* Skip over from offset */
while (count && (offset >= from->iov_len)) {
offset -= from->iov_len;
++from;
--count;
}
/* copy up to skb headlen */
while (count && (copy > 0)) {
size = min_t(unsigned int, copy, from->iov_len - offset);
if (copy_from_user(skb->data + offset1, from->iov_base + offset,
size))
return -EFAULT;
if (copy > size) {
++from;
--count;
offset = 0;
} else
offset += size;
copy -= size;
offset1 += size;
}
if (len == offset1)
return 0;
while (count--) {
struct page *page[MAX_SKB_FRAGS];
int num_pages;
unsigned long base;
unsigned long truesize;
len = from->iov_len - offset;
if (!len) {
offset = 0;
++from;
continue;
}
base = (unsigned long)from->iov_base + offset;
size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT;
if (i + size > MAX_SKB_FRAGS)
return -EMSGSIZE;
num_pages = get_user_pages_fast(base, size, 0, &page[i]);
if (num_pages != size) {
for (i = 0; i < num_pages; i++)
put_page(page[i]);
return -EFAULT;
}
truesize = size * PAGE_SIZE;
skb->data_len += len;
skb->len += len;
skb->truesize += truesize;
atomic_add(truesize, &skb->sk->sk_wmem_alloc);
while (len) {
int off = base & ~PAGE_MASK;
int size = min_t(int, len, PAGE_SIZE - off);
__skb_fill_page_desc(skb, i, page[i], off, size);
skb_shinfo(skb)->nr_frags++;
/* increase sk_wmem_alloc */
base += size;
len -= size;
i++;
}
offset = 0;
++from;
}
return 0;
}
| 166,205
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: authentic_set_current_files(struct sc_card *card, struct sc_path *path,
unsigned char *resp, size_t resplen, struct sc_file **file_out)
{
struct sc_context *ctx = card->ctx;
struct sc_file *file = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
if (resplen) {
switch (resp[0]) {
case 0x62:
case 0x6F:
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
if (path)
file->path = *path;
rv = authentic_process_fci(card, file, resp, resplen);
LOG_TEST_RET(ctx, rv, "cannot set 'current file': FCI process error");
break;
default:
LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
if (file->type == SC_FILE_TYPE_DF) {
struct sc_path cur_df_path;
memset(&cur_df_path, 0, sizeof(cur_df_path));
if (card->cache.valid && card->cache.current_df) {
cur_df_path = card->cache.current_df->path;
sc_file_free(card->cache.current_df);
}
card->cache.current_df = NULL;
sc_file_dup(&card->cache.current_df, file);
if (cur_df_path.len) {
memcpy(card->cache.current_df->path.value + cur_df_path.len,
card->cache.current_df->path.value,
card->cache.current_df->path.len);
memcpy(card->cache.current_df->path.value, cur_df_path.value, cur_df_path.len);
card->cache.current_df->path.len += cur_df_path.len;
}
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
card->cache.valid = 1;
}
else {
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
sc_file_dup(&card->cache.current_ef, file);
}
if (file_out)
*file_out = file;
else
sc_file_free(file);
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
|
authentic_set_current_files(struct sc_card *card, struct sc_path *path,
unsigned char *resp, size_t resplen, struct sc_file **file_out)
{
struct sc_context *ctx = card->ctx;
struct sc_file *file = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
if (resplen) {
switch (resp[0]) {
case 0x62:
case 0x6F:
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
if (path)
file->path = *path;
rv = authentic_process_fci(card, file, resp, resplen);
LOG_TEST_RET(ctx, rv, "cannot set 'current file': FCI process error");
break;
default:
LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
if (file->type == SC_FILE_TYPE_DF) {
struct sc_path cur_df_path;
memset(&cur_df_path, 0, sizeof(cur_df_path));
if (card->cache.valid && card->cache.current_df) {
cur_df_path = card->cache.current_df->path;
sc_file_free(card->cache.current_df);
}
card->cache.current_df = NULL;
sc_file_dup(&card->cache.current_df, file);
if (cur_df_path.len) {
if (cur_df_path.len + card->cache.current_df->path.len > sizeof card->cache.current_df->path.value
|| cur_df_path.len > sizeof card->cache.current_df->path.value)
LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
memcpy(card->cache.current_df->path.value + cur_df_path.len,
card->cache.current_df->path.value,
card->cache.current_df->path.len);
memcpy(card->cache.current_df->path.value, cur_df_path.value, cur_df_path.len);
card->cache.current_df->path.len += cur_df_path.len;
}
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
card->cache.valid = 1;
}
else {
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
sc_file_dup(&card->cache.current_ef, file);
}
if (file_out)
*file_out = file;
else
sc_file_free(file);
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
| 169,049
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FindAndUpdateProperty(const chromeos::ImeProperty& new_prop,
chromeos::ImePropertyList* prop_list) {
for (size_t i = 0; i < prop_list->size(); ++i) {
chromeos::ImeProperty& prop = prop_list->at(i);
if (prop.key == new_prop.key) {
const int saved_id = prop.selection_item_id;
prop = new_prop;
prop.selection_item_id = saved_id;
return true;
}
}
return false;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool FindAndUpdateProperty(const chromeos::ImeProperty& new_prop,
bool FindAndUpdateProperty(
const chromeos::input_method::ImeProperty& new_prop,
chromeos::input_method::ImePropertyList* prop_list) {
for (size_t i = 0; i < prop_list->size(); ++i) {
chromeos::input_method::ImeProperty& prop = prop_list->at(i);
if (prop.key == new_prop.key) {
const int saved_id = prop.selection_item_id;
prop = new_prop;
prop.selection_item_id = saved_id;
return true;
}
}
return false;
}
| 170,484
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 multipath_ioctl(struct dm_target *ti, unsigned int cmd,
unsigned long arg)
{
struct multipath *m = (struct multipath *) ti->private;
struct block_device *bdev = NULL;
fmode_t mode = 0;
unsigned long flags;
int r = 0;
spin_lock_irqsave(&m->lock, flags);
if (!m->current_pgpath)
__choose_pgpath(m, 0);
if (m->current_pgpath) {
bdev = m->current_pgpath->path.dev->bdev;
mode = m->current_pgpath->path.dev->mode;
}
if (m->queue_io)
r = -EAGAIN;
else if (!bdev)
r = -EIO;
spin_unlock_irqrestore(&m->lock, flags);
return r ? : __blkdev_driver_ioctl(bdev, mode, cmd, arg);
}
Commit Message: dm: do not forward ioctls from logical volumes to the underlying device
A logical volume can map to just part of underlying physical volume.
In this case, it must be treated like a partition.
Based on a patch from Alasdair G Kergon.
Cc: Alasdair G Kergon <agk@redhat.com>
Cc: dm-devel@redhat.com
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-264
|
static int multipath_ioctl(struct dm_target *ti, unsigned int cmd,
unsigned long arg)
{
struct multipath *m = (struct multipath *) ti->private;
struct block_device *bdev = NULL;
fmode_t mode = 0;
unsigned long flags;
int r = 0;
spin_lock_irqsave(&m->lock, flags);
if (!m->current_pgpath)
__choose_pgpath(m, 0);
if (m->current_pgpath) {
bdev = m->current_pgpath->path.dev->bdev;
mode = m->current_pgpath->path.dev->mode;
}
if (m->queue_io)
r = -EAGAIN;
else if (!bdev)
r = -EIO;
spin_unlock_irqrestore(&m->lock, flags);
/*
* Only pass ioctls through if the device sizes match exactly.
*/
if (!r && ti->len != i_size_read(bdev->bd_inode) >> SECTOR_SHIFT)
r = scsi_verify_blk_ioctl(NULL, cmd);
return r ? : __blkdev_driver_ioctl(bdev, mode, cmd, arg);
}
| 165,724
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: METHODDEF(JDIMENSION)
get_word_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-word-format PPM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
for (col = cinfo->image_width; col > 0; col--) {
register unsigned int temp;
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_TOOLARGE);
*ptr++ = rescale[temp];
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_TOOLARGE);
*ptr++ = rescale[temp];
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_TOOLARGE);
*ptr++ = rescale[temp];
}
return 1;
}
Commit Message: cjpeg: Fix OOB read caused by malformed 8-bit BMP
... in which one or more of the color indices is out of range for the
number of palette entries.
Fix partly borrowed from jpeg-9c. This commit also adopts Guido's
JERR_PPM_OUTOFRANGE enum value in lieu of our project-specific
JERR_PPM_TOOLARGE enum value.
Fixes #258
CWE ID: CWE-125
|
METHODDEF(JDIMENSION)
get_word_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-word-format PPM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
for (col = cinfo->image_width; col > 0; col--) {
register unsigned int temp;
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);
*ptr++ = rescale[temp];
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);
*ptr++ = rescale[temp];
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);
*ptr++ = rescale[temp];
}
return 1;
}
| 169,839
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mbedtls_ecdsa_write_signature_restartable( mbedtls_ecdsa_context *ctx,
mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hlen,
unsigned char *sig, size_t *slen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret;
mbedtls_mpi r, s;
ECDSA_VALIDATE_RET( ctx != NULL );
ECDSA_VALIDATE_RET( hash != NULL );
ECDSA_VALIDATE_RET( sig != NULL );
ECDSA_VALIDATE_RET( slen != NULL );
mbedtls_mpi_init( &r );
mbedtls_mpi_init( &s );
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
(void) f_rng;
(void) p_rng;
MBEDTLS_MPI_CHK( ecdsa_sign_det_restartable( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, md_alg, rs_ctx ) );
#else
(void) md_alg;
#if defined(MBEDTLS_ECDSA_SIGN_ALT)
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, f_rng, p_rng ) );
#else
MBEDTLS_MPI_CHK( ecdsa_sign_restartable( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, f_rng, p_rng, rs_ctx ) );
#endif /* MBEDTLS_ECDSA_SIGN_ALT */
#endif /* MBEDTLS_ECDSA_DETERMINISTIC */
MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) );
cleanup:
mbedtls_mpi_free( &r );
mbedtls_mpi_free( &s );
return( ret );
}
Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/556' into mbedtls-2.16-restricted
CWE ID: CWE-200
|
int mbedtls_ecdsa_write_signature_restartable( mbedtls_ecdsa_context *ctx,
mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hlen,
unsigned char *sig, size_t *slen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret;
mbedtls_mpi r, s;
ECDSA_VALIDATE_RET( ctx != NULL );
ECDSA_VALIDATE_RET( hash != NULL );
ECDSA_VALIDATE_RET( sig != NULL );
ECDSA_VALIDATE_RET( slen != NULL );
mbedtls_mpi_init( &r );
mbedtls_mpi_init( &s );
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
MBEDTLS_MPI_CHK( ecdsa_sign_det_restartable( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, md_alg, f_rng,
p_rng, rs_ctx ) );
#else
(void) md_alg;
#if defined(MBEDTLS_ECDSA_SIGN_ALT)
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, f_rng, p_rng ) );
#else
/* Use the same RNG for both blinding and ephemeral key generation */
MBEDTLS_MPI_CHK( ecdsa_sign_restartable( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, f_rng, p_rng, f_rng,
p_rng, rs_ctx ) );
#endif /* MBEDTLS_ECDSA_SIGN_ALT */
#endif /* MBEDTLS_ECDSA_DETERMINISTIC */
MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) );
cleanup:
mbedtls_mpi_free( &r );
mbedtls_mpi_free( &s );
return( ret );
}
| 169,509
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 bool InputMethodIsActivated(const std::string& input_method_id) {
scoped_ptr<InputMethodDescriptors> active_input_method_descriptors(
GetActiveInputMethods());
for (size_t i = 0; i < active_input_method_descriptors->size(); ++i) {
if (active_input_method_descriptors->at(i).id == input_method_id) {
return true;
}
}
return false;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
virtual bool InputMethodIsActivated(const std::string& input_method_id) {
scoped_ptr<input_method::InputMethodDescriptors>
active_input_method_descriptors(
GetActiveInputMethods());
for (size_t i = 0; i < active_input_method_descriptors->size(); ++i) {
if (active_input_method_descriptors->at(i).id == input_method_id) {
return true;
}
}
return false;
}
| 170,496
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void PrintPreviewHandler::HandleGetPreview(const ListValue* args) {
DCHECK_EQ(3U, args->GetSize());
scoped_ptr<DictionaryValue> settings(GetSettingsDictionary(args));
if (!settings.get())
return;
int request_id = -1;
if (!settings->GetInteger(printing::kPreviewRequestID, &request_id))
return;
PrintPreviewUI* print_preview_ui = static_cast<PrintPreviewUI*>(
web_ui()->GetController());
print_preview_ui->OnPrintPreviewRequest(request_id);
settings->SetString(printing::kPreviewUIAddr,
print_preview_ui->GetPrintPreviewUIAddress());
++regenerate_preview_request_count_;
TabContents* initiator_tab = GetInitiatorTab();
if (!initiator_tab) {
ReportUserActionHistogram(INITIATOR_TAB_CLOSED);
print_preview_ui->OnClosePrintPreviewTab();
return;
}
bool display_header_footer = false;
if (!settings->GetBoolean(printing::kSettingHeaderFooterEnabled,
&display_header_footer)) {
NOTREACHED();
}
if (display_header_footer) {
settings->SetString(printing::kSettingHeaderFooterTitle,
initiator_tab->web_contents()->GetTitle());
std::string url;
NavigationEntry* entry =
initiator_tab->web_contents()->GetController().GetActiveEntry();
if (entry)
url = entry->GetVirtualURL().spec();
settings->SetString(printing::kSettingHeaderFooterURL, url);
}
bool generate_draft_data = false;
bool success = settings->GetBoolean(printing::kSettingGenerateDraftData,
&generate_draft_data);
DCHECK(success);
if (!generate_draft_data) {
double draft_page_count_double = -1;
success = args->GetDouble(1, &draft_page_count_double);
DCHECK(success);
int draft_page_count = static_cast<int>(draft_page_count_double);
bool preview_modifiable = false;
success = args->GetBoolean(2, &preview_modifiable);
DCHECK(success);
if (draft_page_count != -1 && preview_modifiable &&
print_preview_ui->GetAvailableDraftPageCount() != draft_page_count) {
settings->SetBoolean(printing::kSettingGenerateDraftData, true);
}
}
VLOG(1) << "Print preview request start";
RenderViewHost* rvh = initiator_tab->web_contents()->GetRenderViewHost();
rvh->Send(new PrintMsg_PrintPreview(rvh->GetRoutingID(), *settings));
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
void PrintPreviewHandler::HandleGetPreview(const ListValue* args) {
DCHECK_EQ(3U, args->GetSize());
scoped_ptr<DictionaryValue> settings(GetSettingsDictionary(args));
if (!settings.get())
return;
int request_id = -1;
if (!settings->GetInteger(printing::kPreviewRequestID, &request_id))
return;
PrintPreviewUI* print_preview_ui = static_cast<PrintPreviewUI*>(
web_ui()->GetController());
print_preview_ui->OnPrintPreviewRequest(request_id);
settings->SetInteger(printing::kPreviewUIID,
print_preview_ui->GetIDForPrintPreviewUI());
++regenerate_preview_request_count_;
TabContents* initiator_tab = GetInitiatorTab();
if (!initiator_tab) {
ReportUserActionHistogram(INITIATOR_TAB_CLOSED);
print_preview_ui->OnClosePrintPreviewTab();
return;
}
bool display_header_footer = false;
if (!settings->GetBoolean(printing::kSettingHeaderFooterEnabled,
&display_header_footer)) {
NOTREACHED();
}
if (display_header_footer) {
settings->SetString(printing::kSettingHeaderFooterTitle,
initiator_tab->web_contents()->GetTitle());
std::string url;
NavigationEntry* entry =
initiator_tab->web_contents()->GetController().GetActiveEntry();
if (entry)
url = entry->GetVirtualURL().spec();
settings->SetString(printing::kSettingHeaderFooterURL, url);
}
bool generate_draft_data = false;
bool success = settings->GetBoolean(printing::kSettingGenerateDraftData,
&generate_draft_data);
DCHECK(success);
if (!generate_draft_data) {
double draft_page_count_double = -1;
success = args->GetDouble(1, &draft_page_count_double);
DCHECK(success);
int draft_page_count = static_cast<int>(draft_page_count_double);
bool preview_modifiable = false;
success = args->GetBoolean(2, &preview_modifiable);
DCHECK(success);
if (draft_page_count != -1 && preview_modifiable &&
print_preview_ui->GetAvailableDraftPageCount() != draft_page_count) {
settings->SetBoolean(printing::kSettingGenerateDraftData, true);
}
}
VLOG(1) << "Print preview request start";
RenderViewHost* rvh = initiator_tab->web_contents()->GetRenderViewHost();
rvh->Send(new PrintMsg_PrintPreview(rvh->GetRoutingID(), *settings));
}
| 170,828
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: fb_mmap(struct file *file, struct vm_area_struct * vma)
{
struct fb_info *info = file_fb_info(file);
struct fb_ops *fb;
unsigned long off;
unsigned long start;
u32 len;
if (!info)
return -ENODEV;
if (vma->vm_pgoff > (~0UL >> PAGE_SHIFT))
return -EINVAL;
off = vma->vm_pgoff << PAGE_SHIFT;
fb = info->fbops;
if (!fb)
return -ENODEV;
mutex_lock(&info->mm_lock);
if (fb->fb_mmap) {
int res;
res = fb->fb_mmap(info, vma);
mutex_unlock(&info->mm_lock);
return res;
}
/* frame buffer memory */
start = info->fix.smem_start;
len = PAGE_ALIGN((start & ~PAGE_MASK) + info->fix.smem_len);
if (off >= len) {
/* memory mapped io */
off -= len;
if (info->var.accel_flags) {
mutex_unlock(&info->mm_lock);
return -EINVAL;
}
start = info->fix.mmio_start;
len = PAGE_ALIGN((start & ~PAGE_MASK) + info->fix.mmio_len);
}
mutex_unlock(&info->mm_lock);
start &= PAGE_MASK;
if ((vma->vm_end - vma->vm_start + off) > len)
return -EINVAL;
off += start;
vma->vm_pgoff = off >> PAGE_SHIFT;
/* VM_IO | VM_DONTEXPAND | VM_DONTDUMP are set by io_remap_pfn_range()*/
vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
fb_pgprotect(file, vma, off);
if (io_remap_pfn_range(vma, vma->vm_start, off >> PAGE_SHIFT,
vma->vm_end - vma->vm_start, vma->vm_page_prot))
return -EAGAIN;
return 0;
}
Commit Message: vm: convert fb_mmap to vm_iomap_memory() helper
This is my example conversion of a few existing mmap users. The
fb_mmap() case is a good example because it is a bit more complicated
than some: fb_mmap() mmaps one of two different memory areas depending
on the page offset of the mmap (but happily there is never any mixing of
the two, so the helper function still works).
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-189
|
fb_mmap(struct file *file, struct vm_area_struct * vma)
{
struct fb_info *info = file_fb_info(file);
struct fb_ops *fb;
unsigned long mmio_pgoff;
unsigned long start;
u32 len;
if (!info)
return -ENODEV;
fb = info->fbops;
if (!fb)
return -ENODEV;
mutex_lock(&info->mm_lock);
if (fb->fb_mmap) {
int res;
res = fb->fb_mmap(info, vma);
mutex_unlock(&info->mm_lock);
return res;
}
/*
* Ugh. This can be either the frame buffer mapping, or
* if pgoff points past it, the mmio mapping.
*/
start = info->fix.smem_start;
len = info->fix.smem_len;
mmio_pgoff = PAGE_ALIGN((start & ~PAGE_MASK) + len) >> PAGE_SHIFT;
if (vma->vm_pgoff >= mmio_pgoff) {
vma->vm_pgoff -= mmio_pgoff;
start = info->fix.mmio_start;
len = info->fix.mmio_len;
}
mutex_unlock(&info->mm_lock);
vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
fb_pgprotect(file, vma, start);
return vm_iomap_memory(vma, start, len);
}
| 166,060
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SQLWCHAR* _multi_string_alloc_and_expand( LPCSTR in )
{
SQLWCHAR *chr;
int len = 0;
if ( !in )
{
return in;
}
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
len ++;
}
chr = malloc(sizeof( SQLWCHAR ) * ( len + 2 ));
len = 0;
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
chr[ len ] = in[ len ];
len ++;
}
chr[ len ++ ] = 0;
chr[ len ++ ] = 0;
return chr;
}
Commit Message: New Pre Source
CWE ID: CWE-119
|
SQLWCHAR* _multi_string_alloc_and_expand( LPCSTR in )
{
SQLWCHAR *chr;
int len = 0;
if ( !in )
{
return NULL;
}
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
len ++;
}
chr = malloc(sizeof( SQLWCHAR ) * ( len + 2 ));
len = 0;
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
chr[ len ] = in[ len ];
len ++;
}
chr[ len ++ ] = 0;
chr[ len ++ ] = 0;
return chr;
}
| 169,314
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PrintPreviewUI::SetPrintPreviewDataForIndex(
int index,
const base::RefCountedBytes* data) {
print_preview_data_service()->SetDataEntry(preview_ui_addr_str_, index, data);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
void PrintPreviewUI::SetPrintPreviewDataForIndex(
int index,
const base::RefCountedBytes* data) {
print_preview_data_service()->SetDataEntry(id_, index, data);
}
| 170,843
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void TabCountChangeObserver::TabDetachedAt(TabContents* contents,
int index) {
CheckTabCount();
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void TabCountChangeObserver::TabDetachedAt(TabContents* contents,
void TabCountChangeObserver::TabDetachedAt(WebContents* contents,
int index) {
CheckTabCount();
}
| 171,504
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԗԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡउওဒვპ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Mapping several Indic characters to confusables.
A number of characters from several Indian scripts are confusable,
especially with numbers. This change maps these characters to their
ASCII lookalike to allow fallback to punycode when displaying probable
spoofing URLs.
Bug: 849421
Bug: 892646
Bug: 896722
Change-Id: I6d463642f3541454dc39bf4b32b8291417697c52
Reviewed-on: https://chromium-review.googlesource.com/c/1295179
Reviewed-by: Tommy Li <tommycli@chromium.org>
Commit-Queue: Joe DeBlasio <jdeblasio@chromium.org>
Cr-Commit-Position: refs/heads/master@{#602032}
CWE ID: CWE-20
|
IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԗԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// - {U+0966 (०), U+09E6 (০), U+0A66 (੦), U+0AE6 (૦), U+0B30 (ଠ),
// U+0B66 (୦), U+0CE6 (೦)} => o,
// - {U+09ED (৭), U+0A67 (੧), U+0AE7 (૧)} => q,
// - {U+0E1A (บ), U+0E9A (ບ)} => u
// - {U+0968 (२), U+09E8 (২), U+0A68 (੨), U+0A68 (੨), U+0AE8 (૨),
// U+0ce9 (೩), U+0ced (೭)} => 2,
// U+0A69 (੩), U+0AE9 (૩), U+0C69 (౩),
// - {U+0A6B (੫)} => 4,
// - {U+09EA (৪), U+0A6A (੪), U+0b6b (୫)} => 8,
// - {U+0AED (૭), U+0b68 (୨), U+0C68 (౨)} => 9,
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[०০੦૦ଠ୦೦] > o;"
"[৭੧૧] > q;"
"[บບ] > u;"
"[२২੨੨૨೩೭] > 2;"
"[зҙӡउও੩૩౩ဒვპ] > 3;"
"[੫] > 4;"
"[৪੪୫] > 8;"
"[૭୨౨] > 9;"
),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 173,115
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool SiteInstanceImpl::DoesSiteRequireDedicatedProcess(
BrowserContext* browser_context,
const GURL& url) {
if (SiteIsolationPolicy::UseDedicatedProcessesForAllSites())
return true;
if (url.SchemeIs(kChromeErrorScheme))
return true;
GURL site_url = SiteInstance::GetSiteForURL(browser_context, url);
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
if (policy->IsIsolatedOrigin(url::Origin::Create(site_url)))
return true;
if (GetContentClient()->browser()->DoesSiteRequireDedicatedProcess(
browser_context, site_url)) {
return true;
}
return false;
}
Commit Message: Allow origin lock for WebUI pages.
Returning true for WebUI pages in DoesSiteRequireDedicatedProcess helps
to keep enforcing a SiteInstance swap during chrome://foo ->
chrome://bar navigation, even after relaxing
BrowsingInstance::GetSiteInstanceForURL to consider RPH::IsSuitableHost
(see https://crrev.com/c/783470 for that fixes process sharing in
isolated(b(c),d(c)) scenario).
I've manually tested this CL by visiting the following URLs:
- chrome://welcome/
- chrome://settings
- chrome://extensions
- chrome://history
- chrome://help and chrome://chrome (both redirect to chrome://settings/help)
Bug: 510588, 847127
Change-Id: I55073bce00f32cb8bc5c1c91034438ff9a3f8971
Reviewed-on: https://chromium-review.googlesource.com/1237392
Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org>
Reviewed-by: François Doray <fdoray@chromium.org>
Reviewed-by: Nasko Oskov <nasko@chromium.org>
Reviewed-by: Avi Drissman <avi@chromium.org>
Cr-Commit-Position: refs/heads/master@{#595259}
CWE ID: CWE-119
|
bool SiteInstanceImpl::DoesSiteRequireDedicatedProcess(
BrowserContext* browser_context,
const GURL& url) {
if (SiteIsolationPolicy::UseDedicatedProcessesForAllSites())
return true;
// Always require a dedicated process for isolated origins.
GURL site_url = SiteInstance::GetSiteForURL(browser_context, url);
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
if (policy->IsIsolatedOrigin(url::Origin::Create(site_url)))
return true;
if (site_url.SchemeIs(kChromeErrorScheme))
return true;
// Isolate kChromeUIScheme pages from one another and from other kinds of
// schemes.
if (site_url.SchemeIs(content::kChromeUIScheme))
return true;
if (GetContentClient()->browser()->DoesSiteRequireDedicatedProcess(
browser_context, site_url)) {
return true;
}
return false;
}
| 173,281
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride)
{
nsc_encode_argb_to_aycocg(context, bmpdata, rowstride);
if (context->ChromaSubsamplingLevel)
{
nsc_encode_subsampling(context);
}
}
Commit Message: Fixed CVE-2018-8788
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-787
|
void nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride)
BOOL nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride)
{
if (!context || !bmpdata || (rowstride == 0))
return FALSE;
if (!nsc_encode_argb_to_aycocg(context, bmpdata, rowstride))
return FALSE;
if (context->ChromaSubsamplingLevel)
{
if (!nsc_encode_subsampling(context))
return FALSE;
}
return TRUE;
}
| 169,287
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: my_object_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
MyObject *mobject;
mobject = MY_OBJECT (object);
switch (prop_id)
{
case PROP_THIS_IS_A_STRING:
g_value_set_string (value, mobject->this_is_a_string);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
Commit Message:
CWE ID: CWE-264
|
my_object_get_property (GObject *object,
| 165,102
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftOpus::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch ((int)index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.opus",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAndroidOpus:
{
const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams =
(const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params;
if (opusParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftOpus::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch ((int)index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.opus",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAndroidOpus:
{
const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams =
(const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params;
if (!isValidOMXParam(opusParams)) {
return OMX_ErrorBadParameter;
}
if (opusParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,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: int tls1_setup_key_block(SSL *s)
{
unsigned char *p;
const EVP_CIPHER *c;
const EVP_MD *hash;
int num;
SSL_COMP *comp;
int mac_type = NID_undef, mac_secret_size = 0;
int ret = 0;
if (s->s3->tmp.key_block_length != 0)
return (1);
if (!ssl_cipher_get_evp
(s->session, &c, &hash, &mac_type, &mac_secret_size, &comp,
SSL_USE_ETM(s))) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
return (0);
}
s->s3->tmp.new_sym_enc = c;
s->s3->tmp.new_hash = hash;
s->s3->tmp.new_mac_pkey_type = mac_type;
s->s3->tmp.new_mac_secret_size = mac_secret_size;
num = EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c);
num *= 2;
ssl3_cleanup_key_block(s);
if ((p = OPENSSL_malloc(num)) == NULL) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
goto err;
}
s->s3->tmp.key_block_length = num;
s->s3->tmp.key_block = p;
#ifdef SSL_DEBUG
printf("client random\n");
{
int z;
for (z = 0; z < SSL3_RANDOM_SIZE; z++)
printf("%02X%c", s->s3->client_random[z],
((z + 1) % 16) ? ' ' : '\n');
}
printf("server random\n");
{
int z;
for (z = 0; z < SSL3_RANDOM_SIZE; z++)
printf("%02X%c", s->s3->server_random[z],
((z + 1) % 16) ? ' ' : '\n');
}
printf("master key\n");
{
int z;
for (z = 0; z < s->session->master_key_length; z++)
printf("%02X%c", s->session->master_key[z],
((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (!tls1_generate_key_block(s, p, num))
goto err;
#ifdef SSL_DEBUG
printf("\nkey block\n");
{
int z;
for (z = 0; z < num; z++)
printf("%02X%c", p[z], ((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
&& s->method->version <= TLS1_VERSION) {
/*
* enable vulnerability countermeasure for CBC ciphers with known-IV
* problem (http://www.openssl.org/~bodo/tls-cbc.txt)
*/
s->s3->need_empty_fragments = 1;
if (s->session->cipher != NULL) {
if (s->session->cipher->algorithm_enc == SSL_eNULL)
s->s3->need_empty_fragments = 0;
#ifndef OPENSSL_NO_RC4
if (s->session->cipher->algorithm_enc == SSL_RC4)
s->s3->need_empty_fragments = 0;
#endif
}
}
ret = 1;
err:
return (ret);
}
Commit Message: Don't change the state of the ETM flags until CCS processing
Changing the ciphersuite during a renegotiation can result in a crash
leading to a DoS attack. ETM has not been implemented in 1.1.0 for DTLS
so this is TLS only.
The problem is caused by changing the flag indicating whether to use ETM
or not immediately on negotiation of ETM, rather than at CCS. Therefore,
during a renegotiation, if the ETM state is changing (usually due to a
change of ciphersuite), then an error/crash will occur.
Due to the fact that there are separate CCS messages for read and write
we actually now need two flags to determine whether to use ETM or not.
CVE-2017-3733
Reviewed-by: Richard Levitte <levitte@openssl.org>
CWE ID: CWE-20
|
int tls1_setup_key_block(SSL *s)
{
unsigned char *p;
const EVP_CIPHER *c;
const EVP_MD *hash;
int num;
SSL_COMP *comp;
int mac_type = NID_undef, mac_secret_size = 0;
int ret = 0;
if (s->s3->tmp.key_block_length != 0)
return (1);
if (!ssl_cipher_get_evp(s->session, &c, &hash, &mac_type, &mac_secret_size,
&comp, s->tlsext_use_etm)) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
return (0);
}
s->s3->tmp.new_sym_enc = c;
s->s3->tmp.new_hash = hash;
s->s3->tmp.new_mac_pkey_type = mac_type;
s->s3->tmp.new_mac_secret_size = mac_secret_size;
num = EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c);
num *= 2;
ssl3_cleanup_key_block(s);
if ((p = OPENSSL_malloc(num)) == NULL) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
goto err;
}
s->s3->tmp.key_block_length = num;
s->s3->tmp.key_block = p;
#ifdef SSL_DEBUG
printf("client random\n");
{
int z;
for (z = 0; z < SSL3_RANDOM_SIZE; z++)
printf("%02X%c", s->s3->client_random[z],
((z + 1) % 16) ? ' ' : '\n');
}
printf("server random\n");
{
int z;
for (z = 0; z < SSL3_RANDOM_SIZE; z++)
printf("%02X%c", s->s3->server_random[z],
((z + 1) % 16) ? ' ' : '\n');
}
printf("master key\n");
{
int z;
for (z = 0; z < s->session->master_key_length; z++)
printf("%02X%c", s->session->master_key[z],
((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (!tls1_generate_key_block(s, p, num))
goto err;
#ifdef SSL_DEBUG
printf("\nkey block\n");
{
int z;
for (z = 0; z < num; z++)
printf("%02X%c", p[z], ((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
&& s->method->version <= TLS1_VERSION) {
/*
* enable vulnerability countermeasure for CBC ciphers with known-IV
* problem (http://www.openssl.org/~bodo/tls-cbc.txt)
*/
s->s3->need_empty_fragments = 1;
if (s->session->cipher != NULL) {
if (s->session->cipher->algorithm_enc == SSL_eNULL)
s->s3->need_empty_fragments = 0;
#ifndef OPENSSL_NO_RC4
if (s->session->cipher->algorithm_enc == SSL_RC4)
s->s3->need_empty_fragments = 0;
#endif
}
}
ret = 1;
err:
return (ret);
}
| 168,426
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void WritePixels(struct ngiflib_img * i, struct ngiflib_decode_context * context, const u8 * pixels, u16 n) {
u16 tocopy;
struct ngiflib_gif * p = i->parent;
while(n > 0) {
tocopy = (context->Xtogo < n) ? context->Xtogo : n;
if(!i->gce.transparent_flag) {
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
ngiflib_memcpy(context->frbuff_p.p8, pixels, tocopy);
pixels += tocopy;
context->frbuff_p.p8 += tocopy;
#ifndef NGIFLIB_INDEXED_ONLY
} else {
int j;
for(j = (int)tocopy; j > 0; j--) {
*(context->frbuff_p.p32++) =
GifIndexToTrueColor(i->palette, *pixels++);
}
}
#endif /* NGIFLIB_INDEXED_ONLY */
} else {
int j;
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
for(j = (int)tocopy; j > 0; j--) {
if(*pixels != i->gce.transparent_color) *context->frbuff_p.p8 = *pixels;
pixels++;
context->frbuff_p.p8++;
}
#ifndef NGIFLIB_INDEXED_ONLY
} else {
for(j = (int)tocopy; j > 0; j--) {
if(*pixels != i->gce.transparent_color) {
*context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, *pixels);
}
pixels++;
context->frbuff_p.p32++;
}
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
context->Xtogo -= tocopy;
if(context->Xtogo == 0) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(p->line_cb) p->line_cb(p, context->line_p, context->curY);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
context->Xtogo = i->width;
switch(context->pass) {
case 0:
context->curY++;
break;
case 1: /* 1st pass : every eighth row starting from 0 */
context->curY += 8;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 4;
}
break;
case 2: /* 2nd pass : every eighth row starting from 4 */
context->curY += 8;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 2;
}
break;
case 3: /* 3rd pass : every fourth row starting from 2 */
context->curY += 4;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 1;
}
break;
case 4: /* 4th pass : every odd row */
context->curY += 2;
break;
}
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width;
context->frbuff_p.p8 = context->line_p.p8 + i->posX;
#else
context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#ifndef NGIFLIB_INDEXED_ONLY
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width;
context->frbuff_p.p32 = context->line_p.p32 + i->posX;
#else
context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
n -= tocopy;
}
}
Commit Message: fix deinterlacing for small pictures
fixes #12
CWE ID: CWE-119
|
static void WritePixels(struct ngiflib_img * i, struct ngiflib_decode_context * context, const u8 * pixels, u16 n) {
u16 tocopy;
struct ngiflib_gif * p = i->parent;
while(n > 0) {
tocopy = (context->Xtogo < n) ? context->Xtogo : n;
if(!i->gce.transparent_flag) {
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
ngiflib_memcpy(context->frbuff_p.p8, pixels, tocopy);
pixels += tocopy;
context->frbuff_p.p8 += tocopy;
#ifndef NGIFLIB_INDEXED_ONLY
} else {
int j;
for(j = (int)tocopy; j > 0; j--) {
*(context->frbuff_p.p32++) =
GifIndexToTrueColor(i->palette, *pixels++);
}
}
#endif /* NGIFLIB_INDEXED_ONLY */
} else {
int j;
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
for(j = (int)tocopy; j > 0; j--) {
if(*pixels != i->gce.transparent_color) *context->frbuff_p.p8 = *pixels;
pixels++;
context->frbuff_p.p8++;
}
#ifndef NGIFLIB_INDEXED_ONLY
} else {
for(j = (int)tocopy; j > 0; j--) {
if(*pixels != i->gce.transparent_color) {
*context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, *pixels);
}
pixels++;
context->frbuff_p.p32++;
}
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
context->Xtogo -= tocopy;
if(context->Xtogo == 0) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(p->line_cb) p->line_cb(p, context->line_p, context->curY);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
context->Xtogo = i->width;
switch(context->pass) {
case 0:
context->curY++;
break;
case 1: /* 1st pass : every eighth row starting from 0 */
context->curY += 8;
break;
case 2: /* 2nd pass : every eighth row starting from 4 */
context->curY += 8;
break;
case 3: /* 3rd pass : every fourth row starting from 2 */
context->curY += 4;
break;
case 4: /* 4th pass : every odd row */
context->curY += 2;
break;
}
while(context->pass > 0 && context->pass < 4 &&
context->curY >= p->height) {
switch(++context->pass) {
case 2: /* 2nd pass : every eighth row starting from 4 */
context->curY = i->posY + 4;
break;
case 3: /* 3rd pass : every fourth row starting from 2 */
context->curY = i->posY + 2;
break;
case 4: /* 4th pass : every odd row */
context->curY = i->posY + 1;
break;
}
}
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width;
context->frbuff_p.p8 = context->line_p.p8 + i->posX;
#else
context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#ifndef NGIFLIB_INDEXED_ONLY
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width;
context->frbuff_p.p32 = context->line_p.p32 + i->posX;
#else
context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
n -= tocopy;
}
}
| 169,512
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BrowserTabStripController::TabDetachedAt(TabContents* contents,
int model_index) {
hover_tab_selector_.CancelTabTransition();
tabstrip_->RemoveTabAt(model_index);
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void BrowserTabStripController::TabDetachedAt(TabContents* contents,
void BrowserTabStripController::TabDetachedAt(WebContents* contents,
int model_index) {
hover_tab_selector_.CancelTabTransition();
tabstrip_->RemoveTabAt(model_index);
}
| 171,523
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static ssize_t exitcode_proc_write(struct file *file,
const char __user *buffer, size_t count, loff_t *pos)
{
char *end, buf[sizeof("nnnnn\0")];
int tmp;
if (copy_from_user(buf, buffer, count))
return -EFAULT;
tmp = simple_strtol(buf, &end, 0);
if ((*end != '\0') && !isspace(*end))
return -EINVAL;
uml_exitcode = tmp;
return count;
}
Commit Message: uml: check length in exitcode_proc_write()
We don't cap the size of buffer from the user so we could write past the
end of the array here. Only root can write to this file.
Reported-by: Nico Golde <nico@ngolde.de>
Reported-by: Fabian Yamaguchi <fabs@goesec.de>
Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com>
Cc: stable@kernel.org
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-119
|
static ssize_t exitcode_proc_write(struct file *file,
const char __user *buffer, size_t count, loff_t *pos)
{
char *end, buf[sizeof("nnnnn\0")];
size_t size;
int tmp;
size = min(count, sizeof(buf));
if (copy_from_user(buf, buffer, size))
return -EFAULT;
tmp = simple_strtol(buf, &end, 0);
if ((*end != '\0') && !isspace(*end))
return -EINVAL;
uml_exitcode = tmp;
return count;
}
| 165,966
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int send_event (int fd, uint16_t type, uint16_t code, int32_t value)
{
struct uinput_event event;
BTIF_TRACE_DEBUG("%s type:%u code:%u value:%d", __FUNCTION__,
type, code, value);
memset(&event, 0, sizeof(event));
event.type = type;
event.code = code;
event.value = value;
return write(fd, &event, sizeof(event));
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
int send_event (int fd, uint16_t type, uint16_t code, int32_t value)
{
struct uinput_event event;
BTIF_TRACE_DEBUG("%s type:%u code:%u value:%d", __FUNCTION__,
type, code, value);
memset(&event, 0, sizeof(event));
event.type = type;
event.code = code;
event.value = value;
return TEMP_FAILURE_RETRY(write(fd, &event, sizeof(event)));
}
| 173,451
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: MagickExport void CatchException(ExceptionInfo *exception)
{
register const ExceptionInfo
*p;
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if (exception->exceptions == (void *) NULL)
return;
LockSemaphoreInfo(exception->semaphore);
ResetLinkedListIterator((LinkedListInfo *) exception->exceptions);
p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *)
exception->exceptions);
while (p != (const ExceptionInfo *) NULL)
{
if ((p->severity >= WarningException) && (p->severity < ErrorException))
MagickWarning(p->severity,p->reason,p->description);
if ((p->severity >= ErrorException) && (p->severity < FatalErrorException))
MagickError(p->severity,p->reason,p->description);
if (p->severity >= FatalErrorException)
MagickFatalError(p->severity,p->reason,p->description);
p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *)
exception->exceptions);
}
UnlockSemaphoreInfo(exception->semaphore);
ClearMagickException(exception);
}
Commit Message: Suspend exception processing if there are too many exceptions
CWE ID: CWE-119
|
MagickExport void CatchException(ExceptionInfo *exception)
{
register const ExceptionInfo
*p;
ssize_t
i;
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if (exception->exceptions == (void *) NULL)
return;
LockSemaphoreInfo(exception->semaphore);
ResetLinkedListIterator((LinkedListInfo *) exception->exceptions);
p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *)
exception->exceptions);
for (i=0; p != (const ExceptionInfo *) NULL; i++)
{
if (p->severity >= FatalErrorException)
MagickFatalError(p->severity,p->reason,p->description);
if (i < MaxExceptions)
{
if ((p->severity >= ErrorException) &&
(p->severity < FatalErrorException))
MagickError(p->severity,p->reason,p->description);
if ((p->severity >= WarningException) && (p->severity < ErrorException))
MagickWarning(p->severity,p->reason,p->description);
}
else
if (i == MaxExceptions)
MagickError(ResourceLimitError,"too many exceptions",
"exception processing suspended");
p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *)
exception->exceptions);
}
UnlockSemaphoreInfo(exception->semaphore);
ClearMagickException(exception);
}
| 168,541
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SyncType GetSyncType(const Extension* extension) {
if (!IsSyncable(extension)) {
return SYNC_TYPE_NONE;
}
if (!ManifestURL::GetUpdateURL(extension).is_empty() &&
!ManifestURL::UpdatesFromGallery(extension)) {
return SYNC_TYPE_NONE;
}
if (PluginInfo::HasPlugins(extension))
return SYNC_TYPE_NONE;
switch (extension->GetType()) {
case Manifest::TYPE_EXTENSION:
return SYNC_TYPE_EXTENSION;
case Manifest::TYPE_USER_SCRIPT:
if (ManifestURL::UpdatesFromGallery(extension))
return SYNC_TYPE_EXTENSION;
return SYNC_TYPE_NONE;
case Manifest::TYPE_HOSTED_APP:
case Manifest::TYPE_LEGACY_PACKAGED_APP:
case Manifest::TYPE_PLATFORM_APP:
return SYNC_TYPE_APP;
case Manifest::TYPE_UNKNOWN:
case Manifest::TYPE_THEME:
case Manifest::TYPE_SHARED_MODULE:
return SYNC_TYPE_NONE;
}
NOTREACHED();
return SYNC_TYPE_NONE;
}
Commit Message: Fix syncing of NPAPI plugins.
This fix adds a check for |plugin| permission
while syncing NPAPI plugins.
BUG=252034
Review URL: https://chromiumcodereview.appspot.com/16816024
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207830 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
SyncType GetSyncType(const Extension* extension) {
if (!IsSyncable(extension)) {
return SYNC_TYPE_NONE;
}
if (!ManifestURL::GetUpdateURL(extension).is_empty() &&
!ManifestURL::UpdatesFromGallery(extension)) {
return SYNC_TYPE_NONE;
}
if (PluginInfo::HasPlugins(extension) ||
extension->HasAPIPermission(APIPermission::kPlugin)) {
return SYNC_TYPE_NONE;
}
switch (extension->GetType()) {
case Manifest::TYPE_EXTENSION:
return SYNC_TYPE_EXTENSION;
case Manifest::TYPE_USER_SCRIPT:
if (ManifestURL::UpdatesFromGallery(extension))
return SYNC_TYPE_EXTENSION;
return SYNC_TYPE_NONE;
case Manifest::TYPE_HOSTED_APP:
case Manifest::TYPE_LEGACY_PACKAGED_APP:
case Manifest::TYPE_PLATFORM_APP:
return SYNC_TYPE_APP;
case Manifest::TYPE_UNKNOWN:
case Manifest::TYPE_THEME:
case Manifest::TYPE_SHARED_MODULE:
return SYNC_TYPE_NONE;
}
NOTREACHED();
return SYNC_TYPE_NONE;
}
| 171,248
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg,
X509_ALGOR **pmaskHash)
{
const unsigned char *p;
int plen;
RSA_PSS_PARAMS *pss;
*pmaskHash = NULL;
if (!alg->parameter || alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
pss = d2i_RSA_PSS_PARAMS(NULL, &p, plen);
if (!pss)
return NULL;
if (pss->maskGenAlgorithm) {
ASN1_TYPE *param = pss->maskGenAlgorithm->parameter;
if (OBJ_obj2nid(pss->maskGenAlgorithm->algorithm) == NID_mgf1
&& param->type == V_ASN1_SEQUENCE) {
p = param->value.sequence->data;
plen = param->value.sequence->length;
*pmaskHash = d2i_X509_ALGOR(NULL, &p, plen);
}
}
return pss;
}
Commit Message:
CWE ID:
|
static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg,
X509_ALGOR **pmaskHash)
{
const unsigned char *p;
int plen;
RSA_PSS_PARAMS *pss;
*pmaskHash = NULL;
if (!alg->parameter || alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
pss = d2i_RSA_PSS_PARAMS(NULL, &p, plen);
if (!pss)
return NULL;
if (pss->maskGenAlgorithm) {
ASN1_TYPE *param = pss->maskGenAlgorithm->parameter;
if (OBJ_obj2nid(pss->maskGenAlgorithm->algorithm) == NID_mgf1
&& param && param->type == V_ASN1_SEQUENCE) {
p = param->value.sequence->data;
plen = param->value.sequence->length;
*pmaskHash = d2i_X509_ALGOR(NULL, &p, plen);
}
}
return pss;
}
| 164,719
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mkvparser::UnserializeFloat(IMkvReader* pReader, long long pos,
long long size_, double& result) {
assert(pReader);
assert(pos >= 0);
if ((size_ != 4) && (size_ != 8))
return E_FILE_FORMAT_INVALID;
const long size = static_cast<long>(size_);
unsigned char buf[8];
const int status = pReader->Read(pos, size, buf);
if (status < 0) // error
return status;
if (size == 4) {
union {
float f;
unsigned long ff;
};
ff = 0;
for (int i = 0;;) {
ff |= buf[i];
if (++i >= 4)
break;
ff <<= 8;
}
result = f;
} else {
assert(size == 8);
union {
double d;
unsigned long long dd;
};
dd = 0;
for (int i = 0;;) {
dd |= buf[i];
if (++i >= 8)
break;
dd <<= 8;
}
result = d;
}
return 0;
}
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 mkvparser::UnserializeFloat(IMkvReader* pReader, long long pos,
long UnserializeFloat(IMkvReader* pReader, long long pos, long long size_,
double& result) {
if (!pReader || pos < 0 || ((size_ != 4) && (size_ != 8)))
return E_FILE_FORMAT_INVALID;
const long size = static_cast<long>(size_);
unsigned char buf[8];
const int status = pReader->Read(pos, size, buf);
if (status < 0) // error
return status;
if (size == 4) {
union {
float f;
unsigned long ff;
};
ff = 0;
for (int i = 0;;) {
ff |= buf[i];
if (++i >= 4)
break;
ff <<= 8;
}
result = f;
} else {
union {
double d;
unsigned long long dd;
};
dd = 0;
for (int i = 0;;) {
dd |= buf[i];
if (++i >= 8)
break;
dd <<= 8;
}
result = d;
}
if (std::isinf(result) || std::isnan(result))
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,865
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: GF_Err hdlr_dump(GF_Box *a, FILE * trace)
{
GF_HandlerBox *p = (GF_HandlerBox *)a;
gf_isom_box_dump_start(a, "HandlerBox", trace);
if (p->nameUTF8 && (u32) p->nameUTF8[0] == strlen(p->nameUTF8+1)) {
fprintf(trace, "hdlrType=\"%s\" Name=\"%s\" ", gf_4cc_to_str(p->handlerType), p->nameUTF8+1);
} else {
fprintf(trace, "hdlrType=\"%s\" Name=\"%s\" ", gf_4cc_to_str(p->handlerType), p->nameUTF8);
}
fprintf(trace, "reserved1=\"%d\" reserved2=\"", p->reserved1);
dump_data(trace, (char *) p->reserved2, 12);
fprintf(trace, "\"");
fprintf(trace, ">\n");
gf_isom_box_dump_done("HandlerBox", a, trace);
return GF_OK;
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125
|
GF_Err hdlr_dump(GF_Box *a, FILE * trace)
{
GF_HandlerBox *p = (GF_HandlerBox *)a;
gf_isom_box_dump_start(a, "HandlerBox", trace);
if (p->nameUTF8 && (u32) p->nameUTF8[0] == strlen(p->nameUTF8)-1) {
fprintf(trace, "hdlrType=\"%s\" Name=\"%s\" ", gf_4cc_to_str(p->handlerType), p->nameUTF8+1);
} else {
fprintf(trace, "hdlrType=\"%s\" Name=\"%s\" ", gf_4cc_to_str(p->handlerType), p->nameUTF8);
}
fprintf(trace, "reserved1=\"%d\" reserved2=\"", p->reserved1);
dump_data(trace, (char *) p->reserved2, 12);
fprintf(trace, "\"");
fprintf(trace, ">\n");
gf_isom_box_dump_done("HandlerBox", a, trace);
return GF_OK;
}
| 169,168
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: HistogramBase* Histogram::Factory::Build() {
HistogramBase* histogram = StatisticsRecorder::FindHistogram(name_);
if (!histogram) {
const BucketRanges* created_ranges = CreateRanges();
const BucketRanges* registered_ranges =
StatisticsRecorder::RegisterOrDeleteDuplicateRanges(created_ranges);
if (bucket_count_ == 0) {
bucket_count_ = static_cast<uint32_t>(registered_ranges->bucket_count());
minimum_ = registered_ranges->range(1);
maximum_ = registered_ranges->range(bucket_count_ - 1);
}
PersistentHistogramAllocator::Reference histogram_ref = 0;
std::unique_ptr<HistogramBase> tentative_histogram;
PersistentHistogramAllocator* allocator = GlobalHistogramAllocator::Get();
if (allocator) {
tentative_histogram = allocator->AllocateHistogram(
histogram_type_,
name_,
minimum_,
maximum_,
registered_ranges,
flags_,
&histogram_ref);
}
if (!tentative_histogram) {
DCHECK(!histogram_ref); // Should never have been set.
DCHECK(!allocator); // Shouldn't have failed.
flags_ &= ~HistogramBase::kIsPersistent;
tentative_histogram = HeapAlloc(registered_ranges);
tentative_histogram->SetFlags(flags_);
}
FillHistogram(tentative_histogram.get());
const void* tentative_histogram_ptr = tentative_histogram.get();
histogram = StatisticsRecorder::RegisterOrDeleteDuplicate(
tentative_histogram.release());
if (histogram_ref) {
allocator->FinalizeHistogram(histogram_ref,
histogram == tentative_histogram_ptr);
}
ReportHistogramActivity(*histogram, HISTOGRAM_CREATED);
} else {
ReportHistogramActivity(*histogram, HISTOGRAM_LOOKUP);
}
DCHECK_EQ(histogram_type_, histogram->GetHistogramType()) << name_;
if (bucket_count_ != 0 &&
!histogram->HasConstructionArguments(minimum_, maximum_, bucket_count_)) {
DLOG(ERROR) << "Histogram " << name_ << " has bad construction arguments";
return nullptr;
}
return histogram;
}
Commit Message: Convert DCHECKs to CHECKs for histogram types
When a histogram is looked up by name, there is currently a DCHECK that
verifies the type of the stored histogram matches the expected type.
A mismatch represents a significant problem because the returned
HistogramBase is cast to a Histogram in ValidateRangeChecksum,
potentially causing a crash.
This CL converts the DCHECK to a CHECK to prevent the possibility of
type confusion in release builds.
BUG=651443
R=isherman@chromium.org
Review-Url: https://codereview.chromium.org/2381893003
Cr-Commit-Position: refs/heads/master@{#421929}
CWE ID: CWE-476
|
HistogramBase* Histogram::Factory::Build() {
HistogramBase* histogram = StatisticsRecorder::FindHistogram(name_);
if (!histogram) {
const BucketRanges* created_ranges = CreateRanges();
const BucketRanges* registered_ranges =
StatisticsRecorder::RegisterOrDeleteDuplicateRanges(created_ranges);
if (bucket_count_ == 0) {
bucket_count_ = static_cast<uint32_t>(registered_ranges->bucket_count());
minimum_ = registered_ranges->range(1);
maximum_ = registered_ranges->range(bucket_count_ - 1);
}
PersistentHistogramAllocator::Reference histogram_ref = 0;
std::unique_ptr<HistogramBase> tentative_histogram;
PersistentHistogramAllocator* allocator = GlobalHistogramAllocator::Get();
if (allocator) {
tentative_histogram = allocator->AllocateHistogram(
histogram_type_,
name_,
minimum_,
maximum_,
registered_ranges,
flags_,
&histogram_ref);
}
if (!tentative_histogram) {
DCHECK(!histogram_ref); // Should never have been set.
DCHECK(!allocator); // Shouldn't have failed.
flags_ &= ~HistogramBase::kIsPersistent;
tentative_histogram = HeapAlloc(registered_ranges);
tentative_histogram->SetFlags(flags_);
}
FillHistogram(tentative_histogram.get());
const void* tentative_histogram_ptr = tentative_histogram.get();
histogram = StatisticsRecorder::RegisterOrDeleteDuplicate(
tentative_histogram.release());
if (histogram_ref) {
allocator->FinalizeHistogram(histogram_ref,
histogram == tentative_histogram_ptr);
}
ReportHistogramActivity(*histogram, HISTOGRAM_CREATED);
} else {
ReportHistogramActivity(*histogram, HISTOGRAM_LOOKUP);
}
CHECK_EQ(histogram_type_, histogram->GetHistogramType()) << name_;
if (bucket_count_ != 0 &&
!histogram->HasConstructionArguments(minimum_, maximum_, bucket_count_)) {
DLOG(ERROR) << "Histogram " << name_ << " has bad construction arguments";
return nullptr;
}
return histogram;
}
| 172,493
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 filter_block2d_8_c(const uint8_t *src_ptr,
const unsigned int src_stride,
const int16_t *HFilter,
const int16_t *VFilter,
uint8_t *dst_ptr,
unsigned int dst_stride,
unsigned int output_width,
unsigned int output_height) {
const int kInterp_Extend = 4;
const unsigned int intermediate_height =
(kInterp_Extend - 1) + output_height + kInterp_Extend;
/* Size of intermediate_buffer is max_intermediate_height * filter_max_width,
* where max_intermediate_height = (kInterp_Extend - 1) + filter_max_height
* + kInterp_Extend
* = 3 + 16 + 4
* = 23
* and filter_max_width = 16
*/
uint8_t intermediate_buffer[71 * 64];
const int intermediate_next_stride = 1 - intermediate_height * output_width;
{
uint8_t *output_ptr = intermediate_buffer;
const int src_next_row_stride = src_stride - output_width;
unsigned int i, j;
src_ptr -= (kInterp_Extend - 1) * src_stride + (kInterp_Extend - 1);
for (i = 0; i < intermediate_height; ++i) {
for (j = 0; j < output_width; ++j) {
const int temp = (src_ptr[0] * HFilter[0]) +
(src_ptr[1] * HFilter[1]) +
(src_ptr[2] * HFilter[2]) +
(src_ptr[3] * HFilter[3]) +
(src_ptr[4] * HFilter[4]) +
(src_ptr[5] * HFilter[5]) +
(src_ptr[6] * HFilter[6]) +
(src_ptr[7] * HFilter[7]) +
(VP9_FILTER_WEIGHT >> 1); // Rounding
*output_ptr = clip_pixel(temp >> VP9_FILTER_SHIFT);
++src_ptr;
output_ptr += intermediate_height;
}
src_ptr += src_next_row_stride;
output_ptr += intermediate_next_stride;
}
}
{
uint8_t *src_ptr = intermediate_buffer;
const int dst_next_row_stride = dst_stride - output_width;
unsigned int i, j;
for (i = 0; i < output_height; ++i) {
for (j = 0; j < output_width; ++j) {
const int temp = (src_ptr[0] * VFilter[0]) +
(src_ptr[1] * VFilter[1]) +
(src_ptr[2] * VFilter[2]) +
(src_ptr[3] * VFilter[3]) +
(src_ptr[4] * VFilter[4]) +
(src_ptr[5] * VFilter[5]) +
(src_ptr[6] * VFilter[6]) +
(src_ptr[7] * VFilter[7]) +
(VP9_FILTER_WEIGHT >> 1); // Rounding
*dst_ptr++ = clip_pixel(temp >> VP9_FILTER_SHIFT);
src_ptr += intermediate_height;
}
src_ptr += intermediate_next_stride;
dst_ptr += dst_next_row_stride;
}
}
}
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 filter_block2d_8_c(const uint8_t *src_ptr,
const unsigned int src_stride,
const int16_t *HFilter,
const int16_t *VFilter,
uint8_t *dst_ptr,
unsigned int dst_stride,
unsigned int output_width,
unsigned int output_height) {
const int kInterp_Extend = 4;
const unsigned int intermediate_height =
(kInterp_Extend - 1) + output_height + kInterp_Extend;
unsigned int i, j;
// Size of intermediate_buffer is max_intermediate_height * filter_max_width,
// where max_intermediate_height = (kInterp_Extend - 1) + filter_max_height
// + kInterp_Extend
// = 3 + 16 + 4
// = 23
// and filter_max_width = 16
//
uint8_t intermediate_buffer[71 * kMaxDimension];
const int intermediate_next_stride = 1 - intermediate_height * output_width;
uint8_t *output_ptr = intermediate_buffer;
const int src_next_row_stride = src_stride - output_width;
src_ptr -= (kInterp_Extend - 1) * src_stride + (kInterp_Extend - 1);
for (i = 0; i < intermediate_height; ++i) {
for (j = 0; j < output_width; ++j) {
// Apply filter...
const int temp = (src_ptr[0] * HFilter[0]) +
(src_ptr[1] * HFilter[1]) +
(src_ptr[2] * HFilter[2]) +
(src_ptr[3] * HFilter[3]) +
(src_ptr[4] * HFilter[4]) +
(src_ptr[5] * HFilter[5]) +
(src_ptr[6] * HFilter[6]) +
(src_ptr[7] * HFilter[7]) +
(VP9_FILTER_WEIGHT >> 1); // Rounding
// Normalize back to 0-255...
*output_ptr = clip_pixel(temp >> VP9_FILTER_SHIFT);
++src_ptr;
output_ptr += intermediate_height;
}
src_ptr += src_next_row_stride;
output_ptr += intermediate_next_stride;
}
src_ptr = intermediate_buffer;
const int dst_next_row_stride = dst_stride - output_width;
for (i = 0; i < output_height; ++i) {
for (j = 0; j < output_width; ++j) {
// Apply filter...
const int temp = (src_ptr[0] * VFilter[0]) +
(src_ptr[1] * VFilter[1]) +
(src_ptr[2] * VFilter[2]) +
(src_ptr[3] * VFilter[3]) +
(src_ptr[4] * VFilter[4]) +
(src_ptr[5] * VFilter[5]) +
(src_ptr[6] * VFilter[6]) +
(src_ptr[7] * VFilter[7]) +
(VP9_FILTER_WEIGHT >> 1); // Rounding
// Normalize back to 0-255...
*dst_ptr++ = clip_pixel(temp >> VP9_FILTER_SHIFT);
src_ptr += intermediate_height;
}
src_ptr += intermediate_next_stride;
dst_ptr += dst_next_row_stride;
}
}
| 174,509
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: xmlParseCommentComplex(xmlParserCtxtPtr ctxt, xmlChar *buf, int len, int size) {
int q, ql;
int r, rl;
int cur, l;
int count = 0;
int inputid;
inputid = ctxt->input->id;
if (buf == NULL) {
len = 0;
size = XML_PARSER_BUFFER_SIZE;
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return;
}
}
GROW; /* Assure there's enough input data */
q = CUR_CHAR(ql);
if (q == 0)
goto not_terminated;
if (!IS_CHAR(q)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlParseComment: invalid xmlChar value %d\n",
q);
xmlFree (buf);
return;
}
NEXTL(ql);
r = CUR_CHAR(rl);
if (r == 0)
goto not_terminated;
if (!IS_CHAR(r)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlParseComment: invalid xmlChar value %d\n",
q);
xmlFree (buf);
return;
}
NEXTL(rl);
cur = CUR_CHAR(l);
if (cur == 0)
goto not_terminated;
while (IS_CHAR(cur) && /* checked */
((cur != '>') ||
(r != '-') || (q != '-'))) {
if ((r == '-') && (q == '-')) {
xmlFatalErr(ctxt, XML_ERR_HYPHEN_IN_COMMENT, NULL);
}
if (len + 5 >= size) {
xmlChar *new_buf;
size *= 2;
new_buf = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (new_buf == NULL) {
xmlFree (buf);
xmlErrMemory(ctxt, NULL);
return;
}
buf = new_buf;
}
COPY_BUF(ql,buf,len,q);
q = r;
ql = rl;
r = cur;
rl = l;
count++;
if (count > 50) {
GROW;
count = 0;
}
NEXTL(l);
cur = CUR_CHAR(l);
if (cur == 0) {
SHRINK;
GROW;
cur = CUR_CHAR(l);
}
}
buf[len] = 0;
if (cur == 0) {
xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment not terminated \n<!--%.50s\n", buf);
} else if (!IS_CHAR(cur)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlParseComment: invalid xmlChar value %d\n",
cur);
} else {
if (inputid != ctxt->input->id) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Comment doesn't start and stop in the same entity\n");
}
NEXT;
if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->comment(ctxt->userData, buf);
}
xmlFree(buf);
return;
not_terminated:
xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment not terminated\n", NULL);
xmlFree(buf);
return;
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
xmlParseCommentComplex(xmlParserCtxtPtr ctxt, xmlChar *buf, int len, int size) {
int q, ql;
int r, rl;
int cur, l;
int count = 0;
int inputid;
inputid = ctxt->input->id;
if (buf == NULL) {
len = 0;
size = XML_PARSER_BUFFER_SIZE;
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return;
}
}
GROW; /* Assure there's enough input data */
q = CUR_CHAR(ql);
if (q == 0)
goto not_terminated;
if (!IS_CHAR(q)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlParseComment: invalid xmlChar value %d\n",
q);
xmlFree (buf);
return;
}
NEXTL(ql);
r = CUR_CHAR(rl);
if (r == 0)
goto not_terminated;
if (!IS_CHAR(r)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlParseComment: invalid xmlChar value %d\n",
q);
xmlFree (buf);
return;
}
NEXTL(rl);
cur = CUR_CHAR(l);
if (cur == 0)
goto not_terminated;
while (IS_CHAR(cur) && /* checked */
((cur != '>') ||
(r != '-') || (q != '-'))) {
if ((r == '-') && (q == '-')) {
xmlFatalErr(ctxt, XML_ERR_HYPHEN_IN_COMMENT, NULL);
}
if (len + 5 >= size) {
xmlChar *new_buf;
size *= 2;
new_buf = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (new_buf == NULL) {
xmlFree (buf);
xmlErrMemory(ctxt, NULL);
return;
}
buf = new_buf;
}
COPY_BUF(ql,buf,len,q);
q = r;
ql = rl;
r = cur;
rl = l;
count++;
if (count > 50) {
GROW;
count = 0;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return;
}
}
NEXTL(l);
cur = CUR_CHAR(l);
if (cur == 0) {
SHRINK;
GROW;
cur = CUR_CHAR(l);
}
}
buf[len] = 0;
if (cur == 0) {
xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment not terminated \n<!--%.50s\n", buf);
} else if (!IS_CHAR(cur)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlParseComment: invalid xmlChar value %d\n",
cur);
} else {
if (inputid != ctxt->input->id) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Comment doesn't start and stop in the same entity\n");
}
NEXT;
if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->comment(ctxt->userData, buf);
}
xmlFree(buf);
return;
not_terminated:
xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment not terminated\n", NULL);
xmlFree(buf);
return;
}
| 171,279
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: status_t OMXNodeInstance::emptyBuffer(
OMX::buffer_id buffer,
OMX_U32 rangeOffset, OMX_U32 rangeLength,
OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) {
Mutex::Autolock autoLock(mLock);
if (getGraphicBufferSource() != NULL) {
android_errorWriteLog(0x534e4554, "29422020");
return INVALID_OPERATION;
}
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput);
if (header == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
BufferMeta *buffer_meta =
static_cast<BufferMeta *>(header->pAppPrivate);
sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */);
sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */);
if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource
&& backup->capacity() >= sizeof(VideoNativeMetadata)
&& codec->capacity() >= sizeof(VideoGrallocMetadata)
&& ((VideoNativeMetadata *)backup->base())->eType
== kMetadataBufferTypeANWBuffer) {
VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base();
VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base();
CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p",
backupMeta.pBuffer, backupMeta.pBuffer->handle);
codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL;
codecMeta.eType = kMetadataBufferTypeGrallocSource;
header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0;
header->nOffset = 0;
} else {
if (rangeOffset > header->nAllocLen
|| rangeLength > header->nAllocLen - rangeOffset) {
CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd));
if (fenceFd >= 0) {
::close(fenceFd);
}
return BAD_VALUE;
}
header->nFilledLen = rangeLength;
header->nOffset = rangeOffset;
buffer_meta->CopyToOMX(header);
}
return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd);
}
Commit Message: IOMX: do not convert ANWB to gralloc source in emptyBuffer
Bug: 29422020
Bug: 31412859
Change-Id: If48e3e0b6f1af99a459fdc3f6f03744bbf0dc375
(cherry picked from commit 534bb6132a6a664f90b42b3ef81298b42efb3dc2)
CWE ID: CWE-200
|
status_t OMXNodeInstance::emptyBuffer(
OMX::buffer_id buffer,
OMX_U32 rangeOffset, OMX_U32 rangeLength,
OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) {
Mutex::Autolock autoLock(mLock);
if (getGraphicBufferSource() != NULL) {
android_errorWriteLog(0x534e4554, "29422020");
return INVALID_OPERATION;
}
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput);
if (header == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
BufferMeta *buffer_meta =
static_cast<BufferMeta *>(header->pAppPrivate);
// set up proper filled length if component is configured for gralloc metadata mode
// ignore rangeOffset in this case (as client may be assuming ANW meta buffers).
if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource) {
header->nFilledLen = rangeLength ? sizeof(VideoGrallocMetadata) : 0;
header->nOffset = 0;
} else {
if (rangeOffset > header->nAllocLen
|| rangeLength > header->nAllocLen - rangeOffset) {
CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd));
if (fenceFd >= 0) {
::close(fenceFd);
}
return BAD_VALUE;
}
header->nFilledLen = rangeLength;
header->nOffset = rangeOffset;
buffer_meta->CopyToOMX(header);
}
return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd);
}
| 174,145
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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: WebNotificationData ToWebNotificationData(
const PlatformNotificationData& platform_data) {
WebNotificationData web_data;
web_data.title = platform_data.title;
switch (platform_data.direction) {
case PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT:
web_data.direction = WebNotificationData::DirectionLeftToRight;
break;
case PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT:
web_data.direction = WebNotificationData::DirectionRightToLeft;
break;
case PlatformNotificationData::DIRECTION_AUTO:
web_data.direction = WebNotificationData::DirectionAuto;
break;
}
web_data.lang = blink::WebString::fromUTF8(platform_data.lang);
web_data.body = platform_data.body;
web_data.tag = blink::WebString::fromUTF8(platform_data.tag);
web_data.icon = blink::WebURL(platform_data.icon);
web_data.vibrate = platform_data.vibration_pattern;
web_data.timestamp = platform_data.timestamp.ToJsTime();
web_data.silent = platform_data.silent;
web_data.requireInteraction = platform_data.require_interaction;
web_data.data = platform_data.data;
blink::WebVector<blink::WebNotificationAction> resized(
platform_data.actions.size());
web_data.actions.swap(resized);
for (size_t i = 0; i < platform_data.actions.size(); ++i) {
web_data.actions[i].action =
blink::WebString::fromUTF8(platform_data.actions[i].action);
web_data.actions[i].title = platform_data.actions[i].title;
}
return web_data;
}
Commit Message: Notification actions may have an icon url.
This is behind a runtime flag for two reasons:
* The implementation is incomplete.
* We're still evaluating the API design.
Intent to Implement and Ship: Notification Action Icons
https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ
BUG=581336
Review URL: https://codereview.chromium.org/1644573002
Cr-Commit-Position: refs/heads/master@{#374649}
CWE ID:
|
WebNotificationData ToWebNotificationData(
const PlatformNotificationData& platform_data) {
WebNotificationData web_data;
web_data.title = platform_data.title;
switch (platform_data.direction) {
case PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT:
web_data.direction = WebNotificationData::DirectionLeftToRight;
break;
case PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT:
web_data.direction = WebNotificationData::DirectionRightToLeft;
break;
case PlatformNotificationData::DIRECTION_AUTO:
web_data.direction = WebNotificationData::DirectionAuto;
break;
}
web_data.lang = blink::WebString::fromUTF8(platform_data.lang);
web_data.body = platform_data.body;
web_data.tag = blink::WebString::fromUTF8(platform_data.tag);
web_data.icon = blink::WebURL(platform_data.icon);
web_data.vibrate = platform_data.vibration_pattern;
web_data.timestamp = platform_data.timestamp.ToJsTime();
web_data.silent = platform_data.silent;
web_data.requireInteraction = platform_data.require_interaction;
web_data.data = platform_data.data;
blink::WebVector<blink::WebNotificationAction> resized(
platform_data.actions.size());
web_data.actions.swap(resized);
for (size_t i = 0; i < platform_data.actions.size(); ++i) {
web_data.actions[i].action =
blink::WebString::fromUTF8(platform_data.actions[i].action);
web_data.actions[i].title = platform_data.actions[i].title;
web_data.actions[i].icon = blink::WebURL(platform_data.actions[i].icon);
}
return web_data;
}
| 171,632
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: dtls1_reassemble_fragment(SSL *s, struct hm_header_st* msg_hdr, int *ok)
{
hm_fragment *frag = NULL;
pitem *item = NULL;
int i = -1, is_complete;
unsigned char seq64be[8];
unsigned long frag_len = msg_hdr->frag_len, max_len;
if ((msg_hdr->frag_off+frag_len) > msg_hdr->msg_len)
goto err;
/* Determine maximum allowed message size. Depends on (user set)
* maximum certificate length, but 16k is minimum.
*/
if (DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH < s->max_cert_list)
max_len = s->max_cert_list;
else
max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
if ((msg_hdr->frag_off+frag_len) > max_len)
goto err;
/* Try to find item in queue */
memset(seq64be,0,sizeof(seq64be));
seq64be[6] = (unsigned char) (msg_hdr->seq>>8);
seq64be[7] = (unsigned char) msg_hdr->seq;
item = pqueue_find(s->d1->buffered_messages, seq64be);
if (item == NULL)
{
frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
if ( frag == NULL)
goto err;
memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
frag->msg_header.frag_len = frag->msg_header.msg_len;
frag->msg_header.frag_off = 0;
}
else
frag = (hm_fragment*) item->data;
/* If message is already reassembled, this must be a
* retransmit and can be dropped.
frag_len>sizeof(devnull)?sizeof(devnull):frag_len,0);
if (i<=0) goto err;
frag_len -= i;
}
Commit Message:
CWE ID: CWE-119
|
dtls1_reassemble_fragment(SSL *s, struct hm_header_st* msg_hdr, int *ok)
{
hm_fragment *frag = NULL;
pitem *item = NULL;
int i = -1, is_complete;
unsigned char seq64be[8];
unsigned long frag_len = msg_hdr->frag_len, max_len;
if ((msg_hdr->frag_off+frag_len) > msg_hdr->msg_len)
goto err;
/* Determine maximum allowed message size. Depends on (user set)
* maximum certificate length, but 16k is minimum.
*/
if (DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH < s->max_cert_list)
max_len = s->max_cert_list;
else
max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
if ((msg_hdr->frag_off+frag_len) > max_len)
goto err;
/* Try to find item in queue */
memset(seq64be,0,sizeof(seq64be));
seq64be[6] = (unsigned char) (msg_hdr->seq>>8);
seq64be[7] = (unsigned char) msg_hdr->seq;
item = pqueue_find(s->d1->buffered_messages, seq64be);
if (item == NULL)
{
frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
if ( frag == NULL)
goto err;
memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
frag->msg_header.frag_len = frag->msg_header.msg_len;
frag->msg_header.frag_off = 0;
}
else
{
frag = (hm_fragment*) item->data;
if (frag->msg_header.msg_len != msg_hdr->msg_len)
{
item = NULL;
frag = NULL;
goto err;
}
}
/* If message is already reassembled, this must be a
* retransmit and can be dropped.
frag_len>sizeof(devnull)?sizeof(devnull):frag_len,0);
if (i<=0) goto err;
frag_len -= i;
}
| 165,284
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 HarfBuzzShaper::shape(GlyphBuffer* glyphBuffer)
{
if (!createHarfBuzzRuns())
return false;
m_totalWidth = 0;
if (!shapeHarfBuzzRuns())
return false;
if (glyphBuffer && !fillGlyphBuffer(glyphBuffer))
return false;
return true;
}
Commit Message: Always initialize |m_totalWidth| in HarfBuzzShaper::shape.
R=leviw@chromium.org
BUG=476647
Review URL: https://codereview.chromium.org/1108663003
git-svn-id: svn://svn.chromium.org/blink/trunk@194541 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
|
bool HarfBuzzShaper::shape(GlyphBuffer* glyphBuffer)
{
if (!createHarfBuzzRuns())
return false;
if (!shapeHarfBuzzRuns())
return false;
if (glyphBuffer && !fillGlyphBuffer(glyphBuffer))
return false;
return true;
}
| 172,005
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: juniper_ggsn_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
struct juniper_ggsn_header {
uint8_t svc_id;
uint8_t flags_len;
uint8_t proto;
uint8_t flags;
uint8_t vlan_id[2];
uint8_t res[2];
};
const struct juniper_ggsn_header *gh;
l2info.pictype = DLT_JUNIPER_GGSN;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
gh = (struct juniper_ggsn_header *)&l2info.cookie;
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "proto %s (%u), vlan %u: ",
tok2str(juniper_protocol_values,"Unknown",gh->proto),
gh->proto,
EXTRACT_16BITS(&gh->vlan_id[0])));
}
switch (gh->proto) {
case JUNIPER_PROTO_IPV4:
ip_print(ndo, p, l2info.length);
break;
case JUNIPER_PROTO_IPV6:
ip6_print(ndo, p, l2info.length);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "unknown GGSN proto (%u)", gh->proto));
}
return l2info.header_len;
}
Commit Message: CVE-2017-12993/Juniper: Add more bounds checks.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add tests using the capture files supplied by the reporter(s).
CWE ID: CWE-125
|
juniper_ggsn_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
struct juniper_ggsn_header {
uint8_t svc_id;
uint8_t flags_len;
uint8_t proto;
uint8_t flags;
uint8_t vlan_id[2];
uint8_t res[2];
};
const struct juniper_ggsn_header *gh;
l2info.pictype = DLT_JUNIPER_GGSN;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
gh = (struct juniper_ggsn_header *)&l2info.cookie;
ND_TCHECK(*gh);
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "proto %s (%u), vlan %u: ",
tok2str(juniper_protocol_values,"Unknown",gh->proto),
gh->proto,
EXTRACT_16BITS(&gh->vlan_id[0])));
}
switch (gh->proto) {
case JUNIPER_PROTO_IPV4:
ip_print(ndo, p, l2info.length);
break;
case JUNIPER_PROTO_IPV6:
ip6_print(ndo, p, l2info.length);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "unknown GGSN proto (%u)", gh->proto));
}
return l2info.header_len;
trunc:
ND_PRINT((ndo, "[|juniper_services]"));
return l2info.header_len;
}
| 167,917
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: xps_load_sfnt_name(xps_font_t *font, char *namep)
{
byte *namedata;
int offset, length;
/*int format;*/
int count, stringoffset;
int found;
int i, k;
found = 0;
strcpy(namep, "Unknown");
offset = xps_find_sfnt_table(font, "name", &length);
if (offset < 0 || length < 6)
{
gs_warn("cannot find name table");
return;
}
namedata = font->data + offset;
/*format = u16(namedata + 0);*/
count = u16(namedata + 2);
stringoffset = u16(namedata + 4);
if (length < 6 + (count * 12))
{
gs_warn("name table too short");
{
if (pid == 1 && eid == 0 && langid == 0) /* mac roman, english */
{
if (found < 3)
{
memcpy(namep, namedata + stringoffset + offset, length);
namep[length] = 0;
found = 3;
}
}
if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */
{
if (found < 2)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 2;
for (k = 0; k < n; k ++)
{
int c = u16(s + k * 2);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 2;
}
}
if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */
{
if (found < 1)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 4;
for (k = 0; k < n; k ++)
{
int c = u32(s + k * 4);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 1;
}
}
}
}
}
Commit Message:
CWE ID: CWE-125
|
xps_load_sfnt_name(xps_font_t *font, char *namep)
{
byte *namedata;
int offset, length;
/*int format;*/
int count, stringoffset;
int found;
int i, k;
found = 0;
strcpy(namep, "Unknown");
offset = xps_find_sfnt_table(font, "name", &length);
if (offset < 0 || length < 6)
{
gs_warn("cannot find name table");
return;
}
/* validate the offset, and the data for the two
* values we're about to read
*/
if (offset + 6 > font->length)
{
gs_warn("name table byte offset invalid");
return;
}
namedata = font->data + offset;
/*format = u16(namedata + 0);*/
count = u16(namedata + 2);
stringoffset = u16(namedata + 4);
if (stringoffset + offset > font->length
|| offset + 6 + count * 12 > font->length)
{
gs_warn("name table invalid");
return;
}
if (length < 6 + (count * 12))
{
gs_warn("name table too short");
{
if (pid == 1 && eid == 0 && langid == 0) /* mac roman, english */
{
if (found < 3)
{
memcpy(namep, namedata + stringoffset + offset, length);
namep[length] = 0;
found = 3;
}
}
if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */
{
if (found < 2)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 2;
for (k = 0; k < n; k ++)
{
int c = u16(s + k * 2);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 2;
}
}
if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */
{
if (found < 1)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 4;
for (k = 0; k < n; k ++)
{
int c = u32(s + k * 4);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 1;
}
}
}
}
}
| 164,787
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr TSRMLS_DC) /* {{{ */
{
/*
This is how the time string is formatted:
snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100,
ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec);
*/
time_t ret;
struct tm thetime;
char * strbuf;
char * thestr;
long gmadjust = 0;
if (timestr->length < 13) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "extension author too lazy to parse %s correctly", timestr->data);
return (time_t)-1;
}
strbuf = estrdup((char *)timestr->data);
memset(&thetime, 0, sizeof(thetime));
/* we work backwards so that we can use atoi more easily */
thestr = strbuf + timestr->length - 3;
thetime.tm_sec = atoi(thestr);
*thestr = '\0';
thetime.tm_mon = atoi(thestr)-1;
*thestr = '\0';
thestr -= 2;
thetime.tm_year = atoi(thestr);
if (thetime.tm_year < 68) {
thetime.tm_year += 100;
}
thetime.tm_isdst = -1;
ret = mktime(&thetime);
#if HAVE_TM_GMTOFF
gmadjust = thetime.tm_gmtoff;
#else
/*
** If correcting for daylight savings time, we set the adjustment to
** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and
** set the adjustment to the main timezone + 3600 seconds.
*/
gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone + 3600);
#endif
ret += gmadjust;
efree(strbuf);
return ret;
}
/* }}} */
Commit Message:
CWE ID: CWE-119
|
static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr TSRMLS_DC) /* {{{ */
{
/*
This is how the time string is formatted:
snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100,
ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec);
*/
time_t ret;
struct tm thetime;
char * strbuf;
char * thestr;
long gmadjust = 0;
if (ASN1_STRING_type(timestr) != V_ASN1_UTCTIME) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "illegal ASN1 data type for timestamp");
return (time_t)-1;
}
if (ASN1_STRING_length(timestr) != strlen(ASN1_STRING_data(timestr))) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "illegal length in timestamp");
return (time_t)-1;
}
if (ASN1_STRING_length(timestr) < 13) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to parse time string %s correctly", timestr->data);
return (time_t)-1;
}
strbuf = estrdup((char *)ASN1_STRING_data(timestr));
memset(&thetime, 0, sizeof(thetime));
/* we work backwards so that we can use atoi more easily */
thestr = strbuf + ASN1_STRING_length(timestr) - 3;
thetime.tm_sec = atoi(thestr);
*thestr = '\0';
thetime.tm_mon = atoi(thestr)-1;
*thestr = '\0';
thestr -= 2;
thetime.tm_year = atoi(thestr);
if (thetime.tm_year < 68) {
thetime.tm_year += 100;
}
thetime.tm_isdst = -1;
ret = mktime(&thetime);
#if HAVE_TM_GMTOFF
gmadjust = thetime.tm_gmtoff;
#else
/*
** If correcting for daylight savings time, we set the adjustment to
** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and
** set the adjustment to the main timezone + 3600 seconds.
*/
gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone + 3600);
#endif
ret += gmadjust;
efree(strbuf);
return ret;
}
/* }}} */
| 164,568
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static bool svc_rdma_prealloc_maps(struct svcxprt_rdma *xprt)
{
unsigned int i;
/* One for each receive buffer on this connection. */
i = xprt->sc_max_requests;
while (i--) {
struct svc_rdma_req_map *map;
map = alloc_req_map(GFP_KERNEL);
if (!map) {
dprintk("svcrdma: No memory for request map\n");
return false;
}
list_add(&map->free, &xprt->sc_maps);
}
return true;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
|
static bool svc_rdma_prealloc_maps(struct svcxprt_rdma *xprt)
| 168,182
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: BackendImpl::BackendImpl(
const base::FilePath& path,
scoped_refptr<BackendCleanupTracker> cleanup_tracker,
const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread,
net::NetLog* net_log)
: cleanup_tracker_(std::move(cleanup_tracker)),
background_queue_(this, FallbackToInternalIfNull(cache_thread)),
path_(path),
block_files_(path),
mask_(0),
max_size_(0),
up_ticks_(0),
cache_type_(net::DISK_CACHE),
uma_report_(0),
user_flags_(0),
init_(false),
restarted_(false),
unit_test_(false),
read_only_(false),
disabled_(false),
new_eviction_(false),
first_timer_(true),
user_load_(false),
net_log_(net_log),
done_(base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED),
ptr_factory_(this) {}
Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem
Thanks to nedwilliamson@ (on gmail) for an alternative perspective
plus a reduction to make fixing this much easier.
Bug: 826626, 518908, 537063, 802886
Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f
Reviewed-on: https://chromium-review.googlesource.com/985052
Reviewed-by: Matt Menke <mmenke@chromium.org>
Commit-Queue: Maks Orlovich <morlovich@chromium.org>
Cr-Commit-Position: refs/heads/master@{#547103}
CWE ID: CWE-20
|
BackendImpl::BackendImpl(
const base::FilePath& path,
scoped_refptr<BackendCleanupTracker> cleanup_tracker,
const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread,
net::NetLog* net_log)
: cleanup_tracker_(std::move(cleanup_tracker)),
background_queue_(this, FallbackToInternalIfNull(cache_thread)),
path_(path),
block_files_(path),
mask_(0),
max_size_(0),
up_ticks_(0),
cache_type_(net::DISK_CACHE),
uma_report_(0),
user_flags_(0),
init_(false),
restarted_(false),
unit_test_(false),
read_only_(false),
disabled_(false),
new_eviction_(false),
first_timer_(true),
user_load_(false),
consider_evicting_at_op_end_(false),
net_log_(net_log),
done_(base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED),
ptr_factory_(this) {}
| 172,696
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int main(int argc, char **argv) {
int frame_cnt = 0;
FILE *outfile = NULL;
vpx_codec_ctx_t codec;
vpx_codec_err_t res;
VpxVideoReader *reader = NULL;
const VpxInterface *decoder = NULL;
const VpxVideoInfo *info = NULL;
exec_name = argv[0];
if (argc != 3)
die("Invalid number of arguments.");
reader = vpx_video_reader_open(argv[1]);
if (!reader)
die("Failed to open %s for reading.", argv[1]);
if (!(outfile = fopen(argv[2], "wb")))
die("Failed to open %s for writing", argv[2]);
info = vpx_video_reader_get_info(reader);
decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc);
if (!decoder)
die("Unknown input codec.");
printf("Using %s\n", vpx_codec_iface_name(decoder->interface()));
res = vpx_codec_dec_init(&codec, decoder->interface(), NULL,
VPX_CODEC_USE_POSTPROC);
if (res == VPX_CODEC_INCAPABLE)
die_codec(&codec, "Postproc not supported by this decoder.");
if (res)
die_codec(&codec, "Failed to initialize decoder.");
while (vpx_video_reader_read_frame(reader)) {
vpx_codec_iter_t iter = NULL;
vpx_image_t *img = NULL;
size_t frame_size = 0;
const unsigned char *frame = vpx_video_reader_get_frame(reader,
&frame_size);
++frame_cnt;
if (frame_cnt % 30 == 1) {
vp8_postproc_cfg_t pp = {0, 0, 0};
if (vpx_codec_control(&codec, VP8_SET_POSTPROC, &pp))
die_codec(&codec, "Failed to turn off postproc.");
} else if (frame_cnt % 30 == 16) {
vp8_postproc_cfg_t pp = {VP8_DEBLOCK | VP8_DEMACROBLOCK | VP8_MFQE,
4, 0};
if (vpx_codec_control(&codec, VP8_SET_POSTPROC, &pp))
die_codec(&codec, "Failed to turn on postproc.");
};
if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 15000))
die_codec(&codec, "Failed to decode frame");
while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) {
vpx_img_write(img, outfile);
}
}
printf("Processed %d frames.\n", frame_cnt);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec");
printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n",
info->frame_width, info->frame_height, argv[2]);
vpx_video_reader_close(reader);
fclose(outfile);
return EXIT_SUCCESS;
}
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
|
int main(int argc, char **argv) {
int frame_cnt = 0;
FILE *outfile = NULL;
vpx_codec_ctx_t codec;
vpx_codec_err_t res;
VpxVideoReader *reader = NULL;
const VpxInterface *decoder = NULL;
const VpxVideoInfo *info = NULL;
exec_name = argv[0];
if (argc != 3)
die("Invalid number of arguments.");
reader = vpx_video_reader_open(argv[1]);
if (!reader)
die("Failed to open %s for reading.", argv[1]);
if (!(outfile = fopen(argv[2], "wb")))
die("Failed to open %s for writing", argv[2]);
info = vpx_video_reader_get_info(reader);
decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc);
if (!decoder)
die("Unknown input codec.");
printf("Using %s\n", vpx_codec_iface_name(decoder->codec_interface()));
res = vpx_codec_dec_init(&codec, decoder->codec_interface(), NULL,
VPX_CODEC_USE_POSTPROC);
if (res == VPX_CODEC_INCAPABLE)
die_codec(&codec, "Postproc not supported by this decoder.");
if (res)
die_codec(&codec, "Failed to initialize decoder.");
while (vpx_video_reader_read_frame(reader)) {
vpx_codec_iter_t iter = NULL;
vpx_image_t *img = NULL;
size_t frame_size = 0;
const unsigned char *frame = vpx_video_reader_get_frame(reader,
&frame_size);
++frame_cnt;
if (frame_cnt % 30 == 1) {
vp8_postproc_cfg_t pp = {0, 0, 0};
if (vpx_codec_control(&codec, VP8_SET_POSTPROC, &pp))
die_codec(&codec, "Failed to turn off postproc.");
} else if (frame_cnt % 30 == 16) {
vp8_postproc_cfg_t pp = {VP8_DEBLOCK | VP8_DEMACROBLOCK | VP8_MFQE,
4, 0};
if (vpx_codec_control(&codec, VP8_SET_POSTPROC, &pp))
die_codec(&codec, "Failed to turn on postproc.");
};
if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 15000))
die_codec(&codec, "Failed to decode frame");
while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) {
vpx_img_write(img, outfile);
}
}
printf("Processed %d frames.\n", frame_cnt);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec");
printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n",
info->frame_width, info->frame_height, argv[2]);
vpx_video_reader_close(reader);
fclose(outfile);
return EXIT_SUCCESS;
}
| 174,478
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
{
struct page *page;
struct kvm *kvm;
int r;
BUG_ON(vcpu->kvm == NULL);
kvm = vcpu->kvm;
vcpu->arch.emulate_ctxt.ops = &emulate_ops;
if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
else
vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
page = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (!page) {
r = -ENOMEM;
goto fail;
}
vcpu->arch.pio_data = page_address(page);
kvm_set_tsc_khz(vcpu, max_tsc_khz);
r = kvm_mmu_create(vcpu);
if (r < 0)
goto fail_free_pio_data;
if (irqchip_in_kernel(kvm)) {
r = kvm_create_lapic(vcpu);
if (r < 0)
goto fail_mmu_destroy;
} else
static_key_slow_inc(&kvm_no_apic_vcpu);
vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
GFP_KERNEL);
if (!vcpu->arch.mce_banks) {
r = -ENOMEM;
goto fail_free_lapic;
}
vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL))
goto fail_free_mce_banks;
r = fx_init(vcpu);
if (r)
goto fail_free_wbinvd_dirty_mask;
vcpu->arch.ia32_tsc_adjust_msr = 0x0;
kvm_async_pf_hash_reset(vcpu);
kvm_pmu_init(vcpu);
return 0;
fail_free_wbinvd_dirty_mask:
free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
fail_free_mce_banks:
kfree(vcpu->arch.mce_banks);
fail_free_lapic:
kvm_free_lapic(vcpu);
fail_mmu_destroy:
kvm_mmu_destroy(vcpu);
fail_free_pio_data:
free_page((unsigned long)vcpu->arch.pio_data);
fail:
return r;
}
Commit Message: KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797)
There is a potential use after free issue with the handling of
MSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable
memory such as frame buffers then KVM might continue to write to that
address even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins
the page in memory so it's unlikely to cause an issue, but if the user
space component re-purposes the memory previously used for the guest, then
the guest will be able to corrupt that memory.
Tested: Tested against kvmclock unit test
Signed-off-by: Andrew Honig <ahonig@google.com>
Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com>
CWE ID: CWE-399
|
int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
{
struct page *page;
struct kvm *kvm;
int r;
BUG_ON(vcpu->kvm == NULL);
kvm = vcpu->kvm;
vcpu->arch.emulate_ctxt.ops = &emulate_ops;
if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
else
vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
page = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (!page) {
r = -ENOMEM;
goto fail;
}
vcpu->arch.pio_data = page_address(page);
kvm_set_tsc_khz(vcpu, max_tsc_khz);
r = kvm_mmu_create(vcpu);
if (r < 0)
goto fail_free_pio_data;
if (irqchip_in_kernel(kvm)) {
r = kvm_create_lapic(vcpu);
if (r < 0)
goto fail_mmu_destroy;
} else
static_key_slow_inc(&kvm_no_apic_vcpu);
vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
GFP_KERNEL);
if (!vcpu->arch.mce_banks) {
r = -ENOMEM;
goto fail_free_lapic;
}
vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL))
goto fail_free_mce_banks;
r = fx_init(vcpu);
if (r)
goto fail_free_wbinvd_dirty_mask;
vcpu->arch.ia32_tsc_adjust_msr = 0x0;
vcpu->arch.pv_time_enabled = false;
kvm_async_pf_hash_reset(vcpu);
kvm_pmu_init(vcpu);
return 0;
fail_free_wbinvd_dirty_mask:
free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
fail_free_mce_banks:
kfree(vcpu->arch.mce_banks);
fail_free_lapic:
kvm_free_lapic(vcpu);
fail_mmu_destroy:
kvm_mmu_destroy(vcpu);
fail_free_pio_data:
free_page((unsigned long)vcpu->arch.pio_data);
fail:
return r;
}
| 166,115
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SPL_METHOD(Array, unserialize)
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *buf;
int buf_len;
const unsigned char *p, *s;
php_unserialize_data_t var_hash;
zval *pmembers, *pflags = NULL;
long flags;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) {
return;
}
if (buf_len == 0) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Empty serialized string cannot be empty");
return;
}
/* storage */
s = p = (const unsigned char*)buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (*p!= 'x' || *++p != ':') {
goto outexcept;
}
++p;
ALLOC_INIT_ZVAL(pflags);
if (!php_var_unserialize(&pflags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pflags) != IS_LONG) {
zval_ptr_dtor(&pflags);
goto outexcept;
}
--p; /* for ';' */
flags = Z_LVAL_P(pflags);
zval_ptr_dtor(&pflags);
/* flags needs to be verified and we also need to verify whether the next
* thing we get is ';'. After that we require an 'm' or somethign else
* where 'm' stands for members and anything else should be an array. If
* neither 'a' or 'm' follows we have an error. */
if (*p != ';') {
goto outexcept;
}
++p;
if (*p!='m') {
if (*p!='a' && *p!='O' && *p!='C' && *p!='r') {
goto outexcept;
}
intern->ar_flags &= ~SPL_ARRAY_CLONE_MASK;
intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK;
zval_ptr_dtor(&intern->array);
ALLOC_INIT_ZVAL(intern->array);
if (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC)) {
goto outexcept;
}
}
if (*p != ';') {
goto outexcept;
}
++p;
/* members */
if (*p!= 'm' || *++p != ':') {
goto outexcept;
}
++p;
ALLOC_INIT_ZVAL(pmembers);
if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&pmembers);
goto outexcept;
}
/* copy members */
if (!intern->std.properties) {
rebuild_object_properties(&intern->std);
}
zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *));
zval_ptr_dtor(&pmembers);
/* done reading $serialized */
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
outexcept:
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len);
return;
} /* }}} */
/* {{{ arginfo and function tbale */
Commit Message:
CWE ID:
|
SPL_METHOD(Array, unserialize)
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *buf;
int buf_len;
const unsigned char *p, *s;
php_unserialize_data_t var_hash;
zval *pmembers, *pflags = NULL;
long flags;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) {
return;
}
if (buf_len == 0) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Empty serialized string cannot be empty");
return;
}
/* storage */
s = p = (const unsigned char*)buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (*p!= 'x' || *++p != ':') {
goto outexcept;
}
++p;
ALLOC_INIT_ZVAL(pflags);
if (!php_var_unserialize(&pflags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pflags) != IS_LONG) {
zval_ptr_dtor(&pflags);
goto outexcept;
}
--p; /* for ';' */
flags = Z_LVAL_P(pflags);
zval_ptr_dtor(&pflags);
/* flags needs to be verified and we also need to verify whether the next
* thing we get is ';'. After that we require an 'm' or somethign else
* where 'm' stands for members and anything else should be an array. If
* neither 'a' or 'm' follows we have an error. */
if (*p != ';') {
goto outexcept;
}
++p;
if (*p!='m') {
if (*p!='a' && *p!='O' && *p!='C' && *p!='r') {
goto outexcept;
}
intern->ar_flags &= ~SPL_ARRAY_CLONE_MASK;
intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK;
zval_ptr_dtor(&intern->array);
ALLOC_INIT_ZVAL(intern->array);
if (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC)) {
goto outexcept;
}
}
if (*p != ';') {
goto outexcept;
}
++p;
/* members */
if (*p!= 'm' || *++p != ':') {
goto outexcept;
}
++p;
ALLOC_INIT_ZVAL(pmembers);
if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pmembers) != IS_ARRAY) {
zval_ptr_dtor(&pmembers);
goto outexcept;
}
/* copy members */
if (!intern->std.properties) {
rebuild_object_properties(&intern->std);
}
zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *));
zval_ptr_dtor(&pmembers);
/* done reading $serialized */
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
outexcept:
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len);
return;
} /* }}} */
/* {{{ arginfo and function tbale */
| 165,166
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: next_format(png_bytep colour_type, png_bytep bit_depth,
unsigned int* palette_number, int no_low_depth_gray)
{
if (*bit_depth == 0)
{
*colour_type = 0;
if (no_low_depth_gray)
*bit_depth = 8;
else
*bit_depth = 1;
*palette_number = 0;
return 1;
}
if (*colour_type == 3)
{
/* Add multiple palettes for colour type 3. */
if (++*palette_number < PALETTE_COUNT(*bit_depth))
return 1;
*palette_number = 0;
}
*bit_depth = (png_byte)(*bit_depth << 1);
/* Palette images are restricted to 8 bit depth */
if (*bit_depth <= 8
# ifdef DO_16BIT
|| (*colour_type != 3 && *bit_depth <= 16)
# endif
)
return 1;
/* Move to the next color type, or return 0 at the end. */
switch (*colour_type)
{
case 0:
*colour_type = 2;
*bit_depth = 8;
return 1;
case 2:
*colour_type = 3;
*bit_depth = 1;
return 1;
case 3:
*colour_type = 4;
*bit_depth = 8;
return 1;
case 4:
*colour_type = 6;
*bit_depth = 8;
return 1;
default:
return 0;
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
next_format(png_bytep colour_type, png_bytep bit_depth,
unsigned int* palette_number, int low_depth_gray, int tRNS)
{
if (*bit_depth == 0)
{
*colour_type = 0;
if (low_depth_gray)
*bit_depth = 1;
else
*bit_depth = 8;
*palette_number = 0;
return 1;
}
if (*colour_type < 4/*no alpha channel*/)
{
/* Add multiple palettes for colour type 3, one image with tRNS
* and one without for other non-alpha formats:
*/
unsigned int pn = ++*palette_number;
png_byte ct = *colour_type;
if (((ct == 0/*GRAY*/ || ct/*RGB*/ == 2) && tRNS && pn < 2) ||
(ct == 3/*PALETTE*/ && pn < PALETTE_COUNT(*bit_depth)))
return 1;
/* No: next bit depth */
*palette_number = 0;
}
*bit_depth = (png_byte)(*bit_depth << 1);
/* Palette images are restricted to 8 bit depth */
if (*bit_depth <= 8
#ifdef DO_16BIT
|| (*colour_type != 3 && *bit_depth <= 16)
#endif
)
return 1;
/* Move to the next color type, or return 0 at the end. */
switch (*colour_type)
{
case 0:
*colour_type = 2;
*bit_depth = 8;
return 1;
case 2:
*colour_type = 3;
*bit_depth = 1;
return 1;
case 3:
*colour_type = 4;
*bit_depth = 8;
return 1;
case 4:
*colour_type = 6;
*bit_depth = 8;
return 1;
default:
return 0;
}
}
| 173,672
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŧтҭ] > t;"
"[ƅьҍв] > b; [ωшщ] > w; [мӎ] > m;"
"п > n; [єҽҿ] > e; ґ > r; ғ > f; ҫ > c;"
"ұ > y; [χҳӽӿ] > x;"
#if defined(OS_WIN)
"ӏ > i;"
#else
"ӏ > l;"
#endif
"ԃ > d; ԍ > g; ട > s"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Add more entries to the confusability mapping
U+014B (ŋ) => n
U+1004 (င) => c
U+100c (ဌ) => g
U+1042 (၂) => j
U+1054 (ၔ) => e
Bug: 811117,808316
Test: components_unittests -gtest_filter=*IDN*
Change-Id: I29f73c48d665bd9070050bd7f0080563635b9c63
Reviewed-on: https://chromium-review.googlesource.com/919423
Reviewed-by: Peter Kasting <pkasting@chromium.org>
Commit-Queue: Jungshik Shin <jshin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#536955}
CWE ID:
|
IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// - {U+014B (ŋ), U+043F (п)} => n
// - {U+0454 (є), U+04BD (ҽ), U+04BF (ҿ), U+1054 (ၔ)} => e
// - {U+04AB (ҫ), U+1004 (င)} => c
// - {U+050D (ԍ), U+100c (ဌ)} => g
// - U+1042 (၂) => j
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭ] > t;"
"[ƅьҍв] > b; [ωшщ] > w; [мӎ] > m;"
"[єҽҿၔ] > e; ґ > r; ғ > f; [ҫင] > c;"
"ұ > y; [χҳӽӿ] > x;"
#if defined(OS_WIN)
"ӏ > i;"
#else
"ӏ > l;"
#endif
"ԃ > d; [ԍဌ] > g; ട > s; ၂ > j"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 172,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: const char* Track::GetNameAsUTF8() const
{
return m_info.nameAsUTF8;
}
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 char* Track::GetNameAsUTF8() const
| 174,343
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: views::View* AutofillDialogViews::CreateFootnoteView() {
footnote_view_ = new LayoutPropagationView();
footnote_view_->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kVertical,
kDialogEdgePadding,
kDialogEdgePadding,
0));
footnote_view_->SetBorder(
views::Border::CreateSolidSidedBorder(1, 0, 0, 0, kSubtleBorderColor));
footnote_view_->set_background(
views::Background::CreateSolidBackground(kShadingColor));
legal_document_view_ = new views::StyledLabel(base::string16(), this);
footnote_view_->AddChildView(legal_document_view_);
footnote_view_->SetVisible(false);
return footnote_view_;
}
Commit Message: Clear out some minor TODOs.
BUG=none
Review URL: https://codereview.chromium.org/1047063002
Cr-Commit-Position: refs/heads/master@{#322959}
CWE ID: CWE-20
|
views::View* AutofillDialogViews::CreateFootnoteView() {
footnote_view_ = new LayoutPropagationView();
footnote_view_->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kVertical,
kDialogEdgePadding,
kDialogEdgePadding,
0));
footnote_view_->SetBorder(
views::Border::CreateSolidSidedBorder(1, 0, 0, 0, kSubtleBorderColor));
footnote_view_->set_background(
views::Background::CreateSolidBackground(kLightShadingColor));
legal_document_view_ = new views::StyledLabel(base::string16(), this);
footnote_view_->AddChildView(legal_document_view_);
footnote_view_->SetVisible(false);
return footnote_view_;
}
| 171,139
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Splash::scaleMaskYuXd(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest) {
Guchar *lineBuf;
Guint pix;
Guchar *destPtr0, *destPtr;
int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, xx, d, d0, d1;
int i;
yp = scaledHeight / srcHeight;
lineBuf = (Guchar *)gmalloc(srcWidth);
yt = 0;
destPtr0 = dest->data;
for (y = 0; y < srcHeight; ++y) {
yt = 0;
destPtr0 = dest->data;
for (y = 0; y < srcHeight; ++y) {
}
(*src)(srcData, lineBuf);
xt = 0;
d0 = (255 << 23) / xp;
d1 = (255 << 23) / (xp + 1);
xx = 0;
for (x = 0; x < scaledWidth; ++x) {
if ((xt += xq) >= scaledWidth) {
xt -= scaledWidth;
xStep = xp + 1;
d = d1;
} else {
xStep = xp;
d = d0;
}
pix = 0;
for (i = 0; i < xStep; ++i) {
pix += lineBuf[xx++];
}
pix = (pix * d) >> 23;
for (i = 0; i < yStep; ++i) {
destPtr = destPtr0 + i * scaledWidth + x;
*destPtr = (Guchar)pix;
}
}
destPtr0 += yStep * scaledWidth;
}
gfree(lineBuf);
}
Commit Message:
CWE ID: CWE-119
|
void Splash::scaleMaskYuXd(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest) {
Guchar *lineBuf;
Guint pix;
Guchar *destPtr0, *destPtr;
int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, xx, d, d0, d1;
int i;
destPtr0 = dest->data;
if (destPtr0 == NULL) {
error(errInternal, -1, "dest->data is NULL in Splash::scaleMaskYuXd");
return;
}
yp = scaledHeight / srcHeight;
lineBuf = (Guchar *)gmalloc(srcWidth);
yt = 0;
destPtr0 = dest->data;
for (y = 0; y < srcHeight; ++y) {
yt = 0;
for (y = 0; y < srcHeight; ++y) {
}
(*src)(srcData, lineBuf);
xt = 0;
d0 = (255 << 23) / xp;
d1 = (255 << 23) / (xp + 1);
xx = 0;
for (x = 0; x < scaledWidth; ++x) {
if ((xt += xq) >= scaledWidth) {
xt -= scaledWidth;
xStep = xp + 1;
d = d1;
} else {
xStep = xp;
d = d0;
}
pix = 0;
for (i = 0; i < xStep; ++i) {
pix += lineBuf[xx++];
}
pix = (pix * d) >> 23;
for (i = 0; i < yStep; ++i) {
destPtr = destPtr0 + i * scaledWidth + x;
*destPtr = (Guchar)pix;
}
}
destPtr0 += yStep * scaledWidth;
}
gfree(lineBuf);
}
| 164,735
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static struct page *follow_pmd_mask(struct vm_area_struct *vma,
unsigned long address, pud_t *pudp,
unsigned int flags,
struct follow_page_context *ctx)
{
pmd_t *pmd, pmdval;
spinlock_t *ptl;
struct page *page;
struct mm_struct *mm = vma->vm_mm;
pmd = pmd_offset(pudp, address);
/*
* The READ_ONCE() will stabilize the pmdval in a register or
* on the stack so that it will stop changing under the code.
*/
pmdval = READ_ONCE(*pmd);
if (pmd_none(pmdval))
return no_page_table(vma, flags);
if (pmd_huge(pmdval) && vma->vm_flags & VM_HUGETLB) {
page = follow_huge_pmd(mm, address, pmd, flags);
if (page)
return page;
return no_page_table(vma, flags);
}
if (is_hugepd(__hugepd(pmd_val(pmdval)))) {
page = follow_huge_pd(vma, address,
__hugepd(pmd_val(pmdval)), flags,
PMD_SHIFT);
if (page)
return page;
return no_page_table(vma, flags);
}
retry:
if (!pmd_present(pmdval)) {
if (likely(!(flags & FOLL_MIGRATION)))
return no_page_table(vma, flags);
VM_BUG_ON(thp_migration_supported() &&
!is_pmd_migration_entry(pmdval));
if (is_pmd_migration_entry(pmdval))
pmd_migration_entry_wait(mm, pmd);
pmdval = READ_ONCE(*pmd);
/*
* MADV_DONTNEED may convert the pmd to null because
* mmap_sem is held in read mode
*/
if (pmd_none(pmdval))
return no_page_table(vma, flags);
goto retry;
}
if (pmd_devmap(pmdval)) {
ptl = pmd_lock(mm, pmd);
page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
spin_unlock(ptl);
if (page)
return page;
}
if (likely(!pmd_trans_huge(pmdval)))
return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
if ((flags & FOLL_NUMA) && pmd_protnone(pmdval))
return no_page_table(vma, flags);
retry_locked:
ptl = pmd_lock(mm, pmd);
if (unlikely(pmd_none(*pmd))) {
spin_unlock(ptl);
return no_page_table(vma, flags);
}
if (unlikely(!pmd_present(*pmd))) {
spin_unlock(ptl);
if (likely(!(flags & FOLL_MIGRATION)))
return no_page_table(vma, flags);
pmd_migration_entry_wait(mm, pmd);
goto retry_locked;
}
if (unlikely(!pmd_trans_huge(*pmd))) {
spin_unlock(ptl);
return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
}
if (flags & FOLL_SPLIT) {
int ret;
page = pmd_page(*pmd);
if (is_huge_zero_page(page)) {
spin_unlock(ptl);
ret = 0;
split_huge_pmd(vma, pmd, address);
if (pmd_trans_unstable(pmd))
ret = -EBUSY;
} else {
get_page(page);
spin_unlock(ptl);
lock_page(page);
ret = split_huge_page(page);
unlock_page(page);
put_page(page);
if (pmd_none(*pmd))
return no_page_table(vma, flags);
}
return ret ? ERR_PTR(ret) :
follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
}
page = follow_trans_huge_pmd(vma, address, pmd, flags);
spin_unlock(ptl);
ctx->page_mask = HPAGE_PMD_NR - 1;
return page;
}
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
|
static struct page *follow_pmd_mask(struct vm_area_struct *vma,
unsigned long address, pud_t *pudp,
unsigned int flags,
struct follow_page_context *ctx)
{
pmd_t *pmd, pmdval;
spinlock_t *ptl;
struct page *page;
struct mm_struct *mm = vma->vm_mm;
pmd = pmd_offset(pudp, address);
/*
* The READ_ONCE() will stabilize the pmdval in a register or
* on the stack so that it will stop changing under the code.
*/
pmdval = READ_ONCE(*pmd);
if (pmd_none(pmdval))
return no_page_table(vma, flags);
if (pmd_huge(pmdval) && vma->vm_flags & VM_HUGETLB) {
page = follow_huge_pmd(mm, address, pmd, flags);
if (page)
return page;
return no_page_table(vma, flags);
}
if (is_hugepd(__hugepd(pmd_val(pmdval)))) {
page = follow_huge_pd(vma, address,
__hugepd(pmd_val(pmdval)), flags,
PMD_SHIFT);
if (page)
return page;
return no_page_table(vma, flags);
}
retry:
if (!pmd_present(pmdval)) {
if (likely(!(flags & FOLL_MIGRATION)))
return no_page_table(vma, flags);
VM_BUG_ON(thp_migration_supported() &&
!is_pmd_migration_entry(pmdval));
if (is_pmd_migration_entry(pmdval))
pmd_migration_entry_wait(mm, pmd);
pmdval = READ_ONCE(*pmd);
/*
* MADV_DONTNEED may convert the pmd to null because
* mmap_sem is held in read mode
*/
if (pmd_none(pmdval))
return no_page_table(vma, flags);
goto retry;
}
if (pmd_devmap(pmdval)) {
ptl = pmd_lock(mm, pmd);
page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
spin_unlock(ptl);
if (page)
return page;
}
if (likely(!pmd_trans_huge(pmdval)))
return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
if ((flags & FOLL_NUMA) && pmd_protnone(pmdval))
return no_page_table(vma, flags);
retry_locked:
ptl = pmd_lock(mm, pmd);
if (unlikely(pmd_none(*pmd))) {
spin_unlock(ptl);
return no_page_table(vma, flags);
}
if (unlikely(!pmd_present(*pmd))) {
spin_unlock(ptl);
if (likely(!(flags & FOLL_MIGRATION)))
return no_page_table(vma, flags);
pmd_migration_entry_wait(mm, pmd);
goto retry_locked;
}
if (unlikely(!pmd_trans_huge(*pmd))) {
spin_unlock(ptl);
return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
}
if (flags & FOLL_SPLIT) {
int ret;
page = pmd_page(*pmd);
if (is_huge_zero_page(page)) {
spin_unlock(ptl);
ret = 0;
split_huge_pmd(vma, pmd, address);
if (pmd_trans_unstable(pmd))
ret = -EBUSY;
} else {
if (unlikely(!try_get_page(page))) {
spin_unlock(ptl);
return ERR_PTR(-ENOMEM);
}
spin_unlock(ptl);
lock_page(page);
ret = split_huge_page(page);
unlock_page(page);
put_page(page);
if (pmd_none(*pmd))
return no_page_table(vma, flags);
}
return ret ? ERR_PTR(ret) :
follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
}
page = follow_trans_huge_pmd(vma, address, pmd, flags);
spin_unlock(ptl);
ctx->page_mask = HPAGE_PMD_NR - 1;
return page;
}
| 170,223
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: xmlParsePubidLiteral(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
xmlChar cur;
xmlChar stop;
int count = 0;
xmlParserInputState oldstate = ctxt->instate;
SHRINK;
if (RAW == '"') {
NEXT;
stop = '"';
} else if (RAW == '\'') {
NEXT;
stop = '\'';
} else {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL);
return(NULL);
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
ctxt->instate = XML_PARSER_PUBLIC_LITERAL;
cur = CUR;
while ((IS_PUBIDCHAR_CH(cur)) && (cur != stop)) { /* checked */
if (len + 1 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buf);
return(NULL);
}
buf = tmp;
}
buf[len++] = cur;
count++;
if (count > 50) {
GROW;
count = 0;
}
NEXT;
cur = CUR;
if (cur == 0) {
GROW;
SHRINK;
cur = CUR;
}
}
buf[len] = 0;
if (cur != stop) {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL);
} else {
NEXT;
}
ctxt->instate = oldstate;
return(buf);
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
xmlParsePubidLiteral(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
xmlChar cur;
xmlChar stop;
int count = 0;
xmlParserInputState oldstate = ctxt->instate;
SHRINK;
if (RAW == '"') {
NEXT;
stop = '"';
} else if (RAW == '\'') {
NEXT;
stop = '\'';
} else {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL);
return(NULL);
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
ctxt->instate = XML_PARSER_PUBLIC_LITERAL;
cur = CUR;
while ((IS_PUBIDCHAR_CH(cur)) && (cur != stop)) { /* checked */
if (len + 1 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buf);
return(NULL);
}
buf = tmp;
}
buf[len++] = cur;
count++;
if (count > 50) {
GROW;
count = 0;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return(NULL);
}
}
NEXT;
cur = CUR;
if (cur == 0) {
GROW;
SHRINK;
cur = CUR;
}
}
buf[len] = 0;
if (cur != stop) {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL);
} else {
NEXT;
}
ctxt->instate = oldstate;
return(buf);
}
| 171,301
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 file *get_empty_filp(void)
{
const struct cred *cred = current_cred();
static long old_max;
struct file *f;
int error;
/*
* Privileged users can go above max_files
*/
if (get_nr_files() >= files_stat.max_files && !capable(CAP_SYS_ADMIN)) {
/*
* percpu_counters are inaccurate. Do an expensive check before
* we go and fail.
*/
if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files)
goto over;
}
f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL);
if (unlikely(!f))
return ERR_PTR(-ENOMEM);
percpu_counter_inc(&nr_files);
f->f_cred = get_cred(cred);
error = security_file_alloc(f);
if (unlikely(error)) {
file_free(f);
return ERR_PTR(error);
}
INIT_LIST_HEAD(&f->f_u.fu_list);
atomic_long_set(&f->f_count, 1);
rwlock_init(&f->f_owner.lock);
spin_lock_init(&f->f_lock);
eventpoll_init_file(f);
/* f->f_version: 0 */
return f;
over:
/* Ran out of filps - report that */
if (get_nr_files() > old_max) {
pr_info("VFS: file-max limit %lu reached\n", get_max_files());
old_max = get_nr_files();
}
return ERR_PTR(-ENFILE);
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
CWE ID: CWE-17
|
struct file *get_empty_filp(void)
{
const struct cred *cred = current_cred();
static long old_max;
struct file *f;
int error;
/*
* Privileged users can go above max_files
*/
if (get_nr_files() >= files_stat.max_files && !capable(CAP_SYS_ADMIN)) {
/*
* percpu_counters are inaccurate. Do an expensive check before
* we go and fail.
*/
if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files)
goto over;
}
f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL);
if (unlikely(!f))
return ERR_PTR(-ENOMEM);
percpu_counter_inc(&nr_files);
f->f_cred = get_cred(cred);
error = security_file_alloc(f);
if (unlikely(error)) {
file_free(f);
return ERR_PTR(error);
}
atomic_long_set(&f->f_count, 1);
rwlock_init(&f->f_owner.lock);
spin_lock_init(&f->f_lock);
eventpoll_init_file(f);
/* f->f_version: 0 */
return f;
over:
/* Ran out of filps - report that */
if (get_nr_files() > old_max) {
pr_info("VFS: file-max limit %lu reached\n", get_max_files());
old_max = get_nr_files();
}
return ERR_PTR(-ENFILE);
}
| 166,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: validGlxScreen(ClientPtr client, int screen, __GLXscreen **pGlxScreen, int *err)
{
/*
** Check if screen exists.
*/
if (screen >= screenInfo.numScreens) {
client->errorValue = screen;
*err = BadValue;
return FALSE;
}
*pGlxScreen = glxGetScreen(screenInfo.screens[screen]);
return TRUE;
}
Commit Message:
CWE ID: CWE-20
|
validGlxScreen(ClientPtr client, int screen, __GLXscreen **pGlxScreen, int *err)
{
/*
** Check if screen exists.
*/
if (screen < 0 || screen >= screenInfo.numScreens) {
client->errorValue = screen;
*err = BadValue;
return FALSE;
}
*pGlxScreen = glxGetScreen(screenInfo.screens[screen]);
return TRUE;
}
| 165,270
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: pdf_dict_put(fz_context *ctx, pdf_obj *obj, pdf_obj *key, pdf_obj *val)
{
int i;
RESOLVE(obj);
if (!OBJ_IS_DICT(obj))
fz_throw(ctx, FZ_ERROR_GENERIC, "not a dict (%s)", pdf_objkindstr(obj));
if (!val)
val = PDF_OBJ_NULL;
if (DICT(obj)->len > 100 && !(obj->flags & PDF_FLAGS_SORTED))
pdf_sort_dict(ctx, obj);
if (key < PDF_OBJ_NAME__LIMIT)
i = pdf_dict_find(ctx, obj, key);
else
i = pdf_dict_finds(ctx, obj, pdf_to_name(ctx, key));
prepare_object_for_alteration(ctx, obj, val);
if (i >= 0 && i < DICT(obj)->len)
{
if (DICT(obj)->items[i].v != val)
{
pdf_obj *d = DICT(obj)->items[i].v;
DICT(obj)->items[i].v = pdf_keep_obj(ctx, val);
{
pdf_obj *d = DICT(obj)->items[i].v;
DICT(obj)->items[i].v = pdf_keep_obj(ctx, val);
pdf_drop_obj(ctx, d);
}
}
else
memmove(&DICT(obj)->items[i + 1],
&DICT(obj)->items[i],
(DICT(obj)->len - i) * sizeof(struct keyval));
DICT(obj)->items[i].k = pdf_keep_obj(ctx, key);
DICT(obj)->items[i].v = pdf_keep_obj(ctx, val);
DICT(obj)->len ++;
}
}
Commit Message:
CWE ID: CWE-416
|
pdf_dict_put(fz_context *ctx, pdf_obj *obj, pdf_obj *key, pdf_obj *val)
static void
pdf_dict_get_put(fz_context *ctx, pdf_obj *obj, pdf_obj *key, pdf_obj *val, pdf_obj **old_val)
{
int i;
if (old_val)
*old_val = NULL;
RESOLVE(obj);
if (!OBJ_IS_DICT(obj))
fz_throw(ctx, FZ_ERROR_GENERIC, "not a dict (%s)", pdf_objkindstr(obj));
if (!val)
val = PDF_OBJ_NULL;
if (DICT(obj)->len > 100 && !(obj->flags & PDF_FLAGS_SORTED))
pdf_sort_dict(ctx, obj);
if (key < PDF_OBJ_NAME__LIMIT)
i = pdf_dict_find(ctx, obj, key);
else
i = pdf_dict_finds(ctx, obj, pdf_to_name(ctx, key));
prepare_object_for_alteration(ctx, obj, val);
if (i >= 0 && i < DICT(obj)->len)
{
if (DICT(obj)->items[i].v != val)
{
pdf_obj *d = DICT(obj)->items[i].v;
DICT(obj)->items[i].v = pdf_keep_obj(ctx, val);
{
pdf_obj *d = DICT(obj)->items[i].v;
DICT(obj)->items[i].v = pdf_keep_obj(ctx, val);
if (old_val)
*old_val = d;
else
pdf_drop_obj(ctx, d);
}
}
else
memmove(&DICT(obj)->items[i + 1],
&DICT(obj)->items[i],
(DICT(obj)->len - i) * sizeof(struct keyval));
DICT(obj)->items[i].k = pdf_keep_obj(ctx, key);
DICT(obj)->items[i].v = pdf_keep_obj(ctx, val);
DICT(obj)->len ++;
}
}
| 165,260
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: kg_seal(minor_status, context_handle, conf_req_flag, qop_req,
input_message_buffer, conf_state, output_message_buffer, toktype)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
int conf_req_flag;
gss_qop_t qop_req;
gss_buffer_t input_message_buffer;
int *conf_state;
gss_buffer_t output_message_buffer;
int toktype;
{
krb5_gss_ctx_id_rec *ctx;
krb5_error_code code;
krb5_context context;
output_message_buffer->length = 0;
output_message_buffer->value = NULL;
/* Only default qop or matching established cryptosystem is allowed.
There are NO EXTENSIONS to this set for AES and friends! The
new spec says "just use 0". The old spec plus extensions would
actually allow for certain non-zero values. Fix this to handle
them later. */
if (qop_req != 0) {
*minor_status = (OM_uint32) G_UNKNOWN_QOP;
return GSS_S_FAILURE;
}
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (! ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return(GSS_S_NO_CONTEXT);
}
context = ctx->k5_context;
switch (ctx->proto)
{
case 0:
code = make_seal_token_v1(context, ctx->enc, ctx->seq,
&ctx->seq_send, ctx->initiate,
input_message_buffer, output_message_buffer,
ctx->signalg, ctx->cksum_size, ctx->sealalg,
conf_req_flag, toktype, ctx->mech_used);
break;
case 1:
code = gss_krb5int_make_seal_token_v3(context, ctx,
input_message_buffer,
output_message_buffer,
conf_req_flag, toktype);
break;
default:
code = G_UNKNOWN_QOP; /* XXX */
break;
}
if (code) {
*minor_status = code;
save_error_info(*minor_status, context);
return(GSS_S_FAILURE);
}
if (conf_state)
*conf_state = conf_req_flag;
*minor_status = 0;
return(GSS_S_COMPLETE);
}
Commit Message: Fix gss_process_context_token() [CVE-2014-5352]
[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not
actually delete the context; that leaves the caller with a dangling
pointer and no way to know that it is invalid. Instead, mark the
context as terminated, and check for terminated contexts in the GSS
functions which expect established contexts. Also add checks in
export_sec_context and pseudo_random, and adjust t_prf.c for the
pseudo_random check.
ticket: 8055 (new)
target_version: 1.13.1
tags: pullup
CWE ID:
|
kg_seal(minor_status, context_handle, conf_req_flag, qop_req,
input_message_buffer, conf_state, output_message_buffer, toktype)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
int conf_req_flag;
gss_qop_t qop_req;
gss_buffer_t input_message_buffer;
int *conf_state;
gss_buffer_t output_message_buffer;
int toktype;
{
krb5_gss_ctx_id_rec *ctx;
krb5_error_code code;
krb5_context context;
output_message_buffer->length = 0;
output_message_buffer->value = NULL;
/* Only default qop or matching established cryptosystem is allowed.
There are NO EXTENSIONS to this set for AES and friends! The
new spec says "just use 0". The old spec plus extensions would
actually allow for certain non-zero values. Fix this to handle
them later. */
if (qop_req != 0) {
*minor_status = (OM_uint32) G_UNKNOWN_QOP;
return GSS_S_FAILURE;
}
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (ctx->terminated || !ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return(GSS_S_NO_CONTEXT);
}
context = ctx->k5_context;
switch (ctx->proto)
{
case 0:
code = make_seal_token_v1(context, ctx->enc, ctx->seq,
&ctx->seq_send, ctx->initiate,
input_message_buffer, output_message_buffer,
ctx->signalg, ctx->cksum_size, ctx->sealalg,
conf_req_flag, toktype, ctx->mech_used);
break;
case 1:
code = gss_krb5int_make_seal_token_v3(context, ctx,
input_message_buffer,
output_message_buffer,
conf_req_flag, toktype);
break;
default:
code = G_UNKNOWN_QOP; /* XXX */
break;
}
if (code) {
*minor_status = code;
save_error_info(*minor_status, context);
return(GSS_S_FAILURE);
}
if (conf_state)
*conf_state = conf_req_flag;
*minor_status = 0;
return(GSS_S_COMPLETE);
}
| 166,817
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BrowserCommandController::TabDetachedAt(TabContents* contents, int index) {
RemoveInterstitialObservers(contents);
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void BrowserCommandController::TabDetachedAt(TabContents* contents, int index) {
void BrowserCommandController::TabDetachedAt(WebContents* contents, int index) {
RemoveInterstitialObservers(contents);
}
| 171,511
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: fpAcc(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 = cc;
uint8 *cp = (uint8 *) cp0;
uint8 *tmp = (uint8 *)_TIFFmalloc(cc);
assert((cc%(bps*stride))==0);
if (!tmp)
return;
while (count > stride) {
REPEAT4(stride, cp[stride] =
(unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++)
count -= stride;
}
_TIFFmemcpy(tmp, cp0, cc);
cp = (uint8 *) cp0;
for (count = 0; count < wc; count++) {
uint32 byte;
for (byte = 0; byte < bps; byte++) {
#if WORDS_BIGENDIAN
cp[bps * count + byte] = tmp[byte * wc + count];
#else
cp[bps * count + byte] =
tmp[(bps - byte - 1) * wc + count];
#endif
}
}
_TIFFfree(tmp);
}
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
|
fpAcc(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 = cc;
uint8 *cp = (uint8 *) cp0;
uint8 *tmp = (uint8 *)_TIFFmalloc(cc);
if(cc%(bps*stride)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "fpAcc",
"%s", "cc%(bps*stride))!=0");
return 0;
}
if (!tmp)
return 0;
while (count > stride) {
REPEAT4(stride, cp[stride] =
(unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++)
count -= stride;
}
_TIFFmemcpy(tmp, cp0, cc);
cp = (uint8 *) cp0;
for (count = 0; count < wc; count++) {
uint32 byte;
for (byte = 0; byte < bps; byte++) {
#if WORDS_BIGENDIAN
cp[bps * count + byte] = tmp[byte * wc + count];
#else
cp[bps * count + byte] =
tmp[(bps - byte - 1) * wc + count];
#endif
}
}
_TIFFfree(tmp);
return 1;
}
| 166,880
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static const char *lua_authz_parse(cmd_parms *cmd, const char *require_line,
const void **parsed_require_line)
{
const char *provider_name;
lua_authz_provider_spec *spec;
apr_pool_userdata_get((void**)&provider_name, AUTHZ_PROVIDER_NAME_NOTE,
cmd->temp_pool);
ap_assert(provider_name != NULL);
spec = apr_hash_get(lua_authz_providers, provider_name, APR_HASH_KEY_STRING);
ap_assert(spec != NULL);
if (require_line && *require_line) {
const char *arg;
spec->args = apr_array_make(cmd->pool, 2, sizeof(const char *));
while ((arg = ap_getword_conf(cmd->pool, &require_line)) && *arg) {
APR_ARRAY_PUSH(spec->args, const char *) = arg;
}
}
*parsed_require_line = spec;
return NULL;
}
Commit Message: Merge r1642499 from trunk:
*) SECURITY: CVE-2014-8109 (cve.mitre.org)
mod_lua: Fix handling of the Require line when a LuaAuthzProvider is
used in multiple Require directives with different arguments.
PR57204 [Edward Lu <Chaosed0 gmail.com>]
Submitted By: Edward Lu
Committed By: covener
Submitted by: covener
Reviewed/backported by: jim
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x@1642861 13f79535-47bb-0310-9956-ffa450edef68
CWE ID: CWE-264
|
static const char *lua_authz_parse(cmd_parms *cmd, const char *require_line,
const void **parsed_require_line)
{
const char *provider_name;
lua_authz_provider_spec *spec;
lua_authz_provider_func *func = apr_pcalloc(cmd->pool, sizeof(lua_authz_provider_func));
apr_pool_userdata_get((void**)&provider_name, AUTHZ_PROVIDER_NAME_NOTE,
cmd->temp_pool);
ap_assert(provider_name != NULL);
spec = apr_hash_get(lua_authz_providers, provider_name, APR_HASH_KEY_STRING);
ap_assert(spec != NULL);
func->spec = spec;
if (require_line && *require_line) {
const char *arg;
func->args = apr_array_make(cmd->pool, 2, sizeof(const char *));
while ((arg = ap_getword_conf(cmd->pool, &require_line)) && *arg) {
APR_ARRAY_PUSH(func->args, const char *) = arg;
}
}
*parsed_require_line = func;
return NULL;
}
| 166,251
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jas_stream_read(jas_stream_t *stream, void *buf, int cnt)
{
int n;
int c;
char *bufptr;
bufptr = buf;
n = 0;
while (n < cnt) {
if ((c = jas_stream_getc(stream)) == EOF) {
return n;
}
*bufptr++ = c;
++n;
}
return n;
}
Commit Message: Made some changes to the I/O stream library for memory streams.
There were a number of potential problems due to the possibility
of integer overflow.
Changed some integral types to the larger types size_t or ssize_t.
For example, the function mem_resize now takes the buffer size parameter
as a size_t.
Added a new function jas_stream_memopen2, which takes a
buffer size specified as a size_t instead of an int.
This can be used in jas_image_cmpt_create to avoid potential
overflow problems.
Added a new function jas_deprecated to warn about reliance on
deprecated library behavior.
CWE ID: CWE-190
|
int jas_stream_read(jas_stream_t *stream, void *buf, int cnt)
{
int n;
int c;
char *bufptr;
if (cnt < 0) {
jas_deprecated("negative count for jas_stream_read");
}
bufptr = buf;
n = 0;
while (n < cnt) {
if ((c = jas_stream_getc(stream)) == EOF) {
return n;
}
*bufptr++ = c;
++n;
}
return n;
}
| 168,747
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_,
const struct isakmp_gen *ext, u_int oprop_length,
const u_char *ep, int depth)
{
const struct ikev2_p *p;
struct ikev2_p prop;
u_int prop_length;
const u_char *cp;
int i;
int tcount;
u_char np;
struct isakmp_gen e;
u_int item_len;
p = (const struct ikev2_p *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&prop, ext, sizeof(prop));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical);
/*
* ikev2_sa_print() guarantees that this is >= 4.
*/
prop_length = oprop_length - 4;
ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u",
prop.p_no, PROTOIDSTR(prop.prot_id),
prop.num_t, oprop_length));
cp = (const u_char *)(p + 1);
if (prop.spi_size) {
if (prop_length < prop.spi_size)
goto toolong;
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size))
goto trunc;
cp += prop.spi_size;
prop_length -= prop.spi_size;
}
/*
* Print the transforms.
*/
tcount = 0;
for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) {
tcount++;
ext = (const struct isakmp_gen *)cp;
if (prop_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
goto trunc;
if (prop_length < item_len)
goto toolong;
ND_TCHECK2(*cp, item_len);
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
if (np == ISAKMP_NPTYPE_T) {
cp = ikev2_t_print(ndo, tcount, ext, item_len, ep);
if (cp == NULL) {
/* error, already reported */
return NULL;
}
} else {
ND_PRINT((ndo, "%s", NPSTR(np)));
cp += item_len;
}
ND_PRINT((ndo,")"));
depth--;
prop_length -= item_len;
}
return cp;
toolong:
/*
* Skip the rest of the proposal.
*/
cp += prop_length;
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
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_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_,
const struct isakmp_gen *ext, u_int oprop_length,
const u_char *ep, int depth)
{
const struct ikev2_p *p;
struct ikev2_p prop;
u_int prop_length;
const u_char *cp;
int i;
int tcount;
u_char np;
struct isakmp_gen e;
u_int item_len;
p = (const struct ikev2_p *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&prop, ext, sizeof(prop));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical);
/*
* ikev2_sa_print() guarantees that this is >= 4.
*/
prop_length = oprop_length - 4;
ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u",
prop.p_no, PROTOIDSTR(prop.prot_id),
prop.num_t, oprop_length));
cp = (const u_char *)(p + 1);
if (prop.spi_size) {
if (prop_length < prop.spi_size)
goto toolong;
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size))
goto trunc;
cp += prop.spi_size;
prop_length -= prop.spi_size;
}
/*
* Print the transforms.
*/
tcount = 0;
for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) {
tcount++;
ext = (const struct isakmp_gen *)cp;
if (prop_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
goto trunc;
if (prop_length < item_len)
goto toolong;
ND_TCHECK2(*cp, item_len);
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
if (np == ISAKMP_NPTYPE_T) {
cp = ikev2_t_print(ndo, tcount, ext, item_len, ep);
if (cp == NULL) {
/* error, already reported */
return NULL;
}
} else {
ND_PRINT((ndo, "%s", NPSTR(np)));
cp += item_len;
}
ND_PRINT((ndo,")"));
depth--;
prop_length -= item_len;
}
return cp;
toolong:
/*
* Skip the rest of the proposal.
*/
cp += prop_length;
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return NULL;
}
| 167,800
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: rdpCredssp* credssp_new(freerdp* instance, rdpTransport* transport, rdpSettings* settings)
{
rdpCredssp* credssp;
credssp = (rdpCredssp*) malloc(sizeof(rdpCredssp));
ZeroMemory(credssp, sizeof(rdpCredssp));
if (credssp != NULL)
{
HKEY hKey;
LONG status;
DWORD dwType;
DWORD dwSize;
credssp->instance = instance;
credssp->settings = settings;
credssp->server = settings->ServerMode;
credssp->transport = transport;
credssp->send_seq_num = 0;
credssp->recv_seq_num = 0;
ZeroMemory(&credssp->negoToken, sizeof(SecBuffer));
ZeroMemory(&credssp->pubKeyAuth, sizeof(SecBuffer));
ZeroMemory(&credssp->authInfo, sizeof(SecBuffer));
if (credssp->server)
{
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"),
0, KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status == ERROR_SUCCESS)
{
status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, NULL, &dwSize);
if (status == ERROR_SUCCESS)
{
credssp->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR));
status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType,
(BYTE*) credssp->SspiModule, &dwSize);
if (status == ERROR_SUCCESS)
{
_tprintf(_T("Using SSPI Module: %s\n"), credssp->SspiModule);
RegCloseKey(hKey);
}
}
}
}
}
return credssp;
}
Commit Message: nla: invalidate sec handle after creation
If sec pointer isn't invalidated after creation it is not possible
to check if the upper and lower pointers are valid.
This fixes a segfault in the server part if the client disconnects before
the authentication was finished.
CWE ID: CWE-476
|
rdpCredssp* credssp_new(freerdp* instance, rdpTransport* transport, rdpSettings* settings)
{
rdpCredssp* credssp;
credssp = (rdpCredssp*) malloc(sizeof(rdpCredssp));
ZeroMemory(credssp, sizeof(rdpCredssp));
if (credssp != NULL)
{
HKEY hKey;
LONG status;
DWORD dwType;
DWORD dwSize;
credssp->instance = instance;
credssp->settings = settings;
credssp->server = settings->ServerMode;
credssp->transport = transport;
credssp->send_seq_num = 0;
credssp->recv_seq_num = 0;
ZeroMemory(&credssp->negoToken, sizeof(SecBuffer));
ZeroMemory(&credssp->pubKeyAuth, sizeof(SecBuffer));
ZeroMemory(&credssp->authInfo, sizeof(SecBuffer));
SecInvalidateHandle(&credssp->context);
if (credssp->server)
{
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"),
0, KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status == ERROR_SUCCESS)
{
status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, NULL, &dwSize);
if (status == ERROR_SUCCESS)
{
credssp->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR));
status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType,
(BYTE*) credssp->SspiModule, &dwSize);
if (status == ERROR_SUCCESS)
{
_tprintf(_T("Using SSPI Module: %s\n"), credssp->SspiModule);
RegCloseKey(hKey);
}
}
}
}
}
return credssp;
}
| 167,599
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TPM_RC StartAuthSession(TSS2_SYS_CONTEXT *sapi_context, SESSION *session )
{
TPM_RC rval;
TPM2B_ENCRYPTED_SECRET key;
char label[] = "ATH";
UINT16 bytes;
int i;
key.t.size = 0;
if( session->nonceOlder.t.size == 0 )
{
/* this is an internal routine to TSS and should be removed */
session->nonceOlder.t.size = GetDigestSize( TPM_ALG_SHA1 );
for( i = 0; i < session->nonceOlder.t.size; i++ )
session->nonceOlder.t.buffer[i] = 0;
}
session->nonceNewer.t.size = session->nonceOlder.t.size;
rval = Tss2_Sys_StartAuthSession( sapi_context, session->tpmKey, session->bind, 0,
&( session->nonceOlder ), &( session->encryptedSalt ), session->sessionType,
&( session->symmetric ), session->authHash, &( session->sessionHandle ),
&( session->nonceNewer ), 0 );
if( rval == TPM_RC_SUCCESS )
{
if( session->tpmKey == TPM_RH_NULL )
session->salt.t.size = 0;
if( session->bind == TPM_RH_NULL )
session->authValueBind.t.size = 0;
if( session->tpmKey == TPM_RH_NULL && session->bind == TPM_RH_NULL )
{
session->sessionKey.b.size = 0;
}
else
{
bool result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->authValueBind.b ) );
if (!result)
{
return TSS2_SYS_RC_BAD_VALUE;
}
result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->salt.b ) );
if (!result)
{
return TSS2_SYS_RC_BAD_VALUE;
}
bytes = GetDigestSize( session->authHash );
if( key.t.size == 0 )
{
session->sessionKey.t.size = 0;
}
else
{
rval = tpm_kdfa(sapi_context, session->authHash, &(key.b), label, &( session->nonceNewer.b ),
&( session->nonceOlder.b ), bytes * 8, (TPM2B_MAX_BUFFER *)&( session->sessionKey ) );
}
if( rval != TPM_RC_SUCCESS )
{
return( TSS2_APP_RC_CREATE_SESSION_KEY_FAILED );
}
}
session->nonceTpmDecrypt.b.size = 0;
session->nonceTpmEncrypt.b.size = 0;
session->nvNameChanged = 0;
}
return rval;
}
Commit Message: kdfa: use openssl for hmac not tpm
While not reachable in the current code base tools, a potential
security bug lurked in tpm_kdfa().
If using that routine for an hmac authorization, the hmac was
calculated using the tpm. A user of an object wishing to
authenticate via hmac, would expect that the password is never
sent to the tpm. However, since the hmac calculation relies on
password, and is performed by the tpm, the password ends up
being sent in plain text to the tpm.
The fix is to use openssl to generate the hmac on the host.
Fixes: CVE-2017-7524
Signed-off-by: William Roberts <william.c.roberts@intel.com>
CWE ID: CWE-522
|
static TPM_RC StartAuthSession(TSS2_SYS_CONTEXT *sapi_context, SESSION *session )
{
TPM_RC rval;
TPM2B_ENCRYPTED_SECRET key;
char label[] = "ATH";
UINT16 bytes;
int i;
key.t.size = 0;
if( session->nonceOlder.t.size == 0 )
{
/* this is an internal routine to TSS and should be removed */
session->nonceOlder.t.size = GetDigestSize( TPM_ALG_SHA1 );
for( i = 0; i < session->nonceOlder.t.size; i++ )
session->nonceOlder.t.buffer[i] = 0;
}
session->nonceNewer.t.size = session->nonceOlder.t.size;
rval = Tss2_Sys_StartAuthSession( sapi_context, session->tpmKey, session->bind, 0,
&( session->nonceOlder ), &( session->encryptedSalt ), session->sessionType,
&( session->symmetric ), session->authHash, &( session->sessionHandle ),
&( session->nonceNewer ), 0 );
if( rval == TPM_RC_SUCCESS )
{
if( session->tpmKey == TPM_RH_NULL )
session->salt.t.size = 0;
if( session->bind == TPM_RH_NULL )
session->authValueBind.t.size = 0;
if( session->tpmKey == TPM_RH_NULL && session->bind == TPM_RH_NULL )
{
session->sessionKey.b.size = 0;
}
else
{
bool result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->authValueBind.b ) );
if (!result)
{
return TSS2_SYS_RC_BAD_VALUE;
}
result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->salt.b ) );
if (!result)
{
return TSS2_SYS_RC_BAD_VALUE;
}
bytes = GetDigestSize( session->authHash );
if( key.t.size == 0 )
{
session->sessionKey.t.size = 0;
}
else
{
rval = tpm_kdfa(session->authHash, &(key.b), label, &( session->nonceNewer.b ),
&( session->nonceOlder.b ), bytes * 8, (TPM2B_MAX_BUFFER *)&( session->sessionKey ) );
}
if( rval != TPM_RC_SUCCESS )
{
return( TSS2_APP_RC_CREATE_SESSION_KEY_FAILED );
}
}
session->nonceTpmDecrypt.b.size = 0;
session->nonceTpmEncrypt.b.size = 0;
session->nvNameChanged = 0;
}
return rval;
}
| 168,266
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int get_debug_info(struct PE_(r_bin_pe_obj_t)* bin, PE_(image_debug_directory_entry)* dbg_dir_entry, ut8* dbg_data, int dbg_data_len, SDebugInfo* res) {
#define SIZEOF_FILE_NAME 255
int i = 0;
const char* basename;
if (!dbg_data) {
return 0;
}
switch (dbg_dir_entry->Type) {
case IMAGE_DEBUG_TYPE_CODEVIEW:
if (!strncmp ((char*) dbg_data, "RSDS", 4)) {
SCV_RSDS_HEADER rsds_hdr;
init_rsdr_hdr (&rsds_hdr);
if (!get_rsds (dbg_data, dbg_data_len, &rsds_hdr)) {
bprintf ("Warning: Cannot read PE debug info\n");
return 0;
}
snprintf (res->guidstr, GUIDSTR_LEN,
"%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x%x",
rsds_hdr.guid.data1,
rsds_hdr.guid.data2,
rsds_hdr.guid.data3,
rsds_hdr.guid.data4[0],
rsds_hdr.guid.data4[1],
rsds_hdr.guid.data4[2],
rsds_hdr.guid.data4[3],
rsds_hdr.guid.data4[4],
rsds_hdr.guid.data4[5],
rsds_hdr.guid.data4[6],
rsds_hdr.guid.data4[7],
rsds_hdr.age);
basename = r_file_basename ((char*) rsds_hdr.file_name);
strncpy (res->file_name, (const char*)
basename, sizeof (res->file_name));
res->file_name[sizeof (res->file_name) - 1] = 0;
rsds_hdr.free ((struct SCV_RSDS_HEADER*) &rsds_hdr);
} else if (strncmp ((const char*) dbg_data, "NB10", 4) == 0) {
SCV_NB10_HEADER nb10_hdr;
init_cv_nb10_header (&nb10_hdr);
get_nb10 (dbg_data, &nb10_hdr);
snprintf (res->guidstr, sizeof (res->guidstr),
"%x%x", nb10_hdr.timestamp, nb10_hdr.age);
strncpy (res->file_name, (const char*)
nb10_hdr.file_name, sizeof(res->file_name) - 1);
res->file_name[sizeof (res->file_name) - 1] = 0;
nb10_hdr.free ((struct SCV_NB10_HEADER*) &nb10_hdr);
} else {
bprintf ("CodeView section not NB10 or RSDS\n");
return 0;
}
break;
default:
return 0;
}
while (i < 33) {
res->guidstr[i] = toupper ((int) res->guidstr[i]);
i++;
}
return 1;
}
Commit Message: Fix crash in pe
CWE ID: CWE-125
|
static int get_debug_info(struct PE_(r_bin_pe_obj_t)* bin, PE_(image_debug_directory_entry)* dbg_dir_entry, ut8* dbg_data, int dbg_data_len, SDebugInfo* res) {
#define SIZEOF_FILE_NAME 255
int i = 0;
const char* basename;
if (!dbg_data) {
return 0;
}
switch (dbg_dir_entry->Type) {
case IMAGE_DEBUG_TYPE_CODEVIEW:
if (!strncmp ((char*) dbg_data, "RSDS", 4)) {
SCV_RSDS_HEADER rsds_hdr;
init_rsdr_hdr (&rsds_hdr);
if (!get_rsds (dbg_data, dbg_data_len, &rsds_hdr)) {
bprintf ("Warning: Cannot read PE debug info\n");
return 0;
}
snprintf (res->guidstr, GUIDSTR_LEN,
"%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x%x",
rsds_hdr.guid.data1,
rsds_hdr.guid.data2,
rsds_hdr.guid.data3,
rsds_hdr.guid.data4[0],
rsds_hdr.guid.data4[1],
rsds_hdr.guid.data4[2],
rsds_hdr.guid.data4[3],
rsds_hdr.guid.data4[4],
rsds_hdr.guid.data4[5],
rsds_hdr.guid.data4[6],
rsds_hdr.guid.data4[7],
rsds_hdr.age);
basename = r_file_basename ((char*) rsds_hdr.file_name);
strncpy (res->file_name, (const char*)
basename, sizeof (res->file_name));
res->file_name[sizeof (res->file_name) - 1] = 0;
rsds_hdr.free ((struct SCV_RSDS_HEADER*) &rsds_hdr);
} else if (strncmp ((const char*) dbg_data, "NB10", 4) == 0) {
if (dbg_data_len < 20) {
eprintf ("Truncated NB10 entry, not enough data to parse\n");
return 0;
}
SCV_NB10_HEADER nb10_hdr = {{0}};
init_cv_nb10_header (&nb10_hdr);
get_nb10 (dbg_data, &nb10_hdr);
snprintf (res->guidstr, sizeof (res->guidstr),
"%x%x", nb10_hdr.timestamp, nb10_hdr.age);
res->file_name[0] = 0;
if (nb10_hdr.file_name) {
strncpy (res->file_name, (const char*)
nb10_hdr.file_name, sizeof (res->file_name) - 1);
}
res->file_name[sizeof (res->file_name) - 1] = 0;
nb10_hdr.free ((struct SCV_NB10_HEADER*) &nb10_hdr);
} else {
bprintf ("CodeView section not NB10 or RSDS\n");
return 0;
}
break;
default:
return 0;
}
while (i < 33) {
res->guidstr[i] = toupper ((int) res->guidstr[i]);
i++;
}
return 1;
}
| 169,228
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature,
void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
const EVP_MD *type;
unsigned char *buf_in=NULL;
int ret= -1,i,inl;
EVP_MD_CTX_init(&ctx);
i=OBJ_obj2nid(a->algorithm);
type=EVP_get_digestbyname(OBJ_nid2sn(i));
if (!EVP_VerifyInit_ex(&ctx,type, NULL))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data,
(unsigned int)signature->length,pkey) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
Commit Message:
CWE ID: CWE-310
|
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature,
void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
const EVP_MD *type;
unsigned char *buf_in=NULL;
int ret= -1,i,inl;
if (!pkey)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
EVP_MD_CTX_init(&ctx);
i=OBJ_obj2nid(a->algorithm);
type=EVP_get_digestbyname(OBJ_nid2sn(i));
if (!EVP_VerifyInit_ex(&ctx,type, NULL))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data,
(unsigned int)signature->length,pkey) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
| 164,792
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock)
{
struct grub_ext2_data *data = node->data;
struct grub_ext2_inode *inode = &node->inode;
int blknr = -1;
unsigned int blksz = EXT2_BLOCK_SIZE (data);
int log2_blksz = LOG2_EXT2_BLOCK_SIZE (data);
if (grub_le_to_cpu32(inode->flags) & EXT4_EXTENTS_FLAG)
{
#ifndef _MSC_VER
char buf[EXT2_BLOCK_SIZE (data)];
#else
char * buf = grub_malloc (EXT2_BLOCK_SIZE(data));
#endif
struct grub_ext4_extent_header *leaf;
struct grub_ext4_extent *ext;
int i;
leaf = grub_ext4_find_leaf (data, buf,
(struct grub_ext4_extent_header *) inode->blocks.dir_blocks,
fileblock);
if (! leaf)
{
grub_error (GRUB_ERR_BAD_FS, "invalid extent");
return -1;
}
ext = (struct grub_ext4_extent *) (leaf + 1);
for (i = 0; i < grub_le_to_cpu16 (leaf->entries); i++)
{
if (fileblock < grub_le_to_cpu32 (ext[i].block))
break;
}
if (--i >= 0)
{
fileblock -= grub_le_to_cpu32 (ext[i].block);
if (fileblock >= grub_le_to_cpu16 (ext[i].len))
return 0;
else
{
grub_disk_addr_t start;
start = grub_le_to_cpu16 (ext[i].start_hi);
start = (start << 32) + grub_le_to_cpu32 (ext[i].start);
return fileblock + start;
}
}
else
{
grub_error (GRUB_ERR_BAD_FS, "something wrong with extent");
return -1;
}
}
/* Direct blocks. */
if (fileblock < INDIRECT_BLOCKS) {
blknr = grub_le_to_cpu32 (inode->blocks.dir_blocks[fileblock]);
/* Indirect. */
} else if (fileblock < INDIRECT_BLOCKS + blksz / 4)
{
grub_uint32_t *indir;
indir = grub_malloc (blksz);
if (! indir)
return grub_errno;
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (inode->blocks.indir_block))
<< log2_blksz,
0, blksz, indir))
return grub_errno;
blknr = grub_le_to_cpu32 (indir[fileblock - INDIRECT_BLOCKS]);
grub_free (indir);
}
/* Double indirect. */
else if (fileblock < (grub_disk_addr_t)(INDIRECT_BLOCKS + blksz / 4) \
* (grub_disk_addr_t)(blksz / 4 + 1))
{
unsigned int perblock = blksz / 4;
unsigned int rblock = fileblock - (INDIRECT_BLOCKS
+ blksz / 4);
grub_uint32_t *indir;
indir = grub_malloc (blksz);
if (! indir)
return grub_errno;
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (inode->blocks.double_indir_block))
<< log2_blksz,
0, blksz, indir))
return grub_errno;
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (indir[rblock / perblock]))
<< log2_blksz,
0, blksz, indir))
return grub_errno;
blknr = grub_le_to_cpu32 (indir[rblock % perblock]);
grub_free (indir);
}
/* triple indirect. */
else
{
grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
"ext2fs doesn't support triple indirect blocks");
}
return blknr;
}
Commit Message: Fix #7723 - crash in ext2 GRUB code because of variable size array in stack
CWE ID: CWE-119
|
grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock)
{
struct grub_ext2_data *data = node->data;
struct grub_ext2_inode *inode = &node->inode;
int blknr = -1;
unsigned int blksz = EXT2_BLOCK_SIZE (data);
int log2_blksz = LOG2_EXT2_BLOCK_SIZE (data);
if (grub_le_to_cpu32(inode->flags) & EXT4_EXTENTS_FLAG)
{
char * buf = grub_malloc (EXT2_BLOCK_SIZE (data));
if (!buf) {
return -1;
}
struct grub_ext4_extent_header *leaf;
struct grub_ext4_extent *ext;
int i;
leaf = grub_ext4_find_leaf (data, buf,
(struct grub_ext4_extent_header *) inode->blocks.dir_blocks,
fileblock);
if (! leaf)
{
grub_error (GRUB_ERR_BAD_FS, "invalid extent");
free (buf);
return -1;
}
ext = (struct grub_ext4_extent *) (leaf + 1);
for (i = 0; i < grub_le_to_cpu16 (leaf->entries); i++)
{
if (fileblock < grub_le_to_cpu32 (ext[i].block))
break;
}
if (--i >= 0)
{
fileblock -= grub_le_to_cpu32 (ext[i].block);
if (fileblock >= grub_le_to_cpu16 (ext[i].len)) {
free (buf);
return 0;
} else
{
grub_disk_addr_t start;
start = grub_le_to_cpu16 (ext[i].start_hi);
start = (start << 32) + grub_le_to_cpu32 (ext[i].start);
free (buf);
return fileblock + start;
}
}
else
{
grub_error (GRUB_ERR_BAD_FS, "something wrong with extent");
free (buf);
return -1;
}
free (buf);
}
/* Direct blocks. */
if (fileblock < INDIRECT_BLOCKS) {
blknr = grub_le_to_cpu32 (inode->blocks.dir_blocks[fileblock]);
/* Indirect. */
} else if (fileblock < INDIRECT_BLOCKS + blksz / 4)
{
grub_uint32_t *indir;
indir = grub_malloc (blksz);
if (! indir) {
return grub_errno;
}
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (inode->blocks.indir_block))
<< log2_blksz,
0, blksz, indir)) {
return grub_errno;
}
blknr = grub_le_to_cpu32 (indir[fileblock - INDIRECT_BLOCKS]);
grub_free (indir);
}
/* Double indirect. */
else if (fileblock < (grub_disk_addr_t)(INDIRECT_BLOCKS + blksz / 4) \
* (grub_disk_addr_t)(blksz / 4 + 1))
{
unsigned int perblock = blksz / 4;
unsigned int rblock = fileblock - (INDIRECT_BLOCKS
+ blksz / 4);
grub_uint32_t *indir;
indir = grub_malloc (blksz);
if (! indir) {
return grub_errno;
}
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (inode->blocks.double_indir_block))
<< log2_blksz,
0, blksz, indir)) {
return grub_errno;
}
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (indir[rblock / perblock]))
<< log2_blksz,
0, blksz, indir)) {
return grub_errno;
}
blknr = grub_le_to_cpu32 (indir[rblock % perblock]);
grub_free (indir);
}
/* triple indirect. */
else
{
grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
"ext2fs doesn't support triple indirect blocks");
}
return blknr;
}
| 168,087
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long long Cluster::GetElementSize() const
{
return m_element_size;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long long Cluster::GetElementSize() const
| 174,312
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: tight_detect_smooth_image24(VncState *vs, int w, int h)
{
int off;
int x, y, d, dx;
unsigned int c;
unsigned int stats[256];
int pixels = 0;
int pix, left[3];
unsigned int errors;
unsigned char *buf = vs->tight.tight.buffer;
/*
* If client is big-endian, color samples begin from the second
* byte (offset 1) of a 32-bit pixel value.
*/
off = !!(vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG);
memset(stats, 0, sizeof (stats));
for (y = 0, x = 0; y < h && x < w;) {
for (d = 0; d < h - y && d < w - x - VNC_TIGHT_DETECT_SUBROW_WIDTH;
d++) {
for (c = 0; c < 3; c++) {
left[c] = buf[((y+d)*w+x+d)*4+off+c] & 0xFF;
}
for (dx = 1; dx <= VNC_TIGHT_DETECT_SUBROW_WIDTH; dx++) {
for (c = 0; c < 3; c++) {
pix = buf[((y+d)*w+x+d+dx)*4+off+c] & 0xFF;
stats[abs(pix - left[c])]++;
left[c] = pix;
}
pixels++;
}
}
if (w > h) {
x += h;
y = 0;
} else {
x = 0;
y += w;
}
}
/* 95% smooth or more ... */
if (stats[0] * 33 / pixels >= 95) {
return 0;
}
errors = 0;
for (c = 1; c < 8; c++) {
errors += stats[c] * (c * c);
if (stats[c] == 0 || stats[c] > stats[c-1] * 2) {
return 0;
}
}
for (; c < 256; c++) {
errors += stats[c] * (c * c);
}
errors /= (pixels * 3 - stats[0]);
return errors;
}
Commit Message:
CWE ID: CWE-125
|
tight_detect_smooth_image24(VncState *vs, int w, int h)
{
int off;
int x, y, d, dx;
unsigned int c;
unsigned int stats[256];
int pixels = 0;
int pix, left[3];
unsigned int errors;
unsigned char *buf = vs->tight.tight.buffer;
/*
* If client is big-endian, color samples begin from the second
* byte (offset 1) of a 32-bit pixel value.
*/
off = vs->client_be;
memset(stats, 0, sizeof (stats));
for (y = 0, x = 0; y < h && x < w;) {
for (d = 0; d < h - y && d < w - x - VNC_TIGHT_DETECT_SUBROW_WIDTH;
d++) {
for (c = 0; c < 3; c++) {
left[c] = buf[((y+d)*w+x+d)*4+off+c] & 0xFF;
}
for (dx = 1; dx <= VNC_TIGHT_DETECT_SUBROW_WIDTH; dx++) {
for (c = 0; c < 3; c++) {
pix = buf[((y+d)*w+x+d+dx)*4+off+c] & 0xFF;
stats[abs(pix - left[c])]++;
left[c] = pix;
}
pixels++;
}
}
if (w > h) {
x += h;
y = 0;
} else {
x = 0;
y += w;
}
}
/* 95% smooth or more ... */
if (stats[0] * 33 / pixels >= 95) {
return 0;
}
errors = 0;
for (c = 1; c < 8; c++) {
errors += stats[c] * (c * c);
if (stats[c] == 0 || stats[c] > stats[c-1] * 2) {
return 0;
}
}
for (; c < 256; c++) {
errors += stats[c] * (c * c);
}
errors /= (pixels * 3 - stats[0]);
return errors;
}
| 165,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: cib_notify_client(gpointer key, gpointer value, gpointer user_data)
{
const char *type = NULL;
gboolean do_send = FALSE;
cib_client_t *client = value;
xmlNode *update_msg = user_data;
CRM_CHECK(client != NULL, return TRUE);
CRM_CHECK(update_msg != NULL, return TRUE);
if (client->ipc == NULL) {
crm_warn("Skipping client with NULL channel");
return FALSE;
}
type = crm_element_value(update_msg, F_SUBTYPE);
CRM_LOG_ASSERT(type != NULL);
if (client->diffs && safe_str_eq(type, T_CIB_DIFF_NOTIFY)) {
do_send = TRUE;
} else if (client->replace && safe_str_eq(type, T_CIB_REPLACE_NOTIFY)) {
do_send = TRUE;
} else if (client->confirmations && safe_str_eq(type, T_CIB_UPDATE_CONFIRM)) {
do_send = TRUE;
} else if (client->pre_notify && safe_str_eq(type, T_CIB_PRE_NOTIFY)) {
do_send = TRUE;
} else if (client->post_notify && safe_str_eq(type, T_CIB_POST_NOTIFY)) {
do_send = TRUE;
}
if (do_send) {
if (client->ipc) {
if(crm_ipcs_send(client->ipc, 0, update_msg, TRUE) == FALSE) {
crm_warn("Notification of client %s/%s failed", client->name, client->id);
}
#ifdef HAVE_GNUTLS_GNUTLS_H
} else if (client->session) {
crm_debug("Sent %s notification to client %s/%s", type, client->name, client->id);
crm_send_remote_msg(client->session, update_msg, client->encrypted);
#endif
} else {
crm_err("Unknown transport for %s", client->name);
}
}
return FALSE;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
|
cib_notify_client(gpointer key, gpointer value, gpointer user_data)
{
const char *type = NULL;
gboolean do_send = FALSE;
cib_client_t *client = value;
xmlNode *update_msg = user_data;
CRM_CHECK(client != NULL, return TRUE);
CRM_CHECK(update_msg != NULL, return TRUE);
if (client->ipc == NULL && client->session == NULL) {
crm_warn("Skipping client with NULL channel");
return FALSE;
}
type = crm_element_value(update_msg, F_SUBTYPE);
CRM_LOG_ASSERT(type != NULL);
if (client->diffs && safe_str_eq(type, T_CIB_DIFF_NOTIFY)) {
do_send = TRUE;
} else if (client->replace && safe_str_eq(type, T_CIB_REPLACE_NOTIFY)) {
do_send = TRUE;
} else if (client->confirmations && safe_str_eq(type, T_CIB_UPDATE_CONFIRM)) {
do_send = TRUE;
} else if (client->pre_notify && safe_str_eq(type, T_CIB_PRE_NOTIFY)) {
do_send = TRUE;
} else if (client->post_notify && safe_str_eq(type, T_CIB_POST_NOTIFY)) {
do_send = TRUE;
}
if (do_send) {
if (client->ipc) {
if(crm_ipcs_send(client->ipc, 0, update_msg, TRUE) == FALSE) {
crm_warn("Notification of client %s/%s failed", client->name, client->id);
}
#ifdef HAVE_GNUTLS_GNUTLS_H
} else if (client->session) {
crm_debug("Sent %s notification to client %s/%s", type, client->name, client->id);
crm_send_remote_msg(client->session, update_msg, client->encrypted);
#endif
} else {
crm_err("Unknown transport for %s", client->name);
}
}
return FALSE;
}
| 166,146
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void GpuProcessHost::OnChannelEstablished(
const IPC::ChannelHandle& channel_handle) {
DCHECK(gpu_process_);
EstablishChannelCallback callback = channel_requests_.front();
channel_requests_.pop();
if (!channel_handle.name.empty() &&
!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed()) {
Send(new GpuMsg_CloseChannel(channel_handle));
EstablishChannelError(callback,
IPC::ChannelHandle(),
base::kNullProcessHandle,
content::GPUInfo());
RouteOnUIThread(GpuHostMsg_OnLogMessage(
logging::LOG_WARNING,
"WARNING",
"Hardware acceleration is unavailable."));
return;
}
callback.Run(channel_handle, gpu_process_,
GpuDataManagerImpl::GetInstance()->GetGPUInfo());
}
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 GpuProcessHost::OnChannelEstablished(
const IPC::ChannelHandle& channel_handle) {
EstablishChannelCallback callback = channel_requests_.front();
channel_requests_.pop();
if (!channel_handle.name.empty() &&
!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed()) {
Send(new GpuMsg_CloseChannel(channel_handle));
EstablishChannelError(callback,
IPC::ChannelHandle(),
base::kNullProcessHandle,
content::GPUInfo());
RouteOnUIThread(GpuHostMsg_OnLogMessage(
logging::LOG_WARNING,
"WARNING",
"Hardware acceleration is unavailable."));
return;
}
callback.Run(channel_handle,
GpuDataManagerImpl::GetInstance()->GetGPUInfo());
}
| 170,922
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: Gfx::Gfx(XRef *xrefA, OutputDev *outA, int pageNum, Dict *resDict, Catalog *catalogA,
double hDPI, double vDPI, PDFRectangle *box,
PDFRectangle *cropBox, int rotate,
GBool (*abortCheckCbkA)(void *data),
void *abortCheckCbkDataA)
#ifdef USE_CMS
: iccColorSpaceCache(5)
#endif
{
int i;
xref = xrefA;
catalog = catalogA;
subPage = gFalse;
printCommands = globalParams->getPrintCommands();
profileCommands = globalParams->getProfileCommands();
textHaveCSPattern = gFalse;
drawText = gFalse;
maskHaveCSPattern = gFalse;
mcStack = NULL;
res = new GfxResources(xref, resDict, NULL);
out = outA;
state = new GfxState(hDPI, vDPI, box, rotate, out->upsideDown());
stackHeight = 1;
pushStateGuard();
fontChanged = gFalse;
clip = clipNone;
ignoreUndef = 0;
out->startPage(pageNum, state);
out->setDefaultCTM(state->getCTM());
out->updateAll(state);
for (i = 0; i < 6; ++i) {
baseMatrix[i] = state->getCTM()[i];
}
formDepth = 0;
abortCheckCbk = abortCheckCbkA;
abortCheckCbkData = abortCheckCbkDataA;
if (cropBox) {
state->moveTo(cropBox->x1, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y2);
state->lineTo(cropBox->x1, cropBox->y2);
state->closePath();
state->clip();
out->clip(state);
state->clearPath();
}
}
Commit Message:
CWE ID: CWE-20
|
Gfx::Gfx(XRef *xrefA, OutputDev *outA, int pageNum, Dict *resDict, Catalog *catalogA,
double hDPI, double vDPI, PDFRectangle *box,
PDFRectangle *cropBox, int rotate,
GBool (*abortCheckCbkA)(void *data),
void *abortCheckCbkDataA)
#ifdef USE_CMS
: iccColorSpaceCache(5)
#endif
{
int i;
xref = xrefA;
catalog = catalogA;
subPage = gFalse;
printCommands = globalParams->getPrintCommands();
profileCommands = globalParams->getProfileCommands();
textHaveCSPattern = gFalse;
drawText = gFalse;
maskHaveCSPattern = gFalse;
mcStack = NULL;
parser = NULL;
res = new GfxResources(xref, resDict, NULL);
out = outA;
state = new GfxState(hDPI, vDPI, box, rotate, out->upsideDown());
stackHeight = 1;
pushStateGuard();
fontChanged = gFalse;
clip = clipNone;
ignoreUndef = 0;
out->startPage(pageNum, state);
out->setDefaultCTM(state->getCTM());
out->updateAll(state);
for (i = 0; i < 6; ++i) {
baseMatrix[i] = state->getCTM()[i];
}
formDepth = 0;
abortCheckCbk = abortCheckCbkA;
abortCheckCbkData = abortCheckCbkDataA;
if (cropBox) {
state->moveTo(cropBox->x1, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y2);
state->lineTo(cropBox->x1, cropBox->y2);
state->closePath();
state->clip();
out->clip(state);
state->clearPath();
}
}
| 164,904
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long Chapters::Display::Parse(IMkvReader* pReader, long long pos,
long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x05) { // ChapterString ID
status = UnserializeString(pReader, pos, size, m_string);
if (status)
return status;
} else if (id == 0x037C) { // ChapterLanguage ID
status = UnserializeString(pReader, pos, size, m_language);
if (status)
return status;
} else if (id == 0x037E) { // ChapterCountry ID
status = UnserializeString(pReader, pos, size, m_country);
if (status)
return status;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
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 Chapters::Display::Parse(IMkvReader* pReader, long long pos,
long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x05) { // ChapterString ID
status = UnserializeString(pReader, pos, size, m_string);
if (status)
return status;
} else if (id == 0x037C) { // ChapterLanguage ID
status = UnserializeString(pReader, pos, size, m_language);
if (status)
return status;
} else if (id == 0x037E) { // ChapterCountry ID
status = UnserializeString(pReader, pos, size, m_country);
if (status)
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
Tags::Tags(Segment* pSegment, long long payload_start, long long payload_size,
long long element_start, long long element_size)
: m_pSegment(pSegment),
m_start(payload_start),
m_size(payload_size),
m_element_start(element_start),
m_element_size(element_size),
m_tags(NULL),
m_tags_size(0),
m_tags_count(0) {}
Tags::~Tags() {
while (m_tags_count > 0) {
Tag& t = m_tags[--m_tags_count];
t.Clear();
}
delete[] m_tags;
}
long Tags::Parse() {
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start; // payload start
const long long stop = pos + m_size; // payload stop
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0)
return status;
if (size == 0) // 0 length tag, read another
continue;
if (id == 0x3373) { // Tag ID
status = ParseTag(pos, size);
if (status < 0)
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
int Tags::GetTagCount() const { return m_tags_count; }
const Tags::Tag* Tags::GetTag(int idx) const {
if (idx < 0)
return NULL;
if (idx >= m_tags_count)
return NULL;
return m_tags + idx;
}
bool Tags::ExpandTagsArray() {
if (m_tags_size > m_tags_count)
return true; // nothing else to do
const int size = (m_tags_size == 0) ? 1 : 2 * m_tags_size;
Tag* const tags = new (std::nothrow) Tag[size];
if (tags == NULL)
return false;
for (int idx = 0; idx < m_tags_count; ++idx) {
m_tags[idx].ShallowCopy(tags[idx]);
}
delete[] m_tags;
m_tags = tags;
m_tags_size = size;
return true;
}
long Tags::ParseTag(long long pos, long long size) {
if (!ExpandTagsArray())
return -1;
Tag& t = m_tags[m_tags_count++];
t.Init();
return t.Parse(m_pSegment->m_pReader, pos, size);
}
Tags::Tag::Tag() {}
Tags::Tag::~Tag() {}
int Tags::Tag::GetSimpleTagCount() const { return m_simple_tags_count; }
const Tags::SimpleTag* Tags::Tag::GetSimpleTag(int index) const {
if (index < 0)
return NULL;
if (index >= m_simple_tags_count)
return NULL;
return m_simple_tags + index;
}
void Tags::Tag::Init() {
m_simple_tags = NULL;
m_simple_tags_size = 0;
m_simple_tags_count = 0;
}
void Tags::Tag::ShallowCopy(Tag& rhs) const {
rhs.m_simple_tags = m_simple_tags;
rhs.m_simple_tags_size = m_simple_tags_size;
rhs.m_simple_tags_count = m_simple_tags_count;
}
void Tags::Tag::Clear() {
while (m_simple_tags_count > 0) {
SimpleTag& d = m_simple_tags[--m_simple_tags_count];
d.Clear();
}
delete[] m_simple_tags;
m_simple_tags = NULL;
m_simple_tags_size = 0;
}
long Tags::Tag::Parse(IMkvReader* pReader, long long pos, long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0)
return status;
if (size == 0) // 0 length tag, read another
continue;
if (id == 0x27C8) { // SimpleTag ID
status = ParseSimpleTag(pReader, pos, size);
if (status < 0)
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
long Tags::Tag::ParseSimpleTag(IMkvReader* pReader, long long pos,
long long size) {
if (!ExpandSimpleTagsArray())
return -1;
SimpleTag& st = m_simple_tags[m_simple_tags_count++];
st.Init();
return st.Parse(pReader, pos, size);
}
bool Tags::Tag::ExpandSimpleTagsArray() {
if (m_simple_tags_size > m_simple_tags_count)
return true; // nothing else to do
const int size = (m_simple_tags_size == 0) ? 1 : 2 * m_simple_tags_size;
SimpleTag* const displays = new (std::nothrow) SimpleTag[size];
if (displays == NULL)
return false;
for (int idx = 0; idx < m_simple_tags_count; ++idx) {
m_simple_tags[idx].ShallowCopy(displays[idx]);
}
delete[] m_simple_tags;
m_simple_tags = displays;
m_simple_tags_size = size;
return true;
}
Tags::SimpleTag::SimpleTag() {}
Tags::SimpleTag::~SimpleTag() {}
const char* Tags::SimpleTag::GetTagName() const { return m_tag_name; }
const char* Tags::SimpleTag::GetTagString() const { return m_tag_string; }
void Tags::SimpleTag::Init() {
m_tag_name = NULL;
m_tag_string = NULL;
}
void Tags::SimpleTag::ShallowCopy(SimpleTag& rhs) const {
rhs.m_tag_name = m_tag_name;
rhs.m_tag_string = m_tag_string;
}
void Tags::SimpleTag::Clear() {
delete[] m_tag_name;
m_tag_name = NULL;
delete[] m_tag_string;
m_tag_string = NULL;
}
long Tags::SimpleTag::Parse(IMkvReader* pReader, long long pos,
long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x5A3) { // TagName ID
status = UnserializeString(pReader, pos, size, m_tag_name);
if (status)
return status;
} else if (id == 0x487) { // TagString ID
status = UnserializeString(pReader, pos, size, m_tag_string);
if (status)
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,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: Blob::Blob(PassOwnPtr<BlobData> blobData, long long size)
: m_type(blobData->contentType())
, m_size(size)
{
ASSERT(blobData);
ScriptWrappable::init(this);
m_internalURL = BlobURL::createInternalURL();
ThreadableBlobRegistry::registerBlobURL(m_internalURL, blobData);
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
|
Blob::Blob(PassOwnPtr<BlobData> blobData, long long size)
: m_type(blobData->contentType())
, m_size(size)
{
ASSERT(blobData);
ScriptWrappable::init(this);
m_internalURL = BlobURL::createInternalURL();
BlobRegistry::registerBlobURL(m_internalURL, blobData);
}
| 170,675
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: gfx::Size CardUnmaskPromptViews::GetPreferredSize() const {
const int kWidth = 375;
return gfx::Size(kWidth, GetHeightForWidth(kWidth));
}
Commit Message: Clear out some minor TODOs.
BUG=none
Review URL: https://codereview.chromium.org/1047063002
Cr-Commit-Position: refs/heads/master@{#322959}
CWE ID: CWE-20
|
gfx::Size CardUnmaskPromptViews::GetPreferredSize() const {
// Must hardcode a width so the label knows where to wrap.
const int kWidth = 375;
return gfx::Size(kWidth, GetHeightForWidth(kWidth));
}
| 171,142
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void *nlmsg_reserve(struct nl_msg *n, size_t len, int pad)
{
void *buf = n->nm_nlh;
size_t nlmsg_len = n->nm_nlh->nlmsg_len;
size_t tlen;
tlen = pad ? ((len + (pad - 1)) & ~(pad - 1)) : len;
if ((tlen + nlmsg_len) > n->nm_size)
n->nm_nlh->nlmsg_len += tlen;
if (tlen > len)
memset(buf + len, 0, tlen - len);
NL_DBG(2, "msg %p: Reserved %zu (%zu) bytes, pad=%d, nlmsg_len=%d\n",
n, tlen, len, pad, n->nm_nlh->nlmsg_len);
return buf;
}
Commit Message:
CWE ID: CWE-190
|
void *nlmsg_reserve(struct nl_msg *n, size_t len, int pad)
{
void *buf = n->nm_nlh;
size_t nlmsg_len = n->nm_nlh->nlmsg_len;
size_t tlen;
if (len > n->nm_size)
return NULL;
tlen = pad ? ((len + (pad - 1)) & ~(pad - 1)) : len;
if ((tlen + nlmsg_len) > n->nm_size)
n->nm_nlh->nlmsg_len += tlen;
if (tlen > len)
memset(buf + len, 0, tlen - len);
NL_DBG(2, "msg %p: Reserved %zu (%zu) bytes, pad=%d, nlmsg_len=%d\n",
n, tlen, len, pad, n->nm_nlh->nlmsg_len);
return buf;
}
| 165,218
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: jbig2_word_stream_buf_get_next_word(Jbig2WordStream *self, int offset, uint32_t *word)
{
Jbig2WordStreamBuf *z = (Jbig2WordStreamBuf *) self;
const byte *data = z->data;
uint32_t result;
if (offset + 4 < z->size)
result = (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3];
else if (offset > z->size)
return -1;
else {
int i;
result = 0;
for (i = 0; i < z->size - offset; i++)
result |= data[offset + i] << ((3 - i) << 3);
}
*word = result;
return 0;
}
Commit Message:
CWE ID: CWE-119
|
jbig2_word_stream_buf_get_next_word(Jbig2WordStream *self, int offset, uint32_t *word)
jbig2_word_stream_buf_get_next_word(Jbig2WordStream *self, size_t offset, uint32_t *word)
{
Jbig2WordStreamBuf *z = (Jbig2WordStreamBuf *) self;
const byte *data = z->data;
uint32_t result;
if (offset + 4 < z->size)
result = (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3];
else if (offset > z->size)
return -1;
else {
size_t i;
result = 0;
for (i = 0; i < z->size - offset; i++)
result |= data[offset + i] << ((3 - i) << 3);
}
*word = result;
return 0;
}
| 165,485
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) {
int ret;
if (input == NULL) return(-1);
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur);
}
ret = inputPush(ctxt, input);
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
GROW;
return(ret);
}
Commit Message: Detect infinite recursion in parameter entities
When expanding a parameter entity in a DTD, infinite recursion could
lead to an infinite loop or memory exhaustion.
Thanks to Wei Lei for the first of many reports.
Fixes bug 759579.
CWE ID: CWE-835
|
xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) {
int ret;
if (input == NULL) return(-1);
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur);
}
if (((ctxt->inputNr > 40) && ((ctxt->options & XML_PARSE_HUGE) == 0)) ||
(ctxt->inputNr > 1024)) {
xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
while (ctxt->inputNr > 1)
xmlFreeInputStream(inputPop(ctxt));
return(-1);
}
ret = inputPush(ctxt, input);
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
GROW;
return(ret);
}
| 167,666
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 qemu_spice_create_host_primary(SimpleSpiceDisplay *ssd)
{
QXLDevSurfaceCreate surface;
memset(&surface, 0, sizeof(surface));
dprint(1, "%s/%d: %dx%d\n", __func__, ssd->qxl.id,
surface_width(ssd->ds), surface_height(ssd->ds));
surface.format = SPICE_SURFACE_FMT_32_xRGB;
surface.width = surface_width(ssd->ds);
{
dprint(1, "%s/%d:\n", __func__, ssd->qxl.id);
qemu_spice_destroy_primary_surface(ssd, 0, QXL_SYNC);
}
void qemu_spice_display_init_common(SimpleSpiceDisplay *ssd)
{
qemu_mutex_init(&ssd->lock);
QTAILQ_INIT(&ssd->updates);
ssd->mouse_x = -1;
ssd->mouse_y = -1;
if (ssd->num_surfaces == 0) {
ssd->num_surfaces = 1024;
}
ssd->bufsize = (16 * 1024 * 1024);
ssd->buf = g_malloc(ssd->bufsize);
}
/* display listener callbacks */
void qemu_spice_display_update(SimpleSpiceDisplay *ssd,
int x, int y, int w, int h)
{
if (ssd->num_surfaces == 0) {
ssd->num_surfaces = 1024;
}
ssd->bufsize = (16 * 1024 * 1024);
ssd->buf = g_malloc(ssd->bufsize);
}
/* display listener callbacks */
update_area.top = y;
update_area.bottom = y + h;
if (qemu_spice_rect_is_empty(&ssd->dirty)) {
ssd->notify++;
}
qemu_spice_rect_union(&ssd->dirty, &update_area);
}
Commit Message:
CWE ID: CWE-200
|
void qemu_spice_create_host_primary(SimpleSpiceDisplay *ssd)
{
QXLDevSurfaceCreate surface;
uint64_t surface_size;
memset(&surface, 0, sizeof(surface));
surface_size = (uint64_t) surface_width(ssd->ds) *
surface_height(ssd->ds) * 4;
assert(surface_size > 0);
assert(surface_size < INT_MAX);
if (ssd->bufsize < surface_size) {
ssd->bufsize = surface_size;
g_free(ssd->buf);
ssd->buf = g_malloc(ssd->bufsize);
}
dprint(1, "%s/%d: %ux%u (size %" PRIu64 "/%d)\n", __func__, ssd->qxl.id,
surface_width(ssd->ds), surface_height(ssd->ds),
surface_size, ssd->bufsize);
surface.format = SPICE_SURFACE_FMT_32_xRGB;
surface.width = surface_width(ssd->ds);
{
dprint(1, "%s/%d:\n", __func__, ssd->qxl.id);
qemu_spice_destroy_primary_surface(ssd, 0, QXL_SYNC);
}
void qemu_spice_display_init_common(SimpleSpiceDisplay *ssd)
{
qemu_mutex_init(&ssd->lock);
QTAILQ_INIT(&ssd->updates);
ssd->mouse_x = -1;
ssd->mouse_y = -1;
if (ssd->num_surfaces == 0) {
ssd->num_surfaces = 1024;
}
ssd->bufsize = (16 * 1024 * 1024);
ssd->buf = g_malloc(ssd->bufsize);
}
/* display listener callbacks */
void qemu_spice_display_update(SimpleSpiceDisplay *ssd,
int x, int y, int w, int h)
{
if (ssd->num_surfaces == 0) {
ssd->num_surfaces = 1024;
}
}
/* display listener callbacks */
update_area.top = y;
update_area.bottom = y + h;
if (qemu_spice_rect_is_empty(&ssd->dirty)) {
ssd->notify++;
}
qemu_spice_rect_union(&ssd->dirty, &update_area);
}
| 165,151
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: status_t OMXNodeInstance::allocateBufferWithBackup(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
if (params == NULL || buffer == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size() || portIndex >= NELEM(mNumPortBuffers)) {
return BAD_VALUE;
}
bool copy = mMetadataType[portIndex] == kMetadataBufferTypeInvalid;
BufferMeta *buffer_meta = new BufferMeta(
params, portIndex,
(portIndex == kPortIndexInput) && copy /* copyToOmx */,
(portIndex == kPortIndexOutput) && copy /* copyFromOmx */,
NULL /* data */);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_AllocateBuffer(
mHandle, &header, portIndex, buffer_meta, allottedSize);
if (err != OMX_ErrorNone) {
CLOG_ERROR(allocateBufferWithBackup, err,
SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer()));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
memset(header->pBuffer, 0, header->nAllocLen);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p",
params->size(), params->pointer(), allottedSize, header->pBuffer));
return OK;
}
Commit Message: IOMX: do not clear buffer if it's allocated by component
The component might depends on their buffers to be initialized
in certain ways to work. Don't clear unless we're allocating it.
bug: 31586647
Change-Id: Ia0a125797e414998ef0cd8ce03672f5b1e0bbf7a
(cherry picked from commit ea76573aa276f51950007217a97903c4fe64f685)
CWE ID: CWE-200
|
status_t OMXNodeInstance::allocateBufferWithBackup(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
if (params == NULL || buffer == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size() || portIndex >= NELEM(mNumPortBuffers)) {
return BAD_VALUE;
}
bool copy = mMetadataType[portIndex] == kMetadataBufferTypeInvalid;
BufferMeta *buffer_meta = new BufferMeta(
params, portIndex,
(portIndex == kPortIndexInput) && copy /* copyToOmx */,
(portIndex == kPortIndexOutput) && copy /* copyFromOmx */,
NULL /* data */);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_AllocateBuffer(
mHandle, &header, portIndex, buffer_meta, allottedSize);
if (err != OMX_ErrorNone) {
CLOG_ERROR(allocateBufferWithBackup, err,
SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer()));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p",
params->size(), params->pointer(), allottedSize, header->pBuffer));
return OK;
}
| 174,144
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void FileAPIMessageFilter::OnCreateSnapshotFile(
int request_id, const GURL& blob_url, const GURL& path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
FileSystemURL url(path);
base::Callback<void(const FilePath&)> register_file_callback =
base::Bind(&FileAPIMessageFilter::RegisterFileAsBlob,
this, blob_url, url.path());
FileSystemOperation* operation = GetNewOperation(url, request_id);
if (!operation)
return;
operation->CreateSnapshotFile(
url,
base::Bind(&FileAPIMessageFilter::DidCreateSnapshot,
this, request_id, register_file_callback));
}
Commit Message: File permission fix: now we selectively grant read permission for Sandboxed files
We also need to check the read permission and call GrantReadFile() for
sandboxed files for CreateSnapshotFile().
BUG=162114
TEST=manual
Review URL: https://codereview.chromium.org/11280231
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@170181 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
void FileAPIMessageFilter::OnCreateSnapshotFile(
int request_id, const GURL& blob_url, const GURL& path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
FileSystemURL url(path);
base::Callback<void(const FilePath&)> register_file_callback =
base::Bind(&FileAPIMessageFilter::RegisterFileAsBlob,
this, blob_url, url);
// Make sure if this file can be read by the renderer as this is
// called when the renderer is about to create a new File object
// (for reading the file).
base::PlatformFileError error;
if (!HasPermissionsForFile(url, kReadFilePermissions, &error)) {
Send(new FileSystemMsg_DidFail(request_id, error));
return;
}
FileSystemOperation* operation = GetNewOperation(url, request_id);
if (!operation)
return;
operation->CreateSnapshotFile(
url,
base::Bind(&FileAPIMessageFilter::DidCreateSnapshot,
this, request_id, register_file_callback));
}
| 171,586
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) {
int ret;
if (input == NULL) return(-1);
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur);
}
ret = inputPush(ctxt, input);
GROW;
return(ret);
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) {
int ret;
if (input == NULL) return(-1);
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur);
}
ret = inputPush(ctxt, input);
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
GROW;
return(ret);
}
| 171,309
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WT_NoiseGenerator (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 nInterpolatedSample;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
pOutputBuffer = pWTIntFrame->pAudioBuffer;
phaseInc = pWTIntFrame->frame.phaseIncrement;
/* get last two samples generated */
/*lint -e{704} <avoid divide for performance>*/
tmp0 = (EAS_I32) (pWTVoice->phaseAccum) >> 18;
/*lint -e{704} <avoid divide for performance>*/
tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18;
/* generate a buffer of noise */
while (numSamples--) {
nInterpolatedSample = MULT_AUDIO_COEF( tmp0, (PHASE_ONE - pWTVoice->phaseFrac));
nInterpolatedSample += MULT_AUDIO_COEF( tmp1, pWTVoice->phaseFrac);
*pOutputBuffer++ = (EAS_PCM) nInterpolatedSample;
/* update PRNG */
pWTVoice->phaseFrac += (EAS_U32) phaseInc;
if (GET_PHASE_INT_PART(pWTVoice->phaseFrac)) {
tmp0 = tmp1;
pWTVoice->phaseAccum = pWTVoice->loopEnd;
pWTVoice->loopEnd = (5 * pWTVoice->loopEnd + 1);
tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18;
pWTVoice->phaseFrac = GET_PHASE_FRAC_PART(pWTVoice->phaseFrac);
}
}
}
Commit Message: Sonivox: sanity check numSamples.
Bug: 26366256
Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc
CWE ID: CWE-119
|
void WT_NoiseGenerator (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 nInterpolatedSample;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
return;
}
pOutputBuffer = pWTIntFrame->pAudioBuffer;
phaseInc = pWTIntFrame->frame.phaseIncrement;
/* get last two samples generated */
/*lint -e{704} <avoid divide for performance>*/
tmp0 = (EAS_I32) (pWTVoice->phaseAccum) >> 18;
/*lint -e{704} <avoid divide for performance>*/
tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18;
/* generate a buffer of noise */
while (numSamples--) {
nInterpolatedSample = MULT_AUDIO_COEF( tmp0, (PHASE_ONE - pWTVoice->phaseFrac));
nInterpolatedSample += MULT_AUDIO_COEF( tmp1, pWTVoice->phaseFrac);
*pOutputBuffer++ = (EAS_PCM) nInterpolatedSample;
/* update PRNG */
pWTVoice->phaseFrac += (EAS_U32) phaseInc;
if (GET_PHASE_INT_PART(pWTVoice->phaseFrac)) {
tmp0 = tmp1;
pWTVoice->phaseAccum = pWTVoice->loopEnd;
pWTVoice->loopEnd = (5 * pWTVoice->loopEnd + 1);
tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18;
pWTVoice->phaseFrac = GET_PHASE_FRAC_PART(pWTVoice->phaseFrac);
}
}
}
| 173,920
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 HTMLAnchorElement::handleClick(Event* event)
{
event->setDefaultHandled();
LocalFrame* frame = document().frame();
if (!frame)
return;
StringBuilder url;
url.append(stripLeadingAndTrailingHTMLSpaces(fastGetAttribute(hrefAttr)));
appendServerMapMousePosition(url, event);
KURL completedURL = document().completeURL(url.toString());
sendPings(completedURL);
ResourceRequest request(completedURL);
request.setUIStartTime(event->platformTimeStamp());
request.setInputPerfMetricReportPolicy(InputToLoadPerfMetricReportPolicy::ReportLink);
ReferrerPolicy policy;
if (hasAttribute(referrerpolicyAttr) && SecurityPolicy::referrerPolicyFromString(fastGetAttribute(referrerpolicyAttr), &policy) && !hasRel(RelationNoReferrer)) {
request.setHTTPReferrer(SecurityPolicy::generateReferrer(policy, completedURL, document().outgoingReferrer()));
}
if (hasAttribute(downloadAttr)) {
request.setRequestContext(WebURLRequest::RequestContextDownload);
bool isSameOrigin = completedURL.protocolIsData() || document().getSecurityOrigin()->canRequest(completedURL);
const AtomicString& suggestedName = (isSameOrigin ? fastGetAttribute(downloadAttr) : nullAtom);
frame->loader().client()->loadURLExternally(request, NavigationPolicyDownload, suggestedName, false);
} else {
request.setRequestContext(WebURLRequest::RequestContextHyperlink);
FrameLoadRequest frameRequest(&document(), request, getAttribute(targetAttr));
frameRequest.setTriggeringEvent(event);
if (hasRel(RelationNoReferrer)) {
frameRequest.setShouldSendReferrer(NeverSendReferrer);
frameRequest.setShouldSetOpener(NeverSetOpener);
}
if (hasRel(RelationNoOpener))
frameRequest.setShouldSetOpener(NeverSetOpener);
frame->loader().load(frameRequest);
}
}
Commit Message: Disable frame navigations during DocumentLoader detach in FrameLoader::startLoad
BUG=613266
Review-Url: https://codereview.chromium.org/2006033002
Cr-Commit-Position: refs/heads/master@{#396241}
CWE ID: CWE-284
|
void HTMLAnchorElement::handleClick(Event* event)
{
event->setDefaultHandled();
LocalFrame* frame = document().frame();
if (!frame)
return;
StringBuilder url;
url.append(stripLeadingAndTrailingHTMLSpaces(fastGetAttribute(hrefAttr)));
appendServerMapMousePosition(url, event);
KURL completedURL = document().completeURL(url.toString());
sendPings(completedURL);
ResourceRequest request(completedURL);
request.setUIStartTime(event->platformTimeStamp());
request.setInputPerfMetricReportPolicy(InputToLoadPerfMetricReportPolicy::ReportLink);
ReferrerPolicy policy;
if (hasAttribute(referrerpolicyAttr) && SecurityPolicy::referrerPolicyFromString(fastGetAttribute(referrerpolicyAttr), &policy) && !hasRel(RelationNoReferrer)) {
request.setHTTPReferrer(SecurityPolicy::generateReferrer(policy, completedURL, document().outgoingReferrer()));
}
if (hasAttribute(downloadAttr)) {
request.setRequestContext(WebURLRequest::RequestContextDownload);
bool isSameOrigin = completedURL.protocolIsData() || document().getSecurityOrigin()->canRequest(completedURL);
const AtomicString& suggestedName = (isSameOrigin ? fastGetAttribute(downloadAttr) : nullAtom);
frame->loader().client()->loadURLExternally(request, NavigationPolicyDownload, suggestedName, false);
} else {
request.setRequestContext(WebURLRequest::RequestContextHyperlink);
FrameLoadRequest frameRequest(&document(), request, getAttribute(targetAttr));
frameRequest.setTriggeringEvent(event);
if (hasRel(RelationNoReferrer)) {
frameRequest.setShouldSendReferrer(NeverSendReferrer);
frameRequest.setShouldSetOpener(NeverSetOpener);
}
if (hasRel(RelationNoOpener))
frameRequest.setShouldSetOpener(NeverSetOpener);
// TODO(japhet): Link clicks can be emulated via JS without a user gesture.
// Why doesn't this go through NavigationScheduler?
frame->loader().load(frameRequest);
}
}
| 172,257
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CairoOutputDev::beginString(GfxState *state, GooString *s)
{
int len = s->getLength();
if (needFontUpdate)
updateFont(state);
if (!currentFont)
return;
glyphs = (cairo_glyph_t *) gmalloc (len * sizeof (cairo_glyph_t));
glyphCount = 0;
}
Commit Message:
CWE ID: CWE-189
|
void CairoOutputDev::beginString(GfxState *state, GooString *s)
{
int len = s->getLength();
if (needFontUpdate)
updateFont(state);
if (!currentFont)
return;
glyphs = (cairo_glyph_t *) gmallocn (len, sizeof (cairo_glyph_t));
glyphCount = 0;
}
| 164,604
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 res_unpack(vorbis_info_residue *info,
vorbis_info *vi,oggpack_buffer *opb){
int j,k;
codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
memset(info,0,sizeof(*info));
info->type=oggpack_read(opb,16);
if(info->type>2 || info->type<0)goto errout;
info->begin=oggpack_read(opb,24);
info->end=oggpack_read(opb,24);
info->grouping=oggpack_read(opb,24)+1;
info->partitions=(char)(oggpack_read(opb,6)+1);
info->groupbook=(unsigned char)oggpack_read(opb,8);
if(info->groupbook>=ci->books)goto errout;
info->stagemasks=_ogg_malloc(info->partitions*sizeof(*info->stagemasks));
info->stagebooks=_ogg_malloc(info->partitions*8*sizeof(*info->stagebooks));
for(j=0;j<info->partitions;j++){
int cascade=oggpack_read(opb,3);
if(oggpack_read(opb,1))
cascade|=(oggpack_read(opb,5)<<3);
info->stagemasks[j]=cascade;
}
for(j=0;j<info->partitions;j++){
for(k=0;k<8;k++){
if((info->stagemasks[j]>>k)&1){
unsigned char book=(unsigned char)oggpack_read(opb,8);
if(book>=ci->books)goto errout;
info->stagebooks[j*8+k]=book;
if(k+1>info->stages)info->stages=k+1;
}else
info->stagebooks[j*8+k]=0xff;
}
}
if(oggpack_eop(opb))goto errout;
return 0;
errout:
res_clear_info(info);
return 1;
}
Commit Message: Check partword is in range for # of partitions
and reformat tabs->spaces for readability.
Bug: 28556125
Change-Id: Id02819a6a5bcc24ba4f8a502081e5cb45272681c
CWE ID: CWE-20
|
int res_unpack(vorbis_info_residue *info,
vorbis_info *vi,oggpack_buffer *opb){
int j,k;
codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
memset(info,0,sizeof(*info));
info->type=oggpack_read(opb,16);
if(info->type>2 || info->type<0)goto errout;
info->begin=oggpack_read(opb,24);
info->end=oggpack_read(opb,24);
info->grouping=oggpack_read(opb,24)+1;
info->partitions=(char)(oggpack_read(opb,6)+1);
info->groupbook=(unsigned char)oggpack_read(opb,8);
if(info->groupbook>=ci->books)goto errout;
info->stagemasks=_ogg_malloc(info->partitions*sizeof(*info->stagemasks));
info->stagebooks=_ogg_malloc(info->partitions*8*sizeof(*info->stagebooks));
for(j=0;j<info->partitions;j++){
int cascade=oggpack_read(opb,3);
if(oggpack_read(opb,1))
cascade|=(oggpack_read(opb,5)<<3);
info->stagemasks[j]=cascade;
}
for(j=0;j<info->partitions;j++){
for(k=0;k<8;k++){
if((info->stagemasks[j]>>k)&1){
unsigned char book=(unsigned char)oggpack_read(opb,8);
if(book>=ci->books)goto errout;
info->stagebooks[j*8+k]=book;
if(k+1>info->stages)info->stages=k+1;
}else
info->stagebooks[j*8+k]=0xff;
}
}
if(oggpack_eop(opb))goto errout;
return 0;
errout:
res_clear_info(info);
return 1;
}
| 173,562
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BooleanOrNullAttributeAttributeSetter(
v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
ALLOW_UNUSED_LOCAL(isolate);
v8::Local<v8::Object> holder = info.Holder();
ALLOW_UNUSED_LOCAL(holder);
TestObject* impl = V8TestObject::ToImpl(holder);
ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "TestObject", "booleanOrNullAttribute");
bool cpp_value = NativeValueTraits<IDLBoolean>::NativeValue(info.GetIsolate(), v8_value, exception_state);
if (exception_state.HadException())
return;
bool is_null = IsUndefinedOrNull(v8_value);
impl->setBooleanOrNullAttribute(cpp_value, is_null);
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <peria@chromium.org>
Commit-Queue: Yuki Shiino <yukishiino@chromium.org>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
|
static void BooleanOrNullAttributeAttributeSetter(
v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
ALLOW_UNUSED_LOCAL(isolate);
v8::Local<v8::Object> holder = info.Holder();
ALLOW_UNUSED_LOCAL(holder);
TestObject* impl = V8TestObject::ToImpl(holder);
ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "TestObject", "booleanOrNullAttribute");
bool is_null = IsUndefinedOrNull(v8_value);
bool cpp_value = is_null ? bool() : NativeValueTraits<IDLBoolean>::NativeValue(info.GetIsolate(), v8_value, exception_state);
if (exception_state.HadException())
return;
impl->setBooleanOrNullAttribute(cpp_value, is_null);
}
| 172,304
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void ext4_free_io_end(ext4_io_end_t *io)
{
BUG_ON(!io);
iput(io->inode);
kfree(io);
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <jiayingz@google.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
CWE ID:
|
static void ext4_free_io_end(ext4_io_end_t *io)
| 167,544
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.