instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void test_base64_lengths(void)
{
const char *in = "FuseMuse";
char out1[32];
char out2[32];
size_t enclen;
int declen;
/* Encoding a zero-length string should fail */
enclen = mutt_b64_encode(out1, in, 0, 32);
if (!TEST_CHECK(enclen == 0))
{
TEST_MSG("Expected: %zu", 0);
TEST_MSG("Actual : %zu", enclen);
}
/* Decoding a zero-length string should fail, too */
out1[0] = '\0';
declen = mutt_b64_decode(out2, out1);
if (!TEST_CHECK(declen == -1))
{
TEST_MSG("Expected: %zu", -1);
TEST_MSG("Actual : %zu", declen);
}
/* Encode one to eight bytes, check the lengths of the returned string */
for (size_t i = 1; i <= 8; ++i)
{
enclen = mutt_b64_encode(out1, in, i, 32);
size_t exp = ((i + 2) / 3) << 2;
if (!TEST_CHECK(enclen == exp))
{
TEST_MSG("Expected: %zu", exp);
TEST_MSG("Actual : %zu", enclen);
}
declen = mutt_b64_decode(out2, out1);
if (!TEST_CHECK(declen == i))
{
TEST_MSG("Expected: %zu", i);
TEST_MSG("Actual : %zu", declen);
}
out2[declen] = '\0';
if (!TEST_CHECK(strncmp(out2, in, i) == 0))
{
TEST_MSG("Expected: %s", in);
TEST_MSG("Actual : %s", out2);
}
}
}
Commit Message: Check outbuf length in mutt_to_base64()
The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c.
Thanks to Jeriko One for the bug report.
CWE ID: CWE-119 | void test_base64_lengths(void)
{
const char *in = "FuseMuse";
char out1[32];
char out2[32];
size_t enclen;
int declen;
/* Encoding a zero-length string should fail */
enclen = mutt_b64_encode(out1, in, 0, 32);
if (!TEST_CHECK(enclen == 0))
{
TEST_MSG("Expected: %zu", 0);
TEST_MSG("Actual : %zu", enclen);
}
/* Decoding a zero-length string should fail, too */
out1[0] = '\0';
declen = mutt_b64_decode(out2, out1, sizeof(out2));
if (!TEST_CHECK(declen == -1))
{
TEST_MSG("Expected: %zu", -1);
TEST_MSG("Actual : %zu", declen);
}
/* Encode one to eight bytes, check the lengths of the returned string */
for (size_t i = 1; i <= 8; ++i)
{
enclen = mutt_b64_encode(out1, in, i, 32);
size_t exp = ((i + 2) / 3) << 2;
if (!TEST_CHECK(enclen == exp))
{
TEST_MSG("Expected: %zu", exp);
TEST_MSG("Actual : %zu", enclen);
}
declen = mutt_b64_decode(out2, out1, sizeof(out2));
if (!TEST_CHECK(declen == i))
{
TEST_MSG("Expected: %zu", i);
TEST_MSG("Actual : %zu", declen);
}
out2[declen] = '\0';
if (!TEST_CHECK(strncmp(out2, in, i) == 0))
{
TEST_MSG("Expected: %s", in);
TEST_MSG("Actual : %s", out2);
}
}
}
| 169,131 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::unique_ptr<HistogramBase> PersistentHistogramAllocator::CreateHistogram(
PersistentHistogramData* histogram_data_ptr) {
if (!histogram_data_ptr) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_METADATA_POINTER);
NOTREACHED();
return nullptr;
}
if (histogram_data_ptr->histogram_type == SPARSE_HISTOGRAM) {
std::unique_ptr<HistogramBase> histogram =
SparseHistogram::PersistentCreate(this, histogram_data_ptr->name,
&histogram_data_ptr->samples_metadata,
&histogram_data_ptr->logged_metadata);
DCHECK(histogram);
histogram->SetFlags(histogram_data_ptr->flags);
RecordCreateHistogramResult(CREATE_HISTOGRAM_SUCCESS);
return histogram;
}
int32_t histogram_type = histogram_data_ptr->histogram_type;
int32_t histogram_flags = histogram_data_ptr->flags;
int32_t histogram_minimum = histogram_data_ptr->minimum;
int32_t histogram_maximum = histogram_data_ptr->maximum;
uint32_t histogram_bucket_count = histogram_data_ptr->bucket_count;
uint32_t histogram_ranges_ref = histogram_data_ptr->ranges_ref;
uint32_t histogram_ranges_checksum = histogram_data_ptr->ranges_checksum;
HistogramBase::Sample* ranges_data =
memory_allocator_->GetAsArray<HistogramBase::Sample>(
histogram_ranges_ref, kTypeIdRangesArray,
PersistentMemoryAllocator::kSizeAny);
const uint32_t max_buckets =
std::numeric_limits<uint32_t>::max() / sizeof(HistogramBase::Sample);
size_t required_bytes =
(histogram_bucket_count + 1) * sizeof(HistogramBase::Sample);
size_t allocated_bytes =
memory_allocator_->GetAllocSize(histogram_ranges_ref);
if (!ranges_data || histogram_bucket_count < 2 ||
histogram_bucket_count >= max_buckets ||
allocated_bytes < required_bytes) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_RANGES_ARRAY);
NOTREACHED();
return nullptr;
}
std::unique_ptr<const BucketRanges> created_ranges = CreateRangesFromData(
ranges_data, histogram_ranges_checksum, histogram_bucket_count + 1);
if (!created_ranges) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_RANGES_ARRAY);
NOTREACHED();
return nullptr;
}
const BucketRanges* ranges =
StatisticsRecorder::RegisterOrDeleteDuplicateRanges(
created_ranges.release());
size_t counts_bytes = CalculateRequiredCountsBytes(histogram_bucket_count);
PersistentMemoryAllocator::Reference counts_ref =
subtle::Acquire_Load(&histogram_data_ptr->counts_ref);
if (counts_bytes == 0 ||
(counts_ref != 0 &&
memory_allocator_->GetAllocSize(counts_ref) < counts_bytes)) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_COUNTS_ARRAY);
NOTREACHED();
return nullptr;
}
DelayedPersistentAllocation counts_data(memory_allocator_.get(),
&histogram_data_ptr->counts_ref,
kTypeIdCountsArray, counts_bytes, 0);
DelayedPersistentAllocation logged_data(
memory_allocator_.get(), &histogram_data_ptr->counts_ref,
kTypeIdCountsArray, counts_bytes, counts_bytes / 2,
/*make_iterable=*/false);
const char* name = histogram_data_ptr->name;
std::unique_ptr<HistogramBase> histogram;
switch (histogram_type) {
case HISTOGRAM:
histogram = Histogram::PersistentCreate(
name, histogram_minimum, histogram_maximum, ranges, counts_data,
logged_data, &histogram_data_ptr->samples_metadata,
&histogram_data_ptr->logged_metadata);
DCHECK(histogram);
break;
case LINEAR_HISTOGRAM:
histogram = LinearHistogram::PersistentCreate(
name, histogram_minimum, histogram_maximum, ranges, counts_data,
logged_data, &histogram_data_ptr->samples_metadata,
&histogram_data_ptr->logged_metadata);
DCHECK(histogram);
break;
case BOOLEAN_HISTOGRAM:
histogram = BooleanHistogram::PersistentCreate(
name, ranges, counts_data, logged_data,
&histogram_data_ptr->samples_metadata,
&histogram_data_ptr->logged_metadata);
DCHECK(histogram);
break;
case CUSTOM_HISTOGRAM:
histogram = CustomHistogram::PersistentCreate(
name, ranges, counts_data, logged_data,
&histogram_data_ptr->samples_metadata,
&histogram_data_ptr->logged_metadata);
DCHECK(histogram);
break;
default:
NOTREACHED();
}
if (histogram) {
DCHECK_EQ(histogram_type, histogram->GetHistogramType());
histogram->SetFlags(histogram_flags);
RecordCreateHistogramResult(CREATE_HISTOGRAM_SUCCESS);
} else {
RecordCreateHistogramResult(CREATE_HISTOGRAM_UNKNOWN_TYPE);
}
return histogram;
}
Commit Message: Remove UMA.CreatePersistentHistogram.Result
This histogram isn't showing anything meaningful and the problems it
could show are better observed by looking at the allocators directly.
Bug: 831013
Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9
Reviewed-on: https://chromium-review.googlesource.com/1008047
Commit-Queue: Brian White <[email protected]>
Reviewed-by: Alexei Svitkine <[email protected]>
Cr-Commit-Position: refs/heads/master@{#549986}
CWE ID: CWE-264 | std::unique_ptr<HistogramBase> PersistentHistogramAllocator::CreateHistogram(
PersistentHistogramData* histogram_data_ptr) {
if (!histogram_data_ptr) {
NOTREACHED();
return nullptr;
}
if (histogram_data_ptr->histogram_type == SPARSE_HISTOGRAM) {
std::unique_ptr<HistogramBase> histogram =
SparseHistogram::PersistentCreate(this, histogram_data_ptr->name,
&histogram_data_ptr->samples_metadata,
&histogram_data_ptr->logged_metadata);
DCHECK(histogram);
histogram->SetFlags(histogram_data_ptr->flags);
return histogram;
}
int32_t histogram_type = histogram_data_ptr->histogram_type;
int32_t histogram_flags = histogram_data_ptr->flags;
int32_t histogram_minimum = histogram_data_ptr->minimum;
int32_t histogram_maximum = histogram_data_ptr->maximum;
uint32_t histogram_bucket_count = histogram_data_ptr->bucket_count;
uint32_t histogram_ranges_ref = histogram_data_ptr->ranges_ref;
uint32_t histogram_ranges_checksum = histogram_data_ptr->ranges_checksum;
HistogramBase::Sample* ranges_data =
memory_allocator_->GetAsArray<HistogramBase::Sample>(
histogram_ranges_ref, kTypeIdRangesArray,
PersistentMemoryAllocator::kSizeAny);
const uint32_t max_buckets =
std::numeric_limits<uint32_t>::max() / sizeof(HistogramBase::Sample);
size_t required_bytes =
(histogram_bucket_count + 1) * sizeof(HistogramBase::Sample);
size_t allocated_bytes =
memory_allocator_->GetAllocSize(histogram_ranges_ref);
if (!ranges_data || histogram_bucket_count < 2 ||
histogram_bucket_count >= max_buckets ||
allocated_bytes < required_bytes) {
NOTREACHED();
return nullptr;
}
std::unique_ptr<const BucketRanges> created_ranges = CreateRangesFromData(
ranges_data, histogram_ranges_checksum, histogram_bucket_count + 1);
if (!created_ranges) {
NOTREACHED();
return nullptr;
}
const BucketRanges* ranges =
StatisticsRecorder::RegisterOrDeleteDuplicateRanges(
created_ranges.release());
size_t counts_bytes = CalculateRequiredCountsBytes(histogram_bucket_count);
PersistentMemoryAllocator::Reference counts_ref =
subtle::Acquire_Load(&histogram_data_ptr->counts_ref);
if (counts_bytes == 0 ||
(counts_ref != 0 &&
memory_allocator_->GetAllocSize(counts_ref) < counts_bytes)) {
NOTREACHED();
return nullptr;
}
DelayedPersistentAllocation counts_data(memory_allocator_.get(),
&histogram_data_ptr->counts_ref,
kTypeIdCountsArray, counts_bytes, 0);
DelayedPersistentAllocation logged_data(
memory_allocator_.get(), &histogram_data_ptr->counts_ref,
kTypeIdCountsArray, counts_bytes, counts_bytes / 2,
/*make_iterable=*/false);
const char* name = histogram_data_ptr->name;
std::unique_ptr<HistogramBase> histogram;
switch (histogram_type) {
case HISTOGRAM:
histogram = Histogram::PersistentCreate(
name, histogram_minimum, histogram_maximum, ranges, counts_data,
logged_data, &histogram_data_ptr->samples_metadata,
&histogram_data_ptr->logged_metadata);
DCHECK(histogram);
break;
case LINEAR_HISTOGRAM:
histogram = LinearHistogram::PersistentCreate(
name, histogram_minimum, histogram_maximum, ranges, counts_data,
logged_data, &histogram_data_ptr->samples_metadata,
&histogram_data_ptr->logged_metadata);
DCHECK(histogram);
break;
case BOOLEAN_HISTOGRAM:
histogram = BooleanHistogram::PersistentCreate(
name, ranges, counts_data, logged_data,
&histogram_data_ptr->samples_metadata,
&histogram_data_ptr->logged_metadata);
DCHECK(histogram);
break;
case CUSTOM_HISTOGRAM:
histogram = CustomHistogram::PersistentCreate(
name, ranges, counts_data, logged_data,
&histogram_data_ptr->samples_metadata,
&histogram_data_ptr->logged_metadata);
DCHECK(histogram);
break;
default:
NOTREACHED();
}
if (histogram) {
DCHECK_EQ(histogram_type, histogram->GetHistogramType());
histogram->SetFlags(histogram_flags);
}
return histogram;
}
| 172,132 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static av_cold int vqa_decode_init(AVCodecContext *avctx)
{
VqaContext *s = avctx->priv_data;
int i, j, codebook_index, ret;
s->avctx = avctx;
avctx->pix_fmt = AV_PIX_FMT_PAL8;
/* make sure the extradata made it */
if (s->avctx->extradata_size != VQA_HEADER_SIZE) {
av_log(s->avctx, AV_LOG_ERROR, "expected extradata size of %d\n", VQA_HEADER_SIZE);
return AVERROR(EINVAL);
}
/* load up the VQA parameters from the header */
s->vqa_version = s->avctx->extradata[0];
switch (s->vqa_version) {
case 1:
case 2:
break;
case 3:
avpriv_report_missing_feature(avctx, "VQA Version %d", s->vqa_version);
return AVERROR_PATCHWELCOME;
default:
avpriv_request_sample(avctx, "VQA Version %i", s->vqa_version);
return AVERROR_PATCHWELCOME;
}
s->width = AV_RL16(&s->avctx->extradata[6]);
s->height = AV_RL16(&s->avctx->extradata[8]);
if ((ret = av_image_check_size(s->width, s->height, 0, avctx)) < 0) {
s->width= s->height= 0;
return ret;
}
s->vector_width = s->avctx->extradata[10];
s->vector_height = s->avctx->extradata[11];
s->partial_count = s->partial_countdown = s->avctx->extradata[13];
/* the vector dimensions have to meet very stringent requirements */
if ((s->vector_width != 4) ||
((s->vector_height != 2) && (s->vector_height != 4))) {
/* return without further initialization */
return AVERROR_INVALIDDATA;
}
if (s->width % s->vector_width || s->height % s->vector_height) {
av_log(avctx, AV_LOG_ERROR, "Image size not multiple of block size\n");
return AVERROR_INVALIDDATA;
}
/* allocate codebooks */
s->codebook_size = MAX_CODEBOOK_SIZE;
s->codebook = av_malloc(s->codebook_size);
if (!s->codebook)
goto fail;
s->next_codebook_buffer = av_malloc(s->codebook_size);
if (!s->next_codebook_buffer)
goto fail;
/* allocate decode buffer */
s->decode_buffer_size = (s->width / s->vector_width) *
(s->height / s->vector_height) * 2;
s->decode_buffer = av_mallocz(s->decode_buffer_size);
if (!s->decode_buffer)
goto fail;
/* initialize the solid-color vectors */
if (s->vector_height == 4) {
codebook_index = 0xFF00 * 16;
for (i = 0; i < 256; i++)
for (j = 0; j < 16; j++)
s->codebook[codebook_index++] = i;
} else {
codebook_index = 0xF00 * 8;
for (i = 0; i < 256; i++)
for (j = 0; j < 8; j++)
s->codebook[codebook_index++] = i;
}
s->next_codebook_buffer_index = 0;
return 0;
fail:
av_freep(&s->codebook);
av_freep(&s->next_codebook_buffer);
av_freep(&s->decode_buffer);
return AVERROR(ENOMEM);
}
Commit Message: avcodec/vqavideo: Set video size
Fixes: out of array access
Fixes: 15919/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_VQA_fuzzer-5657368257363968
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: | static av_cold int vqa_decode_init(AVCodecContext *avctx)
{
VqaContext *s = avctx->priv_data;
int i, j, codebook_index, ret;
s->avctx = avctx;
avctx->pix_fmt = AV_PIX_FMT_PAL8;
/* make sure the extradata made it */
if (s->avctx->extradata_size != VQA_HEADER_SIZE) {
av_log(s->avctx, AV_LOG_ERROR, "expected extradata size of %d\n", VQA_HEADER_SIZE);
return AVERROR(EINVAL);
}
/* load up the VQA parameters from the header */
s->vqa_version = s->avctx->extradata[0];
switch (s->vqa_version) {
case 1:
case 2:
break;
case 3:
avpriv_report_missing_feature(avctx, "VQA Version %d", s->vqa_version);
return AVERROR_PATCHWELCOME;
default:
avpriv_request_sample(avctx, "VQA Version %i", s->vqa_version);
return AVERROR_PATCHWELCOME;
}
s->width = AV_RL16(&s->avctx->extradata[6]);
s->height = AV_RL16(&s->avctx->extradata[8]);
if ((ret = ff_set_dimensions(avctx, s->width, s->height)) < 0) {
s->width= s->height= 0;
return ret;
}
s->vector_width = s->avctx->extradata[10];
s->vector_height = s->avctx->extradata[11];
s->partial_count = s->partial_countdown = s->avctx->extradata[13];
/* the vector dimensions have to meet very stringent requirements */
if ((s->vector_width != 4) ||
((s->vector_height != 2) && (s->vector_height != 4))) {
/* return without further initialization */
return AVERROR_INVALIDDATA;
}
if (s->width % s->vector_width || s->height % s->vector_height) {
av_log(avctx, AV_LOG_ERROR, "Image size not multiple of block size\n");
return AVERROR_INVALIDDATA;
}
/* allocate codebooks */
s->codebook_size = MAX_CODEBOOK_SIZE;
s->codebook = av_malloc(s->codebook_size);
if (!s->codebook)
goto fail;
s->next_codebook_buffer = av_malloc(s->codebook_size);
if (!s->next_codebook_buffer)
goto fail;
/* allocate decode buffer */
s->decode_buffer_size = (s->width / s->vector_width) *
(s->height / s->vector_height) * 2;
s->decode_buffer = av_mallocz(s->decode_buffer_size);
if (!s->decode_buffer)
goto fail;
/* initialize the solid-color vectors */
if (s->vector_height == 4) {
codebook_index = 0xFF00 * 16;
for (i = 0; i < 256; i++)
for (j = 0; j < 16; j++)
s->codebook[codebook_index++] = i;
} else {
codebook_index = 0xF00 * 8;
for (i = 0; i < 256; i++)
for (j = 0; j < 8; j++)
s->codebook[codebook_index++] = i;
}
s->next_codebook_buffer_index = 0;
return 0;
fail:
av_freep(&s->codebook);
av_freep(&s->next_codebook_buffer);
av_freep(&s->decode_buffer);
return AVERROR(ENOMEM);
}
| 169,486 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PluginInfoMessageFilter::Context::DecidePluginStatus(
const GetPluginInfo_Params& params,
const WebPluginInfo& plugin,
PluginFinder* plugin_finder,
ChromeViewHostMsg_GetPluginInfo_Status* status,
std::string* group_identifier,
string16* group_name) const {
PluginInstaller* installer = plugin_finder->GetPluginInstaller(plugin);
*group_name = installer->name();
*group_identifier = installer->identifier();
ContentSetting plugin_setting = CONTENT_SETTING_DEFAULT;
bool uses_default_content_setting = true;
GetPluginContentSetting(plugin, params.top_origin_url, params.url,
*group_identifier, &plugin_setting,
&uses_default_content_setting);
DCHECK(plugin_setting != CONTENT_SETTING_DEFAULT);
#if defined(ENABLE_PLUGIN_INSTALLATION)
PluginInstaller::SecurityStatus plugin_status =
installer->GetSecurityStatus(plugin);
if (plugin_status == PluginInstaller::SECURITY_STATUS_OUT_OF_DATE &&
!allow_outdated_plugins_.GetValue()) {
if (allow_outdated_plugins_.IsManaged()) {
status->value =
ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedDisallowed;
} else {
status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedBlocked;
}
return;
}
if ((plugin_status ==
PluginInstaller::SECURITY_STATUS_REQUIRES_AUTHORIZATION ||
PluginService::GetInstance()->IsPluginUnstable(plugin.path)) &&
plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS &&
plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS &&
!always_authorize_plugins_.GetValue() &&
plugin_setting != CONTENT_SETTING_BLOCK &&
uses_default_content_setting) {
status->value = ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized;
return;
}
#endif
if (plugin_setting == CONTENT_SETTING_ASK)
status->value = ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay;
else if (plugin_setting == CONTENT_SETTING_BLOCK)
status->value = ChromeViewHostMsg_GetPluginInfo_Status::kBlocked;
}
Commit Message: Handle crashing Pepper plug-ins the same as crashing NPAPI plug-ins.
BUG=151895
Review URL: https://chromiumcodereview.appspot.com/10956065
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158364 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void PluginInfoMessageFilter::Context::DecidePluginStatus(
const GetPluginInfo_Params& params,
const WebPluginInfo& plugin,
PluginFinder* plugin_finder,
ChromeViewHostMsg_GetPluginInfo_Status* status,
std::string* group_identifier,
string16* group_name) const {
PluginInstaller* installer = plugin_finder->GetPluginInstaller(plugin);
*group_name = installer->name();
*group_identifier = installer->identifier();
ContentSetting plugin_setting = CONTENT_SETTING_DEFAULT;
bool uses_default_content_setting = true;
GetPluginContentSetting(plugin, params.top_origin_url, params.url,
*group_identifier, &plugin_setting,
&uses_default_content_setting);
DCHECK(plugin_setting != CONTENT_SETTING_DEFAULT);
#if defined(ENABLE_PLUGIN_INSTALLATION)
PluginInstaller::SecurityStatus plugin_status =
installer->GetSecurityStatus(plugin);
if (plugin_status == PluginInstaller::SECURITY_STATUS_OUT_OF_DATE &&
!allow_outdated_plugins_.GetValue()) {
if (allow_outdated_plugins_.IsManaged()) {
status->value =
ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedDisallowed;
} else {
status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedBlocked;
}
return;
}
if (plugin_status ==
PluginInstaller::SECURITY_STATUS_REQUIRES_AUTHORIZATION &&
plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS &&
plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS &&
!always_authorize_plugins_.GetValue() &&
plugin_setting != CONTENT_SETTING_BLOCK &&
uses_default_content_setting) {
status->value = ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized;
return;
}
// Check if the plug-in is crashing too much.
if (PluginService::GetInstance()->IsPluginUnstable(plugin.path) &&
!always_authorize_plugins_.GetValue() &&
plugin_setting != CONTENT_SETTING_BLOCK &&
uses_default_content_setting) {
status->value = ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized;
return;
}
#endif
if (plugin_setting == CONTENT_SETTING_ASK)
status->value = ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay;
else if (plugin_setting == CONTENT_SETTING_BLOCK)
status->value = ChromeViewHostMsg_GetPluginInfo_Status::kBlocked;
}
| 170,708 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: pkinit_server_verify_padata(krb5_context context,
krb5_data *req_pkt,
krb5_kdc_req * request,
krb5_enc_tkt_part * enc_tkt_reply,
krb5_pa_data * data,
krb5_kdcpreauth_callbacks cb,
krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata,
krb5_kdcpreauth_verify_respond_fn respond,
void *arg)
{
krb5_error_code retval = 0;
krb5_data authp_data = {0, 0, NULL}, krb5_authz = {0, 0, NULL};
krb5_pa_pk_as_req *reqp = NULL;
krb5_pa_pk_as_req_draft9 *reqp9 = NULL;
krb5_auth_pack *auth_pack = NULL;
krb5_auth_pack_draft9 *auth_pack9 = NULL;
pkinit_kdc_context plgctx = NULL;
pkinit_kdc_req_context reqctx = NULL;
krb5_checksum cksum = {0, 0, 0, NULL};
krb5_data *der_req = NULL;
int valid_eku = 0, valid_san = 0;
krb5_data k5data;
int is_signed = 1;
krb5_pa_data **e_data = NULL;
krb5_kdcpreauth_modreq modreq = NULL;
pkiDebug("pkinit_verify_padata: entered!\n");
if (data == NULL || data->length <= 0 || data->contents == NULL) {
(*respond)(arg, 0, NULL, NULL, NULL);
return;
}
if (moddata == NULL) {
(*respond)(arg, EINVAL, NULL, NULL, NULL);
return;
}
plgctx = pkinit_find_realm_context(context, moddata, request->server);
if (plgctx == NULL) {
(*respond)(arg, 0, NULL, NULL, NULL);
return;
}
#ifdef DEBUG_ASN1
print_buffer_bin(data->contents, data->length, "/tmp/kdc_as_req");
#endif
/* create a per-request context */
retval = pkinit_init_kdc_req_context(context, &reqctx);
if (retval)
goto cleanup;
reqctx->pa_type = data->pa_type;
PADATA_TO_KRB5DATA(data, &k5data);
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
pkiDebug("processing KRB5_PADATA_PK_AS_REQ\n");
retval = k5int_decode_krb5_pa_pk_as_req(&k5data, &reqp);
if (retval) {
pkiDebug("decode_krb5_pa_pk_as_req failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin(reqp->signedAuthPack.data,
reqp->signedAuthPack.length,
"/tmp/kdc_signed_data");
#endif
retval = cms_signeddata_verify(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_CLIENT,
plgctx->opts->require_crl_checking,
(unsigned char *)
reqp->signedAuthPack.data, reqp->signedAuthPack.length,
(unsigned char **)&authp_data.data,
&authp_data.length,
(unsigned char **)&krb5_authz.data,
&krb5_authz.length, &is_signed);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
pkiDebug("processing KRB5_PADATA_PK_AS_REQ_OLD\n");
retval = k5int_decode_krb5_pa_pk_as_req_draft9(&k5data, &reqp9);
if (retval) {
pkiDebug("decode_krb5_pa_pk_as_req_draft9 failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin(reqp9->signedAuthPack.data,
reqp9->signedAuthPack.length,
"/tmp/kdc_signed_data_draft9");
#endif
retval = cms_signeddata_verify(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_DRAFT9,
plgctx->opts->require_crl_checking,
(unsigned char *)
reqp9->signedAuthPack.data, reqp9->signedAuthPack.length,
(unsigned char **)&authp_data.data,
&authp_data.length,
(unsigned char **)&krb5_authz.data,
&krb5_authz.length, NULL);
break;
default:
pkiDebug("unrecognized pa_type = %d\n", data->pa_type);
retval = EINVAL;
goto cleanup;
}
if (retval) {
pkiDebug("pkcs7_signeddata_verify failed\n");
goto cleanup;
}
if (is_signed) {
retval = verify_client_san(context, plgctx, reqctx, request->client,
&valid_san);
if (retval)
goto cleanup;
if (!valid_san) {
pkiDebug("%s: did not find an acceptable SAN in user "
"certificate\n", __FUNCTION__);
retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
goto cleanup;
}
retval = verify_client_eku(context, plgctx, reqctx, &valid_eku);
if (retval)
goto cleanup;
if (!valid_eku) {
pkiDebug("%s: did not find an acceptable EKU in user "
"certificate\n", __FUNCTION__);
retval = KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE;
goto cleanup;
}
} else { /* !is_signed */
if (!krb5_principal_compare(context, request->client,
krb5_anonymous_principal())) {
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval,
_("Pkinit request not signed, but client "
"not anonymous."));
goto cleanup;
}
}
#ifdef DEBUG_ASN1
print_buffer_bin(authp_data.data, authp_data.length, "/tmp/kdc_auth_pack");
#endif
OCTETDATA_TO_KRB5DATA(&authp_data, &k5data);
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
retval = k5int_decode_krb5_auth_pack(&k5data, &auth_pack);
if (retval) {
pkiDebug("failed to decode krb5_auth_pack\n");
goto cleanup;
}
retval = krb5_check_clockskew(context,
auth_pack->pkAuthenticator.ctime);
if (retval)
goto cleanup;
/* check dh parameters */
if (auth_pack->clientPublicValue != NULL) {
retval = server_check_dh(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
&auth_pack->clientPublicValue->algorithm.parameters,
plgctx->opts->dh_min_bits);
if (retval) {
pkiDebug("bad dh parameters\n");
goto cleanup;
}
} else if (!is_signed) {
/*Anonymous pkinit requires DH*/
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval,
_("Anonymous pkinit without DH public "
"value not supported."));
goto cleanup;
}
der_req = cb->request_body(context, rock);
retval = krb5_c_make_checksum(context, CKSUMTYPE_NIST_SHA, NULL,
0, der_req, &cksum);
if (retval) {
pkiDebug("unable to calculate AS REQ checksum\n");
goto cleanup;
}
if (cksum.length != auth_pack->pkAuthenticator.paChecksum.length ||
k5_bcmp(cksum.contents,
auth_pack->pkAuthenticator.paChecksum.contents,
cksum.length) != 0) {
pkiDebug("failed to match the checksum\n");
#ifdef DEBUG_CKSUM
pkiDebug("calculating checksum on buf size (%d)\n",
req_pkt->length);
print_buffer(req_pkt->data, req_pkt->length);
pkiDebug("received checksum type=%d size=%d ",
auth_pack->pkAuthenticator.paChecksum.checksum_type,
auth_pack->pkAuthenticator.paChecksum.length);
print_buffer(auth_pack->pkAuthenticator.paChecksum.contents,
auth_pack->pkAuthenticator.paChecksum.length);
pkiDebug("expected checksum type=%d size=%d ",
cksum.checksum_type, cksum.length);
print_buffer(cksum.contents, cksum.length);
#endif
retval = KRB5KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED;
goto cleanup;
}
/* check if kdcPkId present and match KDC's subjectIdentifier */
if (reqp->kdcPkId.data != NULL) {
int valid_kdcPkId = 0;
retval = pkinit_check_kdc_pkid(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
(unsigned char *)reqp->kdcPkId.data,
reqp->kdcPkId.length, &valid_kdcPkId);
if (retval)
goto cleanup;
if (!valid_kdcPkId)
pkiDebug("kdcPkId in AS_REQ does not match KDC's cert"
"RFC says to ignore and proceed\n");
}
/* remember the decoded auth_pack for verify_padata routine */
reqctx->rcv_auth_pack = auth_pack;
auth_pack = NULL;
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = k5int_decode_krb5_auth_pack_draft9(&k5data, &auth_pack9);
if (retval) {
pkiDebug("failed to decode krb5_auth_pack_draft9\n");
goto cleanup;
}
if (auth_pack9->clientPublicValue != NULL) {
retval = server_check_dh(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
&auth_pack9->clientPublicValue->algorithm.parameters,
plgctx->opts->dh_min_bits);
if (retval) {
pkiDebug("bad dh parameters\n");
goto cleanup;
}
}
/* remember the decoded auth_pack for verify_padata routine */
reqctx->rcv_auth_pack9 = auth_pack9;
auth_pack9 = NULL;
break;
}
/* remember to set the PREAUTH flag in the reply */
enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH;
modreq = (krb5_kdcpreauth_modreq)reqctx;
reqctx = NULL;
cleanup:
if (retval && data->pa_type == KRB5_PADATA_PK_AS_REQ) {
pkiDebug("pkinit_verify_padata failed: creating e-data\n");
if (pkinit_create_edata(context, plgctx->cryptoctx, reqctx->cryptoctx,
plgctx->idctx, plgctx->opts, retval, &e_data))
pkiDebug("pkinit_create_edata failed\n");
}
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
free_krb5_pa_pk_as_req(&reqp);
free(cksum.contents);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
free_krb5_pa_pk_as_req_draft9(&reqp9);
}
free(authp_data.data);
free(krb5_authz.data);
if (reqctx != NULL)
pkinit_fini_kdc_req_context(context, reqctx);
free_krb5_auth_pack(&auth_pack);
free_krb5_auth_pack_draft9(context, &auth_pack9);
(*respond)(arg, retval, modreq, e_data, NULL);
}
Commit Message: Prevent requires_preauth bypass [CVE-2015-2694]
In the OTP kdcpreauth module, don't set the TKT_FLG_PRE_AUTH bit until
the request is successfully verified. In the PKINIT kdcpreauth
module, don't respond with code 0 on empty input or an unconfigured
realm. Together these bugs could cause the KDC preauth framework to
erroneously treat a request as pre-authenticated.
CVE-2015-2694:
In MIT krb5 1.12 and later, when the KDC is configured with PKINIT
support, an unauthenticated remote attacker can bypass the
requires_preauth flag on a client principal and obtain a ciphertext
encrypted in the principal's long-term key. This ciphertext could be
used to conduct an off-line dictionary attack against the user's
password.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:P/I:P/A:N/E:POC/RL:OF/RC:C
ticket: 8160 (new)
target_version: 1.13.2
tags: pullup
subject: requires_preauth bypass in PKINIT-enabled KDC [CVE-2015-2694]
CWE ID: CWE-264 | pkinit_server_verify_padata(krb5_context context,
krb5_data *req_pkt,
krb5_kdc_req * request,
krb5_enc_tkt_part * enc_tkt_reply,
krb5_pa_data * data,
krb5_kdcpreauth_callbacks cb,
krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata,
krb5_kdcpreauth_verify_respond_fn respond,
void *arg)
{
krb5_error_code retval = 0;
krb5_data authp_data = {0, 0, NULL}, krb5_authz = {0, 0, NULL};
krb5_pa_pk_as_req *reqp = NULL;
krb5_pa_pk_as_req_draft9 *reqp9 = NULL;
krb5_auth_pack *auth_pack = NULL;
krb5_auth_pack_draft9 *auth_pack9 = NULL;
pkinit_kdc_context plgctx = NULL;
pkinit_kdc_req_context reqctx = NULL;
krb5_checksum cksum = {0, 0, 0, NULL};
krb5_data *der_req = NULL;
int valid_eku = 0, valid_san = 0;
krb5_data k5data;
int is_signed = 1;
krb5_pa_data **e_data = NULL;
krb5_kdcpreauth_modreq modreq = NULL;
pkiDebug("pkinit_verify_padata: entered!\n");
if (data == NULL || data->length <= 0 || data->contents == NULL) {
(*respond)(arg, EINVAL, NULL, NULL, NULL);
return;
}
if (moddata == NULL) {
(*respond)(arg, EINVAL, NULL, NULL, NULL);
return;
}
plgctx = pkinit_find_realm_context(context, moddata, request->server);
if (plgctx == NULL) {
(*respond)(arg, EINVAL, NULL, NULL, NULL);
return;
}
#ifdef DEBUG_ASN1
print_buffer_bin(data->contents, data->length, "/tmp/kdc_as_req");
#endif
/* create a per-request context */
retval = pkinit_init_kdc_req_context(context, &reqctx);
if (retval)
goto cleanup;
reqctx->pa_type = data->pa_type;
PADATA_TO_KRB5DATA(data, &k5data);
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
pkiDebug("processing KRB5_PADATA_PK_AS_REQ\n");
retval = k5int_decode_krb5_pa_pk_as_req(&k5data, &reqp);
if (retval) {
pkiDebug("decode_krb5_pa_pk_as_req failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin(reqp->signedAuthPack.data,
reqp->signedAuthPack.length,
"/tmp/kdc_signed_data");
#endif
retval = cms_signeddata_verify(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_CLIENT,
plgctx->opts->require_crl_checking,
(unsigned char *)
reqp->signedAuthPack.data, reqp->signedAuthPack.length,
(unsigned char **)&authp_data.data,
&authp_data.length,
(unsigned char **)&krb5_authz.data,
&krb5_authz.length, &is_signed);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
pkiDebug("processing KRB5_PADATA_PK_AS_REQ_OLD\n");
retval = k5int_decode_krb5_pa_pk_as_req_draft9(&k5data, &reqp9);
if (retval) {
pkiDebug("decode_krb5_pa_pk_as_req_draft9 failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin(reqp9->signedAuthPack.data,
reqp9->signedAuthPack.length,
"/tmp/kdc_signed_data_draft9");
#endif
retval = cms_signeddata_verify(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_DRAFT9,
plgctx->opts->require_crl_checking,
(unsigned char *)
reqp9->signedAuthPack.data, reqp9->signedAuthPack.length,
(unsigned char **)&authp_data.data,
&authp_data.length,
(unsigned char **)&krb5_authz.data,
&krb5_authz.length, NULL);
break;
default:
pkiDebug("unrecognized pa_type = %d\n", data->pa_type);
retval = EINVAL;
goto cleanup;
}
if (retval) {
pkiDebug("pkcs7_signeddata_verify failed\n");
goto cleanup;
}
if (is_signed) {
retval = verify_client_san(context, plgctx, reqctx, request->client,
&valid_san);
if (retval)
goto cleanup;
if (!valid_san) {
pkiDebug("%s: did not find an acceptable SAN in user "
"certificate\n", __FUNCTION__);
retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
goto cleanup;
}
retval = verify_client_eku(context, plgctx, reqctx, &valid_eku);
if (retval)
goto cleanup;
if (!valid_eku) {
pkiDebug("%s: did not find an acceptable EKU in user "
"certificate\n", __FUNCTION__);
retval = KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE;
goto cleanup;
}
} else { /* !is_signed */
if (!krb5_principal_compare(context, request->client,
krb5_anonymous_principal())) {
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval,
_("Pkinit request not signed, but client "
"not anonymous."));
goto cleanup;
}
}
#ifdef DEBUG_ASN1
print_buffer_bin(authp_data.data, authp_data.length, "/tmp/kdc_auth_pack");
#endif
OCTETDATA_TO_KRB5DATA(&authp_data, &k5data);
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
retval = k5int_decode_krb5_auth_pack(&k5data, &auth_pack);
if (retval) {
pkiDebug("failed to decode krb5_auth_pack\n");
goto cleanup;
}
retval = krb5_check_clockskew(context,
auth_pack->pkAuthenticator.ctime);
if (retval)
goto cleanup;
/* check dh parameters */
if (auth_pack->clientPublicValue != NULL) {
retval = server_check_dh(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
&auth_pack->clientPublicValue->algorithm.parameters,
plgctx->opts->dh_min_bits);
if (retval) {
pkiDebug("bad dh parameters\n");
goto cleanup;
}
} else if (!is_signed) {
/*Anonymous pkinit requires DH*/
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval,
_("Anonymous pkinit without DH public "
"value not supported."));
goto cleanup;
}
der_req = cb->request_body(context, rock);
retval = krb5_c_make_checksum(context, CKSUMTYPE_NIST_SHA, NULL,
0, der_req, &cksum);
if (retval) {
pkiDebug("unable to calculate AS REQ checksum\n");
goto cleanup;
}
if (cksum.length != auth_pack->pkAuthenticator.paChecksum.length ||
k5_bcmp(cksum.contents,
auth_pack->pkAuthenticator.paChecksum.contents,
cksum.length) != 0) {
pkiDebug("failed to match the checksum\n");
#ifdef DEBUG_CKSUM
pkiDebug("calculating checksum on buf size (%d)\n",
req_pkt->length);
print_buffer(req_pkt->data, req_pkt->length);
pkiDebug("received checksum type=%d size=%d ",
auth_pack->pkAuthenticator.paChecksum.checksum_type,
auth_pack->pkAuthenticator.paChecksum.length);
print_buffer(auth_pack->pkAuthenticator.paChecksum.contents,
auth_pack->pkAuthenticator.paChecksum.length);
pkiDebug("expected checksum type=%d size=%d ",
cksum.checksum_type, cksum.length);
print_buffer(cksum.contents, cksum.length);
#endif
retval = KRB5KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED;
goto cleanup;
}
/* check if kdcPkId present and match KDC's subjectIdentifier */
if (reqp->kdcPkId.data != NULL) {
int valid_kdcPkId = 0;
retval = pkinit_check_kdc_pkid(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
(unsigned char *)reqp->kdcPkId.data,
reqp->kdcPkId.length, &valid_kdcPkId);
if (retval)
goto cleanup;
if (!valid_kdcPkId)
pkiDebug("kdcPkId in AS_REQ does not match KDC's cert"
"RFC says to ignore and proceed\n");
}
/* remember the decoded auth_pack for verify_padata routine */
reqctx->rcv_auth_pack = auth_pack;
auth_pack = NULL;
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = k5int_decode_krb5_auth_pack_draft9(&k5data, &auth_pack9);
if (retval) {
pkiDebug("failed to decode krb5_auth_pack_draft9\n");
goto cleanup;
}
if (auth_pack9->clientPublicValue != NULL) {
retval = server_check_dh(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
&auth_pack9->clientPublicValue->algorithm.parameters,
plgctx->opts->dh_min_bits);
if (retval) {
pkiDebug("bad dh parameters\n");
goto cleanup;
}
}
/* remember the decoded auth_pack for verify_padata routine */
reqctx->rcv_auth_pack9 = auth_pack9;
auth_pack9 = NULL;
break;
}
/* remember to set the PREAUTH flag in the reply */
enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH;
modreq = (krb5_kdcpreauth_modreq)reqctx;
reqctx = NULL;
cleanup:
if (retval && data->pa_type == KRB5_PADATA_PK_AS_REQ) {
pkiDebug("pkinit_verify_padata failed: creating e-data\n");
if (pkinit_create_edata(context, plgctx->cryptoctx, reqctx->cryptoctx,
plgctx->idctx, plgctx->opts, retval, &e_data))
pkiDebug("pkinit_create_edata failed\n");
}
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
free_krb5_pa_pk_as_req(&reqp);
free(cksum.contents);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
free_krb5_pa_pk_as_req_draft9(&reqp9);
}
free(authp_data.data);
free(krb5_authz.data);
if (reqctx != NULL)
pkinit_fini_kdc_req_context(context, reqctx);
free_krb5_auth_pack(&auth_pack);
free_krb5_auth_pack_draft9(context, &auth_pack9);
(*respond)(arg, retval, modreq, e_data, NULL);
}
| 166,678 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MaintainContentLengthPrefsForDateChange(
base::ListValue* original_update,
base::ListValue* received_update,
int days_since_last_update) {
if (days_since_last_update == -1) {
days_since_last_update = 0;
} else if (days_since_last_update < -1) {
original_update->Clear();
received_update->Clear();
days_since_last_update = kNumDaysInHistory;
//// DailyContentLengthUpdate maintains a data saving pref. The pref is a list
//// of |kNumDaysInHistory| elements of daily total content lengths for the past
//// |kNumDaysInHistory| days.
}
DCHECK_GE(days_since_last_update, 0);
for (int i = 0;
i < days_since_last_update && i < static_cast<int>(kNumDaysInHistory);
++i) {
original_update->AppendString(base::Int64ToString(0));
received_update->AppendString(base::Int64ToString(0));
}
MaintainContentLengthPrefsWindow(original_update, kNumDaysInHistory);
MaintainContentLengthPrefsWindow(received_update, kNumDaysInHistory);
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416 | void MaintainContentLengthPrefsForDateChange(
//// DailyContentLengthUpdate maintains a data saving pref. The pref is a list
//// of |kNumDaysInHistory| elements of daily total content lengths for the past
//// |kNumDaysInHistory| days.
class DailyContentLengthUpdate {
public:
DailyContentLengthUpdate(
const char* pref,
PrefService* pref_service)
: update_(pref_service, pref) {
}
void UpdateForDataChange(int days_since_last_update) {
// New empty lists may have been created. Maintain the invariant that
// there should be exactly |kNumDaysInHistory| days in the histories.
MaintainContentLengthPrefsWindow(update_.Get(), kNumDaysInHistory);
if (days_since_last_update) {
MaintainContentLengthPrefForDateChange(days_since_last_update);
}
}
| 171,325 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void mlock_vma_page(struct page *page)
{
BUG_ON(!PageLocked(page));
if (!TestSetPageMlocked(page)) {
mod_zone_page_state(page_zone(page), NR_MLOCK,
hpage_nr_pages(page));
count_vm_event(UNEVICTABLE_PGMLOCKED);
if (!isolate_lru_page(page))
putback_lru_page(page);
}
}
Commit Message: mm: try_to_unmap_cluster() should lock_page() before mlocking
A BUG_ON(!PageLocked) was triggered in mlock_vma_page() by Sasha Levin
fuzzing with trinity. The call site try_to_unmap_cluster() does not lock
the pages other than its check_page parameter (which is already locked).
The BUG_ON in mlock_vma_page() is not documented and its purpose is
somewhat unclear, but apparently it serializes against page migration,
which could otherwise fail to transfer the PG_mlocked flag. This would
not be fatal, as the page would be eventually encountered again, but
NR_MLOCK accounting would become distorted nevertheless. This patch adds
a comment to the BUG_ON in mlock_vma_page() and munlock_vma_page() to that
effect.
The call site try_to_unmap_cluster() is fixed so that for page !=
check_page, trylock_page() is attempted (to avoid possible deadlocks as we
already have check_page locked) and mlock_vma_page() is performed only
upon success. If the page lock cannot be obtained, the page is left
without PG_mlocked, which is again not a problem in the whole unevictable
memory design.
Signed-off-by: Vlastimil Babka <[email protected]>
Signed-off-by: Bob Liu <[email protected]>
Reported-by: Sasha Levin <[email protected]>
Cc: Wanpeng Li <[email protected]>
Cc: Michel Lespinasse <[email protected]>
Cc: KOSAKI Motohiro <[email protected]>
Acked-by: Rik van Riel <[email protected]>
Cc: David Rientjes <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Joonsoo Kim <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | void mlock_vma_page(struct page *page)
{
/* Serialize with page migration */
BUG_ON(!PageLocked(page));
if (!TestSetPageMlocked(page)) {
mod_zone_page_state(page_zone(page), NR_MLOCK,
hpage_nr_pages(page));
count_vm_event(UNEVICTABLE_PGMLOCKED);
if (!isolate_lru_page(page))
putback_lru_page(page);
}
}
| 166,385 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DownloadFileManager::CompleteDownload(DownloadId global_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
if (!ContainsKey(downloads_, global_id))
return;
DownloadFile* download_file = downloads_[global_id];
VLOG(20) << " " << __FUNCTION__ << "()"
<< " id = " << global_id
<< " download_file = " << download_file->DebugString();
download_file->Detach();
EraseDownload(global_id);
}
Commit Message: Refactors to simplify rename pathway in DownloadFileManager.
This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted
due to CrOS failure) with the completion logic moved to after the
auto-opening. The tests that test the auto-opening (for web store install)
were waiting for download completion to check install, and hence were
failing when completion was moved earlier.
Doing this right would probably require another state (OPENED).
BUG=123998
BUG-134930
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10701040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void DownloadFileManager::CompleteDownload(DownloadId global_id) {
void DownloadFileManager::CompleteDownload(
DownloadId global_id, const base::Closure& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
if (!ContainsKey(downloads_, global_id))
return;
DownloadFile* download_file = downloads_[global_id];
VLOG(20) << " " << __FUNCTION__ << "()"
<< " id = " << global_id
<< " download_file = " << download_file->DebugString();
// Done here on Windows so that anti-virus scanners invoked by
// the attachment service actually see the data; see
// http://crbug.com/127999.
// Done here for mac because we only want to do this once; see
// http://crbug.com/13120 for details.
// Other platforms don't currently do source annotation.
download_file->AnnotateWithSourceInformation();
download_file->Detach();
EraseDownload(global_id);
// Notify our caller we've let it go.
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback);
}
| 170,876 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int sockfs_setattr(struct dentry *dentry, struct iattr *iattr)
{
int err = simple_setattr(dentry, iattr);
if (!err && (iattr->ia_valid & ATTR_UID)) {
struct socket *sock = SOCKET_I(d_inode(dentry));
sock->sk->sk_uid = iattr->ia_uid;
}
return err;
}
Commit Message: socket: close race condition between sock_close() and sockfs_setattr()
fchownat() doesn't even hold refcnt of fd until it figures out
fd is really needed (otherwise is ignored) and releases it after
it resolves the path. This means sock_close() could race with
sockfs_setattr(), which leads to a NULL pointer dereference
since typically we set sock->sk to NULL in ->release().
As pointed out by Al, this is unique to sockfs. So we can fix this
in socket layer by acquiring inode_lock in sock_close() and
checking against NULL in sockfs_setattr().
sock_release() is called in many places, only the sock_close()
path matters here. And fortunately, this should not affect normal
sock_close() as it is only called when the last fd refcnt is gone.
It only affects sock_close() with a parallel sockfs_setattr() in
progress, which is not common.
Fixes: 86741ec25462 ("net: core: Add a UID field to struct sock.")
Reported-by: shankarapailoor <[email protected]>
Cc: Tetsuo Handa <[email protected]>
Cc: Lorenzo Colitti <[email protected]>
Cc: Al Viro <[email protected]>
Signed-off-by: Cong Wang <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static int sockfs_setattr(struct dentry *dentry, struct iattr *iattr)
{
int err = simple_setattr(dentry, iattr);
if (!err && (iattr->ia_valid & ATTR_UID)) {
struct socket *sock = SOCKET_I(d_inode(dentry));
if (sock->sk)
sock->sk->sk_uid = iattr->ia_uid;
else
err = -ENOENT;
}
return err;
}
| 169,205 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Browser::SetWebContentsBlocked(content::WebContents* web_contents,
bool blocked) {
int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
if (index == TabStripModel::kNoTab) {
return;
}
tab_strip_model_->SetTabBlocked(index, blocked);
bool browser_active = BrowserList::GetInstance()->GetLastActive() == this;
bool contents_is_active =
tab_strip_model_->GetActiveWebContents() == web_contents;
if (!blocked && contents_is_active && browser_active)
web_contents->Focus();
}
Commit Message: If a dialog is shown, drop fullscreen.
BUG=875066, 817809, 792876, 812769, 813815
TEST=included
Change-Id: Ic3d697fa3c4b01f5d7fea77391857177ada660db
Reviewed-on: https://chromium-review.googlesource.com/1185208
Reviewed-by: Sidney San Martín <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#586418}
CWE ID: CWE-20 | void Browser::SetWebContentsBlocked(content::WebContents* web_contents,
bool blocked) {
int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
if (index == TabStripModel::kNoTab) {
return;
}
// For security, if the WebContents is in fullscreen, have it drop fullscreen.
// This gives the user the context they need in order to make informed
// decisions.
if (web_contents->IsFullscreenForCurrentTab())
web_contents->ExitFullscreen(true);
tab_strip_model_->SetTabBlocked(index, blocked);
bool browser_active = BrowserList::GetInstance()->GetLastActive() == this;
bool contents_is_active =
tab_strip_model_->GetActiveWebContents() == web_contents;
if (!blocked && contents_is_active && browser_active)
web_contents->Focus();
}
| 172,664 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool Get(const std::string& addr, int* out_value) {
base::AutoLock lock(lock_);
PrintPreviewRequestIdMap::const_iterator it = map_.find(addr);
if (it == map_.end())
return false;
*out_value = it->second;
return true;
}
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 | bool Get(const std::string& addr, int* out_value) {
// Gets the value for |preview_id|.
// Returns true and sets |out_value| on success.
bool Get(int32 preview_id, int* out_value) {
base::AutoLock lock(lock_);
PrintPreviewRequestIdMap::const_iterator it = map_.find(preview_id);
if (it == map_.end())
return false;
*out_value = it->second;
return true;
}
| 170,831 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int sock_send_all(int sock_fd, const uint8_t* buf, int len)
{
int s = len;
int ret;
while(s)
{
do ret = send(sock_fd, buf, s, 0);
while(ret < 0 && errno == EINTR);
if(ret <= 0)
{
BTIF_TRACE_ERROR("sock fd:%d send errno:%d, ret:%d", sock_fd, errno, ret);
return -1;
}
buf += ret;
s -= ret;
}
return len;
}
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 sock_send_all(int sock_fd, const uint8_t* buf, int len)
{
int s = len;
int ret;
while(s)
{
do ret = TEMP_FAILURE_RETRY(send(sock_fd, buf, s, 0));
while(ret < 0 && errno == EINTR);
if(ret <= 0)
{
BTIF_TRACE_ERROR("sock fd:%d send errno:%d, ret:%d", sock_fd, errno, ret);
return -1;
}
buf += ret;
s -= ret;
}
return len;
}
| 173,469 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport MagickBooleanType SetImageType(Image *image,const ImageType type)
{
const char
*artifact;
ImageInfo
*image_info;
MagickBooleanType
status;
QuantizeInfo
*quantize_info;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickSignature);
status=MagickTrue;
image_info=AcquireImageInfo();
image_info->dither=image->dither;
artifact=GetImageArtifact(image,"dither");
if (artifact != (const char *) NULL)
(void) SetImageOption(image_info,"dither",artifact);
switch (type)
{
case BilevelType:
{
if (SetImageMonochrome(image,&image->exception) == MagickFalse)
{
status=TransformImageColorspace(image,GRAYColorspace);
(void) NormalizeImage(image);
quantize_info=AcquireQuantizeInfo(image_info);
quantize_info->number_colors=2;
quantize_info->colorspace=GRAYColorspace;
status=QuantizeImage(quantize_info,image);
quantize_info=DestroyQuantizeInfo(quantize_info);
}
image->colors=2;
image->matte=MagickFalse;
break;
}
case GrayscaleType:
{
if (SetImageGray(image,&image->exception) == MagickFalse)
status=TransformImageColorspace(image,GRAYColorspace);
image->matte=MagickFalse;
break;
}
case GrayscaleMatteType:
{
if (SetImageGray(image,&image->exception) == MagickFalse)
status=TransformImageColorspace(image,GRAYColorspace);
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
break;
}
case PaletteType:
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace);
if ((image->storage_class == DirectClass) || (image->colors > 256))
{
quantize_info=AcquireQuantizeInfo(image_info);
quantize_info->number_colors=256;
status=QuantizeImage(quantize_info,image);
quantize_info=DestroyQuantizeInfo(quantize_info);
}
image->matte=MagickFalse;
break;
}
case PaletteBilevelMatteType:
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace);
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
(void) BilevelImageChannel(image,AlphaChannel,(double) QuantumRange/2.0);
quantize_info=AcquireQuantizeInfo(image_info);
status=QuantizeImage(quantize_info,image);
quantize_info=DestroyQuantizeInfo(quantize_info);
break;
}
case PaletteMatteType:
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace);
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
quantize_info=AcquireQuantizeInfo(image_info);
quantize_info->colorspace=TransparentColorspace;
status=QuantizeImage(quantize_info,image);
quantize_info=DestroyQuantizeInfo(quantize_info);
break;
}
case TrueColorType:
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace);
if (image->storage_class != DirectClass)
status=SetImageStorageClass(image,DirectClass);
image->matte=MagickFalse;
break;
}
case TrueColorMatteType:
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace);
if (image->storage_class != DirectClass)
status=SetImageStorageClass(image,DirectClass);
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
break;
}
case ColorSeparationType:
{
if (image->colorspace != CMYKColorspace)
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
status=TransformImageColorspace(image,CMYKColorspace);
}
if (image->storage_class != DirectClass)
status=SetImageStorageClass(image,DirectClass);
image->matte=MagickFalse;
break;
}
case ColorSeparationMatteType:
{
if (image->colorspace != CMYKColorspace)
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
status=TransformImageColorspace(image,CMYKColorspace);
}
if (image->storage_class != DirectClass)
status=SetImageStorageClass(image,DirectClass);
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
break;
}
case OptimizeType:
case UndefinedType:
break;
}
image_info=DestroyImageInfo(image_info);
if (status == MagickFalse)
return(MagickFalse);
image->type=type;
return(MagickTrue);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/281
CWE ID: CWE-416 | MagickExport MagickBooleanType SetImageType(Image *image,const ImageType type)
{
const char
*artifact;
ImageInfo
*image_info;
MagickBooleanType
status;
QuantizeInfo
*quantize_info;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickSignature);
status=MagickTrue;
image_info=AcquireImageInfo();
image_info->dither=image->dither;
artifact=GetImageArtifact(image,"dither");
if (artifact != (const char *) NULL)
(void) SetImageOption(image_info,"dither",artifact);
switch (type)
{
case BilevelType:
{
if (SetImageMonochrome(image,&image->exception) == MagickFalse)
{
status=TransformImageColorspace(image,GRAYColorspace);
(void) NormalizeImage(image);
quantize_info=AcquireQuantizeInfo(image_info);
quantize_info->number_colors=2;
quantize_info->colorspace=GRAYColorspace;
status=QuantizeImage(quantize_info,image);
quantize_info=DestroyQuantizeInfo(quantize_info);
}
status=AcquireImageColormap(image,2);
image->matte=MagickFalse;
break;
}
case GrayscaleType:
{
if (SetImageGray(image,&image->exception) == MagickFalse)
status=TransformImageColorspace(image,GRAYColorspace);
image->matte=MagickFalse;
break;
}
case GrayscaleMatteType:
{
if (SetImageGray(image,&image->exception) == MagickFalse)
status=TransformImageColorspace(image,GRAYColorspace);
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
break;
}
case PaletteType:
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace);
if ((image->storage_class == DirectClass) || (image->colors > 256))
{
quantize_info=AcquireQuantizeInfo(image_info);
quantize_info->number_colors=256;
status=QuantizeImage(quantize_info,image);
quantize_info=DestroyQuantizeInfo(quantize_info);
}
image->matte=MagickFalse;
break;
}
case PaletteBilevelMatteType:
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace);
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
(void) BilevelImageChannel(image,AlphaChannel,(double) QuantumRange/2.0);
quantize_info=AcquireQuantizeInfo(image_info);
status=QuantizeImage(quantize_info,image);
quantize_info=DestroyQuantizeInfo(quantize_info);
break;
}
case PaletteMatteType:
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace);
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
quantize_info=AcquireQuantizeInfo(image_info);
quantize_info->colorspace=TransparentColorspace;
status=QuantizeImage(quantize_info,image);
quantize_info=DestroyQuantizeInfo(quantize_info);
break;
}
case TrueColorType:
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace);
if (image->storage_class != DirectClass)
status=SetImageStorageClass(image,DirectClass);
image->matte=MagickFalse;
break;
}
case TrueColorMatteType:
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace);
if (image->storage_class != DirectClass)
status=SetImageStorageClass(image,DirectClass);
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
break;
}
case ColorSeparationType:
{
if (image->colorspace != CMYKColorspace)
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
status=TransformImageColorspace(image,CMYKColorspace);
}
if (image->storage_class != DirectClass)
status=SetImageStorageClass(image,DirectClass);
image->matte=MagickFalse;
break;
}
case ColorSeparationMatteType:
{
if (image->colorspace != CMYKColorspace)
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
status=TransformImageColorspace(image,CMYKColorspace);
}
if (image->storage_class != DirectClass)
status=SetImageStorageClass(image,DirectClass);
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
break;
}
case OptimizeType:
case UndefinedType:
break;
}
image_info=DestroyImageInfo(image_info);
if (status == MagickFalse)
return(MagickFalse);
image->type=type;
return(MagickTrue);
}
| 168,776 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CrosLibrary::TestApi::SetScreenLockLibrary(
ScreenLockLibrary* library, bool own) {
library_->screen_lock_lib_.SetImpl(library, own);
}
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 | void CrosLibrary::TestApi::SetScreenLockLibrary(
| 170,644 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool RenderMenuList::multiple()
{
return toHTMLSelectElement(node())->multiple();
}
Commit Message: PopupMenuClient::multiple() should be const
https://bugs.webkit.org/show_bug.cgi?id=76771
Patch by Benjamin Poulain <[email protected]> on 2012-01-21
Reviewed by Kent Tamura.
* platform/PopupMenuClient.h:
(WebCore::PopupMenuClient::multiple):
* rendering/RenderMenuList.cpp:
(WebCore::RenderMenuList::multiple):
* rendering/RenderMenuList.h:
git-svn-id: svn://svn.chromium.org/blink/trunk@105570 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | bool RenderMenuList::multiple()
bool RenderMenuList::multiple() const
{
return toHTMLSelectElement(node())->multiple();
}
| 170,300 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ZSTD_buildCTable(void* dst, size_t dstCapacity,
FSE_CTable* nextCTable, U32 FSELog, symbolEncodingType_e type,
U32* count, U32 max,
const BYTE* codeTable, size_t nbSeq,
const S16* defaultNorm, U32 defaultNormLog, U32 defaultMax,
const FSE_CTable* prevCTable, size_t prevCTableSize,
void* workspace, size_t workspaceSize)
{
BYTE* op = (BYTE*)dst;
const BYTE* const oend = op + dstCapacity;
switch (type) {
case set_rle:
*op = codeTable[0];
CHECK_F(FSE_buildCTable_rle(nextCTable, (BYTE)max));
return 1;
case set_repeat:
memcpy(nextCTable, prevCTable, prevCTableSize);
return 0;
case set_basic:
CHECK_F(FSE_buildCTable_wksp(nextCTable, defaultNorm, defaultMax, defaultNormLog, workspace, workspaceSize)); /* note : could be pre-calculated */
return 0;
case set_compressed: {
S16 norm[MaxSeq + 1];
size_t nbSeq_1 = nbSeq;
const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max);
if (count[codeTable[nbSeq-1]] > 1) {
count[codeTable[nbSeq-1]]--;
nbSeq_1--;
}
assert(nbSeq_1 > 1);
CHECK_F(FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max));
{ size_t const NCountSize = FSE_writeNCount(op, oend - op, norm, max, tableLog); /* overflow protected */
if (FSE_isError(NCountSize)) return NCountSize;
CHECK_F(FSE_buildCTable_wksp(nextCTable, norm, max, tableLog, workspace, workspaceSize));
return NCountSize;
}
}
default: return assert(0), ERROR(GENERIC);
}
}
Commit Message: fixed T36302429
CWE ID: CWE-362 | ZSTD_buildCTable(void* dst, size_t dstCapacity,
FSE_CTable* nextCTable, U32 FSELog, symbolEncodingType_e type,
U32* count, U32 max,
const BYTE* codeTable, size_t nbSeq,
const S16* defaultNorm, U32 defaultNormLog, U32 defaultMax,
const FSE_CTable* prevCTable, size_t prevCTableSize,
void* workspace, size_t workspaceSize)
{
BYTE* op = (BYTE*)dst;
const BYTE* const oend = op + dstCapacity;
DEBUGLOG(6, "ZSTD_buildCTable (dstCapacity=%u)", (unsigned)dstCapacity);
switch (type) {
case set_rle:
CHECK_F(FSE_buildCTable_rle(nextCTable, (BYTE)max));
if (dstCapacity==0) return ERROR(dstSize_tooSmall);
*op = codeTable[0];
return 1;
case set_repeat:
memcpy(nextCTable, prevCTable, prevCTableSize);
return 0;
case set_basic:
CHECK_F(FSE_buildCTable_wksp(nextCTable, defaultNorm, defaultMax, defaultNormLog, workspace, workspaceSize)); /* note : could be pre-calculated */
return 0;
case set_compressed: {
S16 norm[MaxSeq + 1];
size_t nbSeq_1 = nbSeq;
const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max);
if (count[codeTable[nbSeq-1]] > 1) {
count[codeTable[nbSeq-1]]--;
nbSeq_1--;
}
assert(nbSeq_1 > 1);
CHECK_F(FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max));
{ size_t const NCountSize = FSE_writeNCount(op, oend - op, norm, max, tableLog); /* overflow protected */
if (FSE_isError(NCountSize)) return NCountSize;
CHECK_F(FSE_buildCTable_wksp(nextCTable, norm, max, tableLog, workspace, workspaceSize));
return NCountSize;
}
}
default: return assert(0), ERROR(GENERIC);
}
}
| 169,671 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void hostap_setup_dev(struct net_device *dev, local_info_t *local,
int type)
{
struct hostap_interface *iface;
iface = netdev_priv(dev);
ether_setup(dev);
/* kernel callbacks */
if (iface) {
/* Currently, we point to the proper spy_data only on
* the main_dev. This could be fixed. Jean II */
iface->wireless_data.spy_data = &iface->spy_data;
dev->wireless_data = &iface->wireless_data;
}
dev->wireless_handlers = &hostap_iw_handler_def;
dev->watchdog_timeo = TX_TIMEOUT;
switch(type) {
case HOSTAP_INTERFACE_AP:
dev->tx_queue_len = 0; /* use main radio device queue */
dev->netdev_ops = &hostap_mgmt_netdev_ops;
dev->type = ARPHRD_IEEE80211;
dev->header_ops = &hostap_80211_ops;
break;
case HOSTAP_INTERFACE_MASTER:
dev->netdev_ops = &hostap_master_ops;
break;
default:
dev->tx_queue_len = 0; /* use main radio device queue */
dev->netdev_ops = &hostap_netdev_ops;
}
dev->mtu = local->mtu;
SET_ETHTOOL_OPS(dev, &prism2_ethtool_ops);
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264 | void hostap_setup_dev(struct net_device *dev, local_info_t *local,
int type)
{
struct hostap_interface *iface;
iface = netdev_priv(dev);
ether_setup(dev);
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
/* kernel callbacks */
if (iface) {
/* Currently, we point to the proper spy_data only on
* the main_dev. This could be fixed. Jean II */
iface->wireless_data.spy_data = &iface->spy_data;
dev->wireless_data = &iface->wireless_data;
}
dev->wireless_handlers = &hostap_iw_handler_def;
dev->watchdog_timeo = TX_TIMEOUT;
switch(type) {
case HOSTAP_INTERFACE_AP:
dev->tx_queue_len = 0; /* use main radio device queue */
dev->netdev_ops = &hostap_mgmt_netdev_ops;
dev->type = ARPHRD_IEEE80211;
dev->header_ops = &hostap_80211_ops;
break;
case HOSTAP_INTERFACE_MASTER:
dev->netdev_ops = &hostap_master_ops;
break;
default:
dev->tx_queue_len = 0; /* use main radio device queue */
dev->netdev_ops = &hostap_netdev_ops;
}
dev->mtu = local->mtu;
SET_ETHTOOL_OPS(dev, &prism2_ethtool_ops);
}
| 165,734 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ext2_xattr_put_super(struct super_block *sb)
{
mb_cache_shrink(sb->s_bdev);
}
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19 | ext2_xattr_put_super(struct super_block *sb)
| 169,982 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: mobility_opt_print(netdissect_options *ndo,
const u_char *bp, const unsigned len)
{
unsigned i, optlen;
for (i = 0; i < len; i += optlen) {
ND_TCHECK(bp[i]);
if (bp[i] == IP6MOPT_PAD1)
optlen = 1;
else {
if (i + 1 < len) {
ND_TCHECK(bp[i + 1]);
optlen = bp[i + 1] + 2;
}
else
goto trunc;
}
if (i + optlen > len)
goto trunc;
ND_TCHECK(bp[i + optlen]);
switch (bp[i]) {
case IP6MOPT_PAD1:
ND_PRINT((ndo, "(pad1)"));
break;
case IP6MOPT_PADN:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(padn: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(padn)"));
break;
case IP6MOPT_REFRESH:
if (len - i < IP6MOPT_REFRESH_MINLEN) {
ND_PRINT((ndo, "(refresh: trunc)"));
goto trunc;
}
/* units of 4 secs */
ND_TCHECK_16BITS(&bp[i+2]);
ND_PRINT((ndo, "(refresh: %u)",
EXTRACT_16BITS(&bp[i+2]) << 2));
break;
case IP6MOPT_ALTCOA:
if (len - i < IP6MOPT_ALTCOA_MINLEN) {
ND_PRINT((ndo, "(altcoa: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2])));
break;
case IP6MOPT_NONCEID:
if (len - i < IP6MOPT_NONCEID_MINLEN) {
ND_PRINT((ndo, "(ni: trunc)"));
goto trunc;
}
ND_TCHECK_16BITS(&bp[i+2]);
ND_TCHECK_16BITS(&bp[i+4]);
ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)",
EXTRACT_16BITS(&bp[i+2]),
EXTRACT_16BITS(&bp[i+4])));
break;
case IP6MOPT_AUTH:
if (len - i < IP6MOPT_AUTH_MINLEN) {
ND_PRINT((ndo, "(auth: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(auth)"));
break;
default:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i]));
goto trunc;
}
ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1]));
break;
}
}
return 0;
trunc:
return 1;
}
Commit Message: CVE-2017-13025/IPv6 mobility: Add a bounds check before fetching data
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't cause 'tcpdump: pcap_loop: truncated dump file'
CWE ID: CWE-125 | mobility_opt_print(netdissect_options *ndo,
const u_char *bp, const unsigned len)
{
unsigned i, optlen;
for (i = 0; i < len; i += optlen) {
ND_TCHECK(bp[i]);
if (bp[i] == IP6MOPT_PAD1)
optlen = 1;
else {
if (i + 1 < len) {
ND_TCHECK(bp[i + 1]);
optlen = bp[i + 1] + 2;
}
else
goto trunc;
}
if (i + optlen > len)
goto trunc;
ND_TCHECK(bp[i + optlen]);
switch (bp[i]) {
case IP6MOPT_PAD1:
ND_PRINT((ndo, "(pad1)"));
break;
case IP6MOPT_PADN:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(padn: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(padn)"));
break;
case IP6MOPT_REFRESH:
if (len - i < IP6MOPT_REFRESH_MINLEN) {
ND_PRINT((ndo, "(refresh: trunc)"));
goto trunc;
}
/* units of 4 secs */
ND_TCHECK_16BITS(&bp[i+2]);
ND_PRINT((ndo, "(refresh: %u)",
EXTRACT_16BITS(&bp[i+2]) << 2));
break;
case IP6MOPT_ALTCOA:
if (len - i < IP6MOPT_ALTCOA_MINLEN) {
ND_PRINT((ndo, "(altcoa: trunc)"));
goto trunc;
}
ND_TCHECK_128BITS(&bp[i+2]);
ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2])));
break;
case IP6MOPT_NONCEID:
if (len - i < IP6MOPT_NONCEID_MINLEN) {
ND_PRINT((ndo, "(ni: trunc)"));
goto trunc;
}
ND_TCHECK_16BITS(&bp[i+2]);
ND_TCHECK_16BITS(&bp[i+4]);
ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)",
EXTRACT_16BITS(&bp[i+2]),
EXTRACT_16BITS(&bp[i+4])));
break;
case IP6MOPT_AUTH:
if (len - i < IP6MOPT_AUTH_MINLEN) {
ND_PRINT((ndo, "(auth: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(auth)"));
break;
default:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i]));
goto trunc;
}
ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1]));
break;
}
}
return 0;
trunc:
return 1;
}
| 167,866 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: file_trycdf(struct magic_set *ms, int fd, const unsigned char *buf,
size_t nbytes)
{
cdf_info_t info;
cdf_header_t h;
cdf_sat_t sat, ssat;
cdf_stream_t sst, scn;
cdf_dir_t dir;
int i;
const char *expn = "";
const char *corrupt = "corrupt: ";
info.i_fd = fd;
info.i_buf = buf;
info.i_len = nbytes;
if (ms->flags & MAGIC_APPLE)
return 0;
if (cdf_read_header(&info, &h) == -1)
return 0;
#ifdef CDF_DEBUG
cdf_dump_header(&h);
#endif
if ((i = cdf_read_sat(&info, &h, &sat)) == -1) {
expn = "Can't read SAT";
goto out0;
}
#ifdef CDF_DEBUG
cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h));
#endif
if ((i = cdf_read_ssat(&info, &h, &sat, &ssat)) == -1) {
expn = "Can't read SSAT";
goto out1;
}
#ifdef CDF_DEBUG
cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h));
#endif
if ((i = cdf_read_dir(&info, &h, &sat, &dir)) == -1) {
expn = "Can't read directory";
goto out2;
}
const cdf_directory_t *root_storage;
if ((i = cdf_read_short_stream(&info, &h, &sat, &dir, &sst,
&root_storage)) == -1) {
expn = "Cannot read short stream";
goto out3;
}
#ifdef CDF_DEBUG
cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir);
#endif
#ifdef notdef
if (root_storage) {
if (NOTMIME(ms)) {
char clsbuf[128];
if (file_printf(ms, "CLSID %s, ",
format_clsid(clsbuf, sizeof(clsbuf),
root_storage->d_storage_uuid)) == -1)
return -1;
}
}
#endif
if ((i = cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir,
&scn)) == -1) {
if (errno == ESRCH) {
corrupt = expn;
expn = "No summary info";
} else {
expn = "Cannot read summary info";
}
goto out4;
}
#ifdef CDF_DEBUG
cdf_dump_summary_info(&h, &scn);
#endif
if ((i = cdf_file_summary_info(ms, &h, &scn,
root_storage->d_storage_uuid)) < 0)
expn = "Can't expand summary_info";
if (i == 0) {
const char *str = NULL;
cdf_directory_t *d;
char name[__arraycount(d->d_name)];
size_t j, k;
for (j = 0; str == NULL && j < dir.dir_len; j++) {
d = &dir.dir_tab[j];
for (k = 0; k < sizeof(name); k++)
name[k] = (char)cdf_tole2(d->d_name[k]);
str = cdf_app_to_mime(name,
NOTMIME(ms) ? name2desc : name2mime);
}
if (NOTMIME(ms)) {
if (str != NULL) {
if (file_printf(ms, "%s", str) == -1)
return -1;
i = 1;
}
} else {
if (str == NULL)
str = "vnd.ms-office";
if (file_printf(ms, "application/%s", str) == -1)
return -1;
i = 1;
}
}
free(scn.sst_tab);
out4:
free(sst.sst_tab);
out3:
free(dir.dir_tab);
out2:
free(ssat.sat_tab);
out1:
free(sat.sat_tab);
out0:
if (i == -1) {
if (NOTMIME(ms)) {
if (file_printf(ms,
"Composite Document File V2 Document") == -1)
return -1;
if (*expn)
if (file_printf(ms, ", %s%s", corrupt, expn) == -1)
return -1;
} else {
if (file_printf(ms, "application/CDFV2-corrupt") == -1)
return -1;
}
i = 1;
}
return i;
}
Commit Message: Apply patches from file-CVE-2012-1571.patch
From Francisco Alonso Espejo:
file < 5.18/git version can be made to crash when checking some
corrupt CDF files (Using an invalid cdf_read_short_sector size)
The problem I found here, is that in most situations (if
h_short_sec_size_p2 > 8) because the blocksize is 512 and normal
values are 06 which means reading 64 bytes.As long as the check
for the block size copy is not checked properly (there's an assert
that makes wrong/invalid assumptions)
CWE ID: CWE-119 | file_trycdf(struct magic_set *ms, int fd, const unsigned char *buf,
size_t nbytes)
{
cdf_info_t info;
cdf_header_t h;
cdf_sat_t sat, ssat;
cdf_stream_t sst, scn;
cdf_dir_t dir;
int i;
const char *expn = "";
const char *corrupt = "corrupt: ";
info.i_fd = fd;
info.i_buf = buf;
info.i_len = nbytes;
if (ms->flags & MAGIC_APPLE)
return 0;
if (cdf_read_header(&info, &h) == -1)
return 0;
#ifdef CDF_DEBUG
cdf_dump_header(&h);
#endif
if ((i = cdf_read_sat(&info, &h, &sat)) == -1) {
expn = "Can't read SAT";
goto out0;
}
#ifdef CDF_DEBUG
cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h));
#endif
if ((i = cdf_read_ssat(&info, &h, &sat, &ssat)) == -1) {
expn = "Can't read SSAT";
goto out1;
}
#ifdef CDF_DEBUG
cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h));
#endif
if ((i = cdf_read_dir(&info, &h, &sat, &dir)) == -1) {
expn = "Can't read directory";
goto out2;
}
const cdf_directory_t *root_storage;
if ((i = cdf_read_short_stream(&info, &h, &sat, &dir, &sst,
&root_storage)) == -1) {
expn = "Cannot read short stream";
goto out3;
}
#ifdef CDF_DEBUG
cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir);
#endif
#ifdef notdef
if (root_storage) {
if (NOTMIME(ms)) {
char clsbuf[128];
if (file_printf(ms, "CLSID %s, ",
format_clsid(clsbuf, sizeof(clsbuf),
root_storage->d_storage_uuid)) == -1)
return -1;
}
}
#endif
if ((i = cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir,
&scn)) == -1) {
if (errno == ESRCH) {
corrupt = expn;
expn = "No summary info";
} else {
expn = "Cannot read summary info";
}
goto out4;
}
#ifdef CDF_DEBUG
cdf_dump_summary_info(&h, &scn);
#endif
if ((i = cdf_file_summary_info(ms, &h, &scn, root_storage)) < 0)
expn = "Can't expand summary_info";
if (i == 0) {
const char *str = NULL;
cdf_directory_t *d;
char name[__arraycount(d->d_name)];
size_t j, k;
for (j = 0; str == NULL && j < dir.dir_len; j++) {
d = &dir.dir_tab[j];
for (k = 0; k < sizeof(name); k++)
name[k] = (char)cdf_tole2(d->d_name[k]);
str = cdf_app_to_mime(name,
NOTMIME(ms) ? name2desc : name2mime);
}
if (NOTMIME(ms)) {
if (str != NULL) {
if (file_printf(ms, "%s", str) == -1)
return -1;
i = 1;
}
} else {
if (str == NULL)
str = "vnd.ms-office";
if (file_printf(ms, "application/%s", str) == -1)
return -1;
i = 1;
}
}
free(scn.sst_tab);
out4:
free(sst.sst_tab);
out3:
free(dir.dir_tab);
out2:
free(ssat.sat_tab);
out1:
free(sat.sat_tab);
out0:
if (i == -1) {
if (NOTMIME(ms)) {
if (file_printf(ms,
"Composite Document File V2 Document") == -1)
return -1;
if (*expn)
if (file_printf(ms, ", %s%s", corrupt, expn) == -1)
return -1;
} else {
if (file_printf(ms, "application/CDFV2-corrupt") == -1)
return -1;
}
i = 1;
}
return i;
}
| 166,447 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int x86_pmu_handle_irq(struct pt_regs *regs)
{
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
struct perf_event *event;
int idx, handled = 0;
u64 val;
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
/*
* Some chipsets need to unmask the LVTPC in a particular spot
* inside the nmi handler. As a result, the unmasking was pushed
* into all the nmi handlers.
*
* This generic handler doesn't seem to have any issues where the
* unmasking occurs so it was left at the top.
*/
apic_write(APIC_LVTPC, APIC_DM_NMI);
for (idx = 0; idx < x86_pmu.num_counters; idx++) {
if (!test_bit(idx, cpuc->active_mask)) {
/*
* Though we deactivated the counter some cpus
* might still deliver spurious interrupts still
* in flight. Catch them:
*/
if (__test_and_clear_bit(idx, cpuc->running))
handled++;
continue;
}
event = cpuc->events[idx];
val = x86_perf_event_update(event);
if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
continue;
/*
* event overflow
*/
handled++;
data.period = event->hw.last_period;
if (!x86_perf_event_set_period(event))
continue;
if (perf_event_overflow(event, 1, &data, regs))
x86_pmu_stop(event, 0);
}
if (handled)
inc_irq_stat(apic_perf_irqs);
return handled;
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | static int x86_pmu_handle_irq(struct pt_regs *regs)
{
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
struct perf_event *event;
int idx, handled = 0;
u64 val;
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
/*
* Some chipsets need to unmask the LVTPC in a particular spot
* inside the nmi handler. As a result, the unmasking was pushed
* into all the nmi handlers.
*
* This generic handler doesn't seem to have any issues where the
* unmasking occurs so it was left at the top.
*/
apic_write(APIC_LVTPC, APIC_DM_NMI);
for (idx = 0; idx < x86_pmu.num_counters; idx++) {
if (!test_bit(idx, cpuc->active_mask)) {
/*
* Though we deactivated the counter some cpus
* might still deliver spurious interrupts still
* in flight. Catch them:
*/
if (__test_and_clear_bit(idx, cpuc->running))
handled++;
continue;
}
event = cpuc->events[idx];
val = x86_perf_event_update(event);
if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
continue;
/*
* event overflow
*/
handled++;
data.period = event->hw.last_period;
if (!x86_perf_event_set_period(event))
continue;
if (perf_event_overflow(event, &data, regs))
x86_pmu_stop(event, 0);
}
if (handled)
inc_irq_stat(apic_perf_irqs);
return handled;
}
| 165,818 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t clear_refs_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct task_struct *task;
char buffer[PROC_NUMBUF];
struct mm_struct *mm;
struct vm_area_struct *vma;
enum clear_refs_types type;
struct mmu_gather tlb;
int itype;
int rv;
memset(buffer, 0, sizeof(buffer));
if (count > sizeof(buffer) - 1)
count = sizeof(buffer) - 1;
if (copy_from_user(buffer, buf, count))
return -EFAULT;
rv = kstrtoint(strstrip(buffer), 10, &itype);
if (rv < 0)
return rv;
type = (enum clear_refs_types)itype;
if (type < CLEAR_REFS_ALL || type >= CLEAR_REFS_LAST)
return -EINVAL;
task = get_proc_task(file_inode(file));
if (!task)
return -ESRCH;
mm = get_task_mm(task);
if (mm) {
struct mmu_notifier_range range;
struct clear_refs_private cp = {
.type = type,
};
struct mm_walk clear_refs_walk = {
.pmd_entry = clear_refs_pte_range,
.test_walk = clear_refs_test_walk,
.mm = mm,
.private = &cp,
};
if (type == CLEAR_REFS_MM_HIWATER_RSS) {
if (down_write_killable(&mm->mmap_sem)) {
count = -EINTR;
goto out_mm;
}
/*
* Writing 5 to /proc/pid/clear_refs resets the peak
* resident set size to this mm's current rss value.
*/
reset_mm_hiwater_rss(mm);
up_write(&mm->mmap_sem);
goto out_mm;
}
down_read(&mm->mmap_sem);
tlb_gather_mmu(&tlb, mm, 0, -1);
if (type == CLEAR_REFS_SOFT_DIRTY) {
for (vma = mm->mmap; vma; vma = vma->vm_next) {
if (!(vma->vm_flags & VM_SOFTDIRTY))
continue;
up_read(&mm->mmap_sem);
if (down_write_killable(&mm->mmap_sem)) {
count = -EINTR;
goto out_mm;
}
for (vma = mm->mmap; vma; vma = vma->vm_next) {
vma->vm_flags &= ~VM_SOFTDIRTY;
vma_set_page_prot(vma);
}
downgrade_write(&mm->mmap_sem);
break;
}
mmu_notifier_range_init(&range, mm, 0, -1UL);
mmu_notifier_invalidate_range_start(&range);
}
walk_page_range(0, mm->highest_vm_end, &clear_refs_walk);
if (type == CLEAR_REFS_SOFT_DIRTY)
mmu_notifier_invalidate_range_end(&range);
tlb_finish_mmu(&tlb, 0, -1);
up_read(&mm->mmap_sem);
out_mm:
mmput(mm);
}
put_task_struct(task);
return count;
}
Commit Message: coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping
The core dumping code has always run without holding the mmap_sem for
writing, despite that is the only way to ensure that the entire vma
layout will not change from under it. Only using some signal
serialization on the processes belonging to the mm is not nearly enough.
This was pointed out earlier. For example in Hugh's post from Jul 2017:
https://lkml.kernel.org/r/[email protected]
"Not strictly relevant here, but a related note: I was very surprised
to discover, only quite recently, how handle_mm_fault() may be called
without down_read(mmap_sem) - when core dumping. That seems a
misguided optimization to me, which would also be nice to correct"
In particular because the growsdown and growsup can move the
vm_start/vm_end the various loops the core dump does around the vma will
not be consistent if page faults can happen concurrently.
Pretty much all users calling mmget_not_zero()/get_task_mm() and then
taking the mmap_sem had the potential to introduce unexpected side
effects in the core dumping code.
Adding mmap_sem for writing around the ->core_dump invocation is a
viable long term fix, but it requires removing all copy user and page
faults and to replace them with get_dump_page() for all binary formats
which is not suitable as a short term fix.
For the time being this solution manually covers the places that can
confuse the core dump either by altering the vma layout or the vma flags
while it runs. Once ->core_dump runs under mmap_sem for writing the
function mmget_still_valid() can be dropped.
Allowing mmap_sem protected sections to run in parallel with the
coredump provides some minor parallelism advantage to the swapoff code
(which seems to be safe enough by never mangling any vma field and can
keep doing swapins in parallel to the core dumping) and to some other
corner case.
In order to facilitate the backporting I added "Fixes: 86039bd3b4e6"
however the side effect of this same race condition in /proc/pid/mem
should be reproducible since before 2.6.12-rc2 so I couldn't add any
other "Fixes:" because there's no hash beyond the git genesis commit.
Because find_extend_vma() is the only location outside of the process
context that could modify the "mm" structures under mmap_sem for
reading, by adding the mmget_still_valid() check to it, all other cases
that take the mmap_sem for reading don't need the new check after
mmget_not_zero()/get_task_mm(). The expand_stack() in page fault
context also doesn't need the new check, because all tasks under core
dumping are frozen.
Link: http://lkml.kernel.org/r/[email protected]
Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization")
Signed-off-by: Andrea Arcangeli <[email protected]>
Reported-by: Jann Horn <[email protected]>
Suggested-by: Oleg Nesterov <[email protected]>
Acked-by: Peter Xu <[email protected]>
Reviewed-by: Mike Rapoport <[email protected]>
Reviewed-by: Oleg Nesterov <[email protected]>
Reviewed-by: Jann Horn <[email protected]>
Acked-by: Jason Gunthorpe <[email protected]>
Acked-by: Michal Hocko <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362 | static ssize_t clear_refs_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct task_struct *task;
char buffer[PROC_NUMBUF];
struct mm_struct *mm;
struct vm_area_struct *vma;
enum clear_refs_types type;
struct mmu_gather tlb;
int itype;
int rv;
memset(buffer, 0, sizeof(buffer));
if (count > sizeof(buffer) - 1)
count = sizeof(buffer) - 1;
if (copy_from_user(buffer, buf, count))
return -EFAULT;
rv = kstrtoint(strstrip(buffer), 10, &itype);
if (rv < 0)
return rv;
type = (enum clear_refs_types)itype;
if (type < CLEAR_REFS_ALL || type >= CLEAR_REFS_LAST)
return -EINVAL;
task = get_proc_task(file_inode(file));
if (!task)
return -ESRCH;
mm = get_task_mm(task);
if (mm) {
struct mmu_notifier_range range;
struct clear_refs_private cp = {
.type = type,
};
struct mm_walk clear_refs_walk = {
.pmd_entry = clear_refs_pte_range,
.test_walk = clear_refs_test_walk,
.mm = mm,
.private = &cp,
};
if (type == CLEAR_REFS_MM_HIWATER_RSS) {
if (down_write_killable(&mm->mmap_sem)) {
count = -EINTR;
goto out_mm;
}
/*
* Writing 5 to /proc/pid/clear_refs resets the peak
* resident set size to this mm's current rss value.
*/
reset_mm_hiwater_rss(mm);
up_write(&mm->mmap_sem);
goto out_mm;
}
down_read(&mm->mmap_sem);
tlb_gather_mmu(&tlb, mm, 0, -1);
if (type == CLEAR_REFS_SOFT_DIRTY) {
for (vma = mm->mmap; vma; vma = vma->vm_next) {
if (!(vma->vm_flags & VM_SOFTDIRTY))
continue;
up_read(&mm->mmap_sem);
if (down_write_killable(&mm->mmap_sem)) {
count = -EINTR;
goto out_mm;
}
/*
* Avoid to modify vma->vm_flags
* without locked ops while the
* coredump reads the vm_flags.
*/
if (!mmget_still_valid(mm)) {
/*
* Silently return "count"
* like if get_task_mm()
* failed. FIXME: should this
* function have returned
* -ESRCH if get_task_mm()
* failed like if
* get_proc_task() fails?
*/
up_write(&mm->mmap_sem);
goto out_mm;
}
for (vma = mm->mmap; vma; vma = vma->vm_next) {
vma->vm_flags &= ~VM_SOFTDIRTY;
vma_set_page_prot(vma);
}
downgrade_write(&mm->mmap_sem);
break;
}
mmu_notifier_range_init(&range, mm, 0, -1UL);
mmu_notifier_invalidate_range_start(&range);
}
walk_page_range(0, mm->highest_vm_end, &clear_refs_walk);
if (type == CLEAR_REFS_SOFT_DIRTY)
mmu_notifier_invalidate_range_end(&range);
tlb_finish_mmu(&tlb, 0, -1);
up_read(&mm->mmap_sem);
out_mm:
mmput(mm);
}
put_task_struct(task);
return count;
}
| 169,685 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SoftMPEG2::setDecodeArgs(
ivd_video_decode_ip_t *ps_dec_ip,
ivd_video_decode_op_t *ps_dec_op,
OMX_BUFFERHEADERTYPE *inHeader,
OMX_BUFFERHEADERTYPE *outHeader,
size_t timeStampIx) {
size_t sizeY = outputBufferWidth() * outputBufferHeight();
size_t sizeUV;
uint8_t *pBuf;
ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
/* When in flush and after EOS with zero byte input,
* inHeader is set to zero. Hence check for non-null */
if (inHeader) {
ps_dec_ip->u4_ts = timeStampIx;
ps_dec_ip->pv_stream_buffer = inHeader->pBuffer
+ inHeader->nOffset;
ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen;
} else {
ps_dec_ip->u4_ts = 0;
ps_dec_ip->pv_stream_buffer = NULL;
ps_dec_ip->u4_num_Bytes = 0;
}
if (outHeader) {
pBuf = outHeader->pBuffer;
} else {
pBuf = mFlushOutBuffer;
}
sizeUV = sizeY / 4;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf;
ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY;
ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV;
ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
return;
}
Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec
Bug: 27833616
Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738
(cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d)
CWE ID: CWE-20 | void SoftMPEG2::setDecodeArgs(
bool SoftMPEG2::setDecodeArgs(
ivd_video_decode_ip_t *ps_dec_ip,
ivd_video_decode_op_t *ps_dec_op,
OMX_BUFFERHEADERTYPE *inHeader,
OMX_BUFFERHEADERTYPE *outHeader,
size_t timeStampIx) {
size_t sizeY = outputBufferWidth() * outputBufferHeight();
size_t sizeUV;
ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
/* When in flush and after EOS with zero byte input,
* inHeader is set to zero. Hence check for non-null */
if (inHeader) {
ps_dec_ip->u4_ts = timeStampIx;
ps_dec_ip->pv_stream_buffer = inHeader->pBuffer
+ inHeader->nOffset;
ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen;
} else {
ps_dec_ip->u4_ts = 0;
ps_dec_ip->pv_stream_buffer = NULL;
ps_dec_ip->u4_num_Bytes = 0;
}
sizeUV = sizeY / 4;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
uint8_t *pBuf;
if (outHeader) {
if (outHeader->nAllocLen < sizeY + (sizeUV * 2)) {
android_errorWriteLog(0x534e4554, "27569635");
return false;
}
pBuf = outHeader->pBuffer;
} else {
// mFlushOutBuffer always has the right size.
pBuf = mFlushOutBuffer;
}
ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf;
ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY;
ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV;
ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
return true;
}
| 174,184 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters)
{
FILE *f;
opj_image_t *image;
unsigned int image_width, image_height, pixel_bit_depth;
unsigned int x, y;
int flip_image = 0;
opj_image_cmptparm_t cmptparm[4]; /* maximum 4 components */
int numcomps;
OPJ_COLOR_SPACE color_space;
OPJ_BOOL mono ;
OPJ_BOOL save_alpha;
int subsampling_dx, subsampling_dy;
int i;
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Failed to open %s for reading !!\n", filename);
return 0;
}
if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height,
&flip_image)) {
fclose(f);
return NULL;
}
/* We currently only support 24 & 32 bit tga's ... */
if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32))) {
fclose(f);
return NULL;
}
/* initialize image components */
memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
mono = (pixel_bit_depth == 8) ||
(pixel_bit_depth == 16); /* Mono with & without alpha. */
save_alpha = (pixel_bit_depth == 16) ||
(pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
if (mono) {
color_space = OPJ_CLRSPC_GRAY;
numcomps = save_alpha ? 2 : 1;
} else {
numcomps = save_alpha ? 4 : 3;
color_space = OPJ_CLRSPC_SRGB;
}
subsampling_dx = parameters->subsampling_dx;
subsampling_dy = parameters->subsampling_dy;
for (i = 0; i < numcomps; i++) {
cmptparm[i].prec = 8;
cmptparm[i].bpp = 8;
cmptparm[i].sgnd = 0;
cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
cmptparm[i].w = image_width;
cmptparm[i].h = image_height;
}
/* create the image */
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
if (!image) {
fclose(f);
return NULL;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = !image->x0 ? (OPJ_UINT32)(image_width - 1) *
(OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(image_width - 1) *
(OPJ_UINT32)subsampling_dx + 1;
image->y1 = !image->y0 ? (OPJ_UINT32)(image_height - 1) *
(OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(image_height - 1) *
(OPJ_UINT32)subsampling_dy + 1;
/* set image data */
for (y = 0; y < image_height; y++) {
int index;
if (flip_image) {
index = (int)((image_height - y - 1) * image_width);
} else {
index = (int)(y * image_width);
}
if (numcomps == 3) {
for (x = 0; x < image_width; x++) {
unsigned char r, g, b;
if (!fread(&b, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&g, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&r, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[0].data[index] = r;
image->comps[1].data[index] = g;
image->comps[2].data[index] = b;
index++;
}
} else if (numcomps == 4) {
for (x = 0; x < image_width; x++) {
unsigned char r, g, b, a;
if (!fread(&b, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&g, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&r, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&a, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[0].data[index] = r;
image->comps[1].data[index] = g;
image->comps[2].data[index] = b;
image->comps[3].data[index] = a;
index++;
}
} else {
fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
}
}
fclose(f);
return image;
}
Commit Message: tgatoimage(): avoid excessive memory allocation attempt, and fixes unaligned load (#995)
CWE ID: CWE-787 | opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters)
{
FILE *f;
opj_image_t *image;
unsigned int image_width, image_height, pixel_bit_depth;
unsigned int x, y;
int flip_image = 0;
opj_image_cmptparm_t cmptparm[4]; /* maximum 4 components */
int numcomps;
OPJ_COLOR_SPACE color_space;
OPJ_BOOL mono ;
OPJ_BOOL save_alpha;
int subsampling_dx, subsampling_dy;
int i;
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Failed to open %s for reading !!\n", filename);
return 0;
}
if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height,
&flip_image)) {
fclose(f);
return NULL;
}
/* We currently only support 24 & 32 bit tga's ... */
if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32))) {
fclose(f);
return NULL;
}
/* initialize image components */
memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
mono = (pixel_bit_depth == 8) ||
(pixel_bit_depth == 16); /* Mono with & without alpha. */
save_alpha = (pixel_bit_depth == 16) ||
(pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
if (mono) {
color_space = OPJ_CLRSPC_GRAY;
numcomps = save_alpha ? 2 : 1;
} else {
numcomps = save_alpha ? 4 : 3;
color_space = OPJ_CLRSPC_SRGB;
}
/* If the declared file size is > 10 MB, check that the file is big */
/* enough to avoid excessive memory allocations */
if (image_height != 0 && image_width > 10000000 / image_height / numcomps) {
char ch;
OPJ_UINT64 expected_file_size =
(OPJ_UINT64)image_width * image_height * numcomps;
long curpos = ftell(f);
if (expected_file_size > (OPJ_UINT64)INT_MAX) {
expected_file_size = (OPJ_UINT64)INT_MAX;
}
fseek(f, (long)expected_file_size - 1, SEEK_SET);
if (fread(&ch, 1, 1, f) != 1) {
fclose(f);
return NULL;
}
fseek(f, curpos, SEEK_SET);
}
subsampling_dx = parameters->subsampling_dx;
subsampling_dy = parameters->subsampling_dy;
for (i = 0; i < numcomps; i++) {
cmptparm[i].prec = 8;
cmptparm[i].bpp = 8;
cmptparm[i].sgnd = 0;
cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
cmptparm[i].w = image_width;
cmptparm[i].h = image_height;
}
/* create the image */
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
if (!image) {
fclose(f);
return NULL;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = !image->x0 ? (OPJ_UINT32)(image_width - 1) *
(OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(image_width - 1) *
(OPJ_UINT32)subsampling_dx + 1;
image->y1 = !image->y0 ? (OPJ_UINT32)(image_height - 1) *
(OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(image_height - 1) *
(OPJ_UINT32)subsampling_dy + 1;
/* set image data */
for (y = 0; y < image_height; y++) {
int index;
if (flip_image) {
index = (int)((image_height - y - 1) * image_width);
} else {
index = (int)(y * image_width);
}
if (numcomps == 3) {
for (x = 0; x < image_width; x++) {
unsigned char r, g, b;
if (!fread(&b, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&g, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&r, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[0].data[index] = r;
image->comps[1].data[index] = g;
image->comps[2].data[index] = b;
index++;
}
} else if (numcomps == 4) {
for (x = 0; x < image_width; x++) {
unsigned char r, g, b, a;
if (!fread(&b, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&g, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&r, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&a, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[0].data[index] = r;
image->comps[1].data[index] = g;
image->comps[2].data[index] = b;
image->comps[3].data[index] = a;
index++;
}
} else {
fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
}
}
fclose(f);
return image;
}
| 167,782 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: mcid_char_imp(fz_context *ctx, pdf_filter_processor *p, tag_record *tr, int uni, int remove)
{
if (tr->mcid_obj == NULL)
/* No object, or already deleted */
return;
if (remove)
{
/* Remove the expanded abbreviation, if there is one. */
pdf_dict_del(ctx, tr->mcid_obj, PDF_NAME(E));
/* Remove the structure title, if there is one. */
pdf_dict_del(ctx, tr->mcid_obj, PDF_NAME(T));
}
/* Edit the Alt string */
walk_string(ctx, uni, remove, &tr->alt);
/* Edit the ActualText string */
walk_string(ctx, uni, remove, &tr->actualtext);
/* If we're removing a character, and either of the strings
* haven't matched up to what we were expecting, then just
* delete the whole string. */
else if (tr->alt.pos >= 0 || tr->actualtext.pos >= 0)
{
/* The strings are making sense so far */
remove = 0;
/* The strings are making sense so far */
remove = 0;
}
if (remove)
{
/* Anything else we have to err on the side of caution and
if (tr->alt.pos == -1)
pdf_dict_del(ctx, tr->mcid_obj, PDF_NAME(Alt));
pdf_drop_obj(ctx, tr->mcid_obj);
tr->mcid_obj = NULL;
fz_free(ctx, tr->alt.utf8);
tr->alt.utf8 = NULL;
fz_free(ctx, tr->actualtext.utf8);
tr->actualtext.utf8 = NULL;
}
}
Commit Message:
CWE ID: CWE-125 | mcid_char_imp(fz_context *ctx, pdf_filter_processor *p, tag_record *tr, int uni, int remove)
{
if (tr->mcid_obj == NULL)
/* No object, or already deleted */
return;
if (remove)
{
/* Remove the expanded abbreviation, if there is one. */
pdf_dict_del(ctx, tr->mcid_obj, PDF_NAME(E));
/* Remove the structure title, if there is one. */
pdf_dict_del(ctx, tr->mcid_obj, PDF_NAME(T));
}
/* Edit the Alt string */
walk_string(ctx, uni, remove, &tr->alt);
/* Edit the ActualText string */
walk_string(ctx, uni, remove, &tr->actualtext);
/* If we're removing a character, and either of the strings
* haven't matched up to what we were expecting, then just
* delete the whole string. */
else if (tr->alt.pos >= 0 || tr->actualtext.pos >= 0)
{
/* The strings are making sense so far */
remove = 0;
/* The strings are making sense so far */
remove = 0;
}
if (remove)
{
/* Anything else we have to err on the side of caution and
if (tr->alt.pos == -1)
pdf_dict_del(ctx, tr->mcid_obj, PDF_NAME(Alt));
pdf_drop_obj(ctx, tr->mcid_obj);
tr->mcid_obj = NULL;
fz_free(ctx, tr->alt.utf8);
tr->alt.utf8 = NULL;
fz_free(ctx, tr->actualtext.utf8);
tr->actualtext.utf8 = NULL;
}
}
| 164,659 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int get_next_block(bunzip_data *bd)
{
struct group_data *hufGroup;
int dbufCount, dbufSize, groupCount, *base, *limit, selector,
i, j, runPos, symCount, symTotal, nSelectors, byteCount[256];
int runCnt = runCnt; /* for compiler */
uint8_t uc, symToByte[256], mtfSymbol[256], *selectors;
uint32_t *dbuf;
unsigned origPtr, t;
dbuf = bd->dbuf;
dbufSize = bd->dbufSize;
selectors = bd->selectors;
/* In bbox, we are ok with aborting through setjmp which is set up in start_bunzip */
#if 0
/* Reset longjmp I/O error handling */
i = setjmp(bd->jmpbuf);
if (i) return i;
#endif
/* Read in header signature and CRC, then validate signature.
(last block signature means CRC is for whole file, return now) */
i = get_bits(bd, 24);
j = get_bits(bd, 24);
bd->headerCRC = get_bits(bd, 32);
if ((i == 0x177245) && (j == 0x385090)) return RETVAL_LAST_BLOCK;
if ((i != 0x314159) || (j != 0x265359)) return RETVAL_NOT_BZIP_DATA;
/* We can add support for blockRandomised if anybody complains. There was
some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
it didn't actually work. */
if (get_bits(bd, 1)) return RETVAL_OBSOLETE_INPUT;
origPtr = get_bits(bd, 24);
if ((int)origPtr > dbufSize) return RETVAL_DATA_ERROR;
/* mapping table: if some byte values are never used (encoding things
like ascii text), the compression code removes the gaps to have fewer
symbols to deal with, and writes a sparse bitfield indicating which
values were present. We make a translation table to convert the symbols
back to the corresponding bytes. */
symTotal = 0;
i = 0;
t = get_bits(bd, 16);
do {
if (t & (1 << 15)) {
unsigned inner_map = get_bits(bd, 16);
do {
if (inner_map & (1 << 15))
symToByte[symTotal++] = i;
inner_map <<= 1;
i++;
} while (i & 15);
i -= 16;
}
t <<= 1;
i += 16;
} while (i < 256);
/* How many different Huffman coding groups does this block use? */
groupCount = get_bits(bd, 3);
if (groupCount < 2 || groupCount > MAX_GROUPS)
return RETVAL_DATA_ERROR;
/* nSelectors: Every GROUP_SIZE many symbols we select a new Huffman coding
group. Read in the group selector list, which is stored as MTF encoded
bit runs. (MTF=Move To Front, as each value is used it's moved to the
start of the list.) */
for (i = 0; i < groupCount; i++)
mtfSymbol[i] = i;
nSelectors = get_bits(bd, 15);
if (!nSelectors)
return RETVAL_DATA_ERROR;
for (i = 0; i < nSelectors; i++) {
uint8_t tmp_byte;
/* Get next value */
int n = 0;
while (get_bits(bd, 1)) {
if (n >= groupCount) return RETVAL_DATA_ERROR;
n++;
}
/* Decode MTF to get the next selector */
tmp_byte = mtfSymbol[n];
while (--n >= 0)
mtfSymbol[n + 1] = mtfSymbol[n];
mtfSymbol[0] = selectors[i] = tmp_byte;
}
/* Read the Huffman coding tables for each group, which code for symTotal
literal symbols, plus two run symbols (RUNA, RUNB) */
symCount = symTotal + 2;
for (j = 0; j < groupCount; j++) {
uint8_t length[MAX_SYMBOLS];
/* 8 bits is ALMOST enough for temp[], see below */
unsigned temp[MAX_HUFCODE_BITS+1];
int minLen, maxLen, pp, len_m1;
/* Read Huffman code lengths for each symbol. They're stored in
a way similar to mtf; record a starting value for the first symbol,
and an offset from the previous value for every symbol after that.
(Subtracting 1 before the loop and then adding it back at the end is
an optimization that makes the test inside the loop simpler: symbol
length 0 becomes negative, so an unsigned inequality catches it.) */
len_m1 = get_bits(bd, 5) - 1;
for (i = 0; i < symCount; i++) {
for (;;) {
int two_bits;
if ((unsigned)len_m1 > (MAX_HUFCODE_BITS-1))
return RETVAL_DATA_ERROR;
/* If first bit is 0, stop. Else second bit indicates whether
to increment or decrement the value. Optimization: grab 2
bits and unget the second if the first was 0. */
two_bits = get_bits(bd, 2);
if (two_bits < 2) {
bd->inbufBitCount++;
break;
}
/* Add one if second bit 1, else subtract 1. Avoids if/else */
len_m1 += (((two_bits+1) & 2) - 1);
}
/* Correct for the initial -1, to get the final symbol length */
length[i] = len_m1 + 1;
}
/* Find largest and smallest lengths in this group */
minLen = maxLen = length[0];
for (i = 1; i < symCount; i++) {
if (length[i] > maxLen) maxLen = length[i];
else if (length[i] < minLen) minLen = length[i];
}
/* Calculate permute[], base[], and limit[] tables from length[].
*
* permute[] is the lookup table for converting Huffman coded symbols
* into decoded symbols. base[] is the amount to subtract from the
* value of a Huffman symbol of a given length when using permute[].
*
* limit[] indicates the largest numerical value a symbol with a given
* number of bits can have. This is how the Huffman codes can vary in
* length: each code with a value>limit[length] needs another bit.
*/
hufGroup = bd->groups + j;
hufGroup->minLen = minLen;
hufGroup->maxLen = maxLen;
/* Note that minLen can't be smaller than 1, so we adjust the base
and limit array pointers so we're not always wasting the first
entry. We do this again when using them (during symbol decoding). */
base = hufGroup->base - 1;
limit = hufGroup->limit - 1;
/* Calculate permute[]. Concurrently, initialize temp[] and limit[]. */
pp = 0;
for (i = minLen; i <= maxLen; i++) {
int k;
temp[i] = limit[i] = 0;
for (k = 0; k < symCount; k++)
if (length[k] == i)
hufGroup->permute[pp++] = k;
}
/* Count symbols coded for at each bit length */
/* NB: in pathological cases, temp[8] can end ip being 256.
* That's why uint8_t is too small for temp[]. */
for (i = 0; i < symCount; i++) temp[length[i]]++;
/* Calculate limit[] (the largest symbol-coding value at each bit
* length, which is (previous limit<<1)+symbols at this level), and
* base[] (number of symbols to ignore at each bit length, which is
* limit minus the cumulative count of symbols coded for already). */
pp = t = 0;
for (i = minLen; i < maxLen;) {
unsigned temp_i = temp[i];
pp += temp_i;
/* We read the largest possible symbol size and then unget bits
after determining how many we need, and those extra bits could
be set to anything. (They're noise from future symbols.) At
each level we're really only interested in the first few bits,
so here we set all the trailing to-be-ignored bits to 1 so they
don't affect the value>limit[length] comparison. */
limit[i] = (pp << (maxLen - i)) - 1;
pp <<= 1;
t += temp_i;
base[++i] = pp - t;
}
limit[maxLen] = pp + temp[maxLen] - 1;
limit[maxLen+1] = INT_MAX; /* Sentinel value for reading next sym. */
base[minLen] = 0;
}
/* We've finished reading and digesting the block header. Now read this
block's Huffman coded symbols from the file and undo the Huffman coding
and run length encoding, saving the result into dbuf[dbufCount++] = uc */
/* Initialize symbol occurrence counters and symbol Move To Front table */
/*memset(byteCount, 0, sizeof(byteCount)); - smaller, but slower */
for (i = 0; i < 256; i++) {
byteCount[i] = 0;
mtfSymbol[i] = (uint8_t)i;
}
/* Loop through compressed symbols. */
runPos = dbufCount = selector = 0;
for (;;) {
int nextSym;
/* Fetch next Huffman coding group from list. */
symCount = GROUP_SIZE - 1;
if (selector >= nSelectors) return RETVAL_DATA_ERROR;
hufGroup = bd->groups + selectors[selector++];
base = hufGroup->base - 1;
limit = hufGroup->limit - 1;
continue_this_group:
/* Read next Huffman-coded symbol. */
/* Note: It is far cheaper to read maxLen bits and back up than it is
to read minLen bits and then add additional bit at a time, testing
as we go. Because there is a trailing last block (with file CRC),
there is no danger of the overread causing an unexpected EOF for a
valid compressed file.
*/
if (1) {
/* As a further optimization, we do the read inline
(falling back to a call to get_bits if the buffer runs dry).
*/
int new_cnt;
while ((new_cnt = bd->inbufBitCount - hufGroup->maxLen) < 0) {
/* bd->inbufBitCount < hufGroup->maxLen */
if (bd->inbufPos == bd->inbufCount) {
nextSym = get_bits(bd, hufGroup->maxLen);
goto got_huff_bits;
}
bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++];
bd->inbufBitCount += 8;
};
bd->inbufBitCount = new_cnt; /* "bd->inbufBitCount -= hufGroup->maxLen;" */
nextSym = (bd->inbufBits >> new_cnt) & ((1 << hufGroup->maxLen) - 1);
got_huff_bits: ;
} else { /* unoptimized equivalent */
nextSym = get_bits(bd, hufGroup->maxLen);
}
/* Figure how many bits are in next symbol and unget extras */
i = hufGroup->minLen;
while (nextSym > limit[i]) ++i;
j = hufGroup->maxLen - i;
if (j < 0)
return RETVAL_DATA_ERROR;
bd->inbufBitCount += j;
/* Huffman decode value to get nextSym (with bounds checking) */
nextSym = (nextSym >> j) - base[i];
if ((unsigned)nextSym >= MAX_SYMBOLS)
return RETVAL_DATA_ERROR;
nextSym = hufGroup->permute[nextSym];
/* We have now decoded the symbol, which indicates either a new literal
byte, or a repeated run of the most recent literal byte. First,
check if nextSym indicates a repeated run, and if so loop collecting
how many times to repeat the last literal. */
if ((unsigned)nextSym <= SYMBOL_RUNB) { /* RUNA or RUNB */
/* If this is the start of a new run, zero out counter */
if (runPos == 0) {
runPos = 1;
runCnt = 0;
}
/* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
each bit position, add 1 or 2 instead. For example,
1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
You can make any bit pattern that way using 1 less symbol than
the basic or 0/1 method (except all bits 0, which would use no
symbols, but a run of length 0 doesn't mean anything in this
context). Thus space is saved. */
runCnt += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */
if (runPos < dbufSize) runPos <<= 1;
////The 32-bit overflow of runCnt wasn't yet seen, but probably can happen.
////This would be the fix (catches too large count way before it can overflow):
//// if (runCnt > bd->dbufSize) {
//// dbg("runCnt:%u > dbufSize:%u RETVAL_DATA_ERROR",
//// runCnt, bd->dbufSize);
//// return RETVAL_DATA_ERROR;
//// }
goto end_of_huffman_loop;
}
dbg("dbufCount:%d+runCnt:%d %d > dbufSize:%d RETVAL_DATA_ERROR",
dbufCount, runCnt, dbufCount + runCnt, dbufSize);
return RETVAL_DATA_ERROR;
literal used is the one at the head of the mtfSymbol array.) */
if (runPos != 0) {
uint8_t tmp_byte;
if (dbufCount + runCnt > dbufSize) {
dbg("dbufCount:%d+runCnt:%d %d > dbufSize:%d RETVAL_DATA_ERROR",
dbufCount, runCnt, dbufCount + runCnt, dbufSize);
return RETVAL_DATA_ERROR;
}
tmp_byte = symToByte[mtfSymbol[0]];
byteCount[tmp_byte] += runCnt;
while (--runCnt >= 0) dbuf[dbufCount++] = (uint32_t)tmp_byte;
runPos = 0;
}
as part of a run above. Therefore 1 unused mtf position minus
2 non-literal nextSym values equals -1.) */
if (dbufCount >= dbufSize) return RETVAL_DATA_ERROR;
i = nextSym - 1;
uc = mtfSymbol[i];
/* Adjust the MTF array. Since we typically expect to move only a
first symbol in the mtf array, position 0, would have been handled
as part of a run above. Therefore 1 unused mtf position minus
2 non-literal nextSym values equals -1.) */
if (dbufCount >= dbufSize) return RETVAL_DATA_ERROR;
i = nextSym - 1;
uc = mtfSymbol[i];
uc = symToByte[uc];
/* We have our literal byte. Save it into dbuf. */
byteCount[uc]++;
dbuf[dbufCount++] = (uint32_t)uc;
/* Skip group initialization if we're not done with this group. Done
* this way to avoid compiler warning. */
end_of_huffman_loop:
if (--symCount >= 0) goto continue_this_group;
}
/* At this point, we've read all the Huffman-coded symbols (and repeated
runs) for this block from the input stream, and decoded them into the
intermediate buffer. There are dbufCount many decoded bytes in dbuf[].
Now undo the Burrows-Wheeler transform on dbuf.
See http://dogma.net/markn/articles/bwt/bwt.htm
*/
/* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
j = 0;
for (i = 0; i < 256; i++) {
int tmp_count = j + byteCount[i];
byteCount[i] = j;
j = tmp_count;
}
/* Figure out what order dbuf would be in if we sorted it. */
for (i = 0; i < dbufCount; i++) {
uint8_t tmp_byte = (uint8_t)dbuf[i];
int tmp_count = byteCount[tmp_byte];
dbuf[tmp_count] |= (i << 8);
byteCount[tmp_byte] = tmp_count + 1;
}
/* Decode first byte by hand to initialize "previous" byte. Note that it
doesn't get output, and if the first three characters are identical
it doesn't qualify as a run (hence writeRunCountdown=5). */
if (dbufCount) {
uint32_t tmp;
if ((int)origPtr >= dbufCount) return RETVAL_DATA_ERROR;
tmp = dbuf[origPtr];
bd->writeCurrent = (uint8_t)tmp;
bd->writePos = (tmp >> 8);
bd->writeRunCountdown = 5;
}
bd->writeCount = dbufCount;
return RETVAL_OK;
}
Commit Message:
CWE ID: CWE-190 | static int get_next_block(bunzip_data *bd)
{
struct group_data *hufGroup;
int groupCount, *base, *limit, selector,
i, j, symCount, symTotal, nSelectors, byteCount[256];
uint8_t uc, symToByte[256], mtfSymbol[256], *selectors;
uint32_t *dbuf;
unsigned origPtr, t;
unsigned dbufCount, runPos;
unsigned runCnt = runCnt; /* for compiler */
dbuf = bd->dbuf;
selectors = bd->selectors;
/* In bbox, we are ok with aborting through setjmp which is set up in start_bunzip */
#if 0
/* Reset longjmp I/O error handling */
i = setjmp(bd->jmpbuf);
if (i) return i;
#endif
/* Read in header signature and CRC, then validate signature.
(last block signature means CRC is for whole file, return now) */
i = get_bits(bd, 24);
j = get_bits(bd, 24);
bd->headerCRC = get_bits(bd, 32);
if ((i == 0x177245) && (j == 0x385090)) return RETVAL_LAST_BLOCK;
if ((i != 0x314159) || (j != 0x265359)) return RETVAL_NOT_BZIP_DATA;
/* We can add support for blockRandomised if anybody complains. There was
some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
it didn't actually work. */
if (get_bits(bd, 1)) return RETVAL_OBSOLETE_INPUT;
origPtr = get_bits(bd, 24);
if (origPtr > bd->dbufSize) return RETVAL_DATA_ERROR;
/* mapping table: if some byte values are never used (encoding things
like ascii text), the compression code removes the gaps to have fewer
symbols to deal with, and writes a sparse bitfield indicating which
values were present. We make a translation table to convert the symbols
back to the corresponding bytes. */
symTotal = 0;
i = 0;
t = get_bits(bd, 16);
do {
if (t & (1 << 15)) {
unsigned inner_map = get_bits(bd, 16);
do {
if (inner_map & (1 << 15))
symToByte[symTotal++] = i;
inner_map <<= 1;
i++;
} while (i & 15);
i -= 16;
}
t <<= 1;
i += 16;
} while (i < 256);
/* How many different Huffman coding groups does this block use? */
groupCount = get_bits(bd, 3);
if (groupCount < 2 || groupCount > MAX_GROUPS)
return RETVAL_DATA_ERROR;
/* nSelectors: Every GROUP_SIZE many symbols we select a new Huffman coding
group. Read in the group selector list, which is stored as MTF encoded
bit runs. (MTF=Move To Front, as each value is used it's moved to the
start of the list.) */
for (i = 0; i < groupCount; i++)
mtfSymbol[i] = i;
nSelectors = get_bits(bd, 15);
if (!nSelectors)
return RETVAL_DATA_ERROR;
for (i = 0; i < nSelectors; i++) {
uint8_t tmp_byte;
/* Get next value */
int n = 0;
while (get_bits(bd, 1)) {
if (n >= groupCount) return RETVAL_DATA_ERROR;
n++;
}
/* Decode MTF to get the next selector */
tmp_byte = mtfSymbol[n];
while (--n >= 0)
mtfSymbol[n + 1] = mtfSymbol[n];
mtfSymbol[0] = selectors[i] = tmp_byte;
}
/* Read the Huffman coding tables for each group, which code for symTotal
literal symbols, plus two run symbols (RUNA, RUNB) */
symCount = symTotal + 2;
for (j = 0; j < groupCount; j++) {
uint8_t length[MAX_SYMBOLS];
/* 8 bits is ALMOST enough for temp[], see below */
unsigned temp[MAX_HUFCODE_BITS+1];
int minLen, maxLen, pp, len_m1;
/* Read Huffman code lengths for each symbol. They're stored in
a way similar to mtf; record a starting value for the first symbol,
and an offset from the previous value for every symbol after that.
(Subtracting 1 before the loop and then adding it back at the end is
an optimization that makes the test inside the loop simpler: symbol
length 0 becomes negative, so an unsigned inequality catches it.) */
len_m1 = get_bits(bd, 5) - 1;
for (i = 0; i < symCount; i++) {
for (;;) {
int two_bits;
if ((unsigned)len_m1 > (MAX_HUFCODE_BITS-1))
return RETVAL_DATA_ERROR;
/* If first bit is 0, stop. Else second bit indicates whether
to increment or decrement the value. Optimization: grab 2
bits and unget the second if the first was 0. */
two_bits = get_bits(bd, 2);
if (two_bits < 2) {
bd->inbufBitCount++;
break;
}
/* Add one if second bit 1, else subtract 1. Avoids if/else */
len_m1 += (((two_bits+1) & 2) - 1);
}
/* Correct for the initial -1, to get the final symbol length */
length[i] = len_m1 + 1;
}
/* Find largest and smallest lengths in this group */
minLen = maxLen = length[0];
for (i = 1; i < symCount; i++) {
if (length[i] > maxLen) maxLen = length[i];
else if (length[i] < minLen) minLen = length[i];
}
/* Calculate permute[], base[], and limit[] tables from length[].
*
* permute[] is the lookup table for converting Huffman coded symbols
* into decoded symbols. base[] is the amount to subtract from the
* value of a Huffman symbol of a given length when using permute[].
*
* limit[] indicates the largest numerical value a symbol with a given
* number of bits can have. This is how the Huffman codes can vary in
* length: each code with a value>limit[length] needs another bit.
*/
hufGroup = bd->groups + j;
hufGroup->minLen = minLen;
hufGroup->maxLen = maxLen;
/* Note that minLen can't be smaller than 1, so we adjust the base
and limit array pointers so we're not always wasting the first
entry. We do this again when using them (during symbol decoding). */
base = hufGroup->base - 1;
limit = hufGroup->limit - 1;
/* Calculate permute[]. Concurrently, initialize temp[] and limit[]. */
pp = 0;
for (i = minLen; i <= maxLen; i++) {
int k;
temp[i] = limit[i] = 0;
for (k = 0; k < symCount; k++)
if (length[k] == i)
hufGroup->permute[pp++] = k;
}
/* Count symbols coded for at each bit length */
/* NB: in pathological cases, temp[8] can end ip being 256.
* That's why uint8_t is too small for temp[]. */
for (i = 0; i < symCount; i++) temp[length[i]]++;
/* Calculate limit[] (the largest symbol-coding value at each bit
* length, which is (previous limit<<1)+symbols at this level), and
* base[] (number of symbols to ignore at each bit length, which is
* limit minus the cumulative count of symbols coded for already). */
pp = t = 0;
for (i = minLen; i < maxLen;) {
unsigned temp_i = temp[i];
pp += temp_i;
/* We read the largest possible symbol size and then unget bits
after determining how many we need, and those extra bits could
be set to anything. (They're noise from future symbols.) At
each level we're really only interested in the first few bits,
so here we set all the trailing to-be-ignored bits to 1 so they
don't affect the value>limit[length] comparison. */
limit[i] = (pp << (maxLen - i)) - 1;
pp <<= 1;
t += temp_i;
base[++i] = pp - t;
}
limit[maxLen] = pp + temp[maxLen] - 1;
limit[maxLen+1] = INT_MAX; /* Sentinel value for reading next sym. */
base[minLen] = 0;
}
/* We've finished reading and digesting the block header. Now read this
block's Huffman coded symbols from the file and undo the Huffman coding
and run length encoding, saving the result into dbuf[dbufCount++] = uc */
/* Initialize symbol occurrence counters and symbol Move To Front table */
/*memset(byteCount, 0, sizeof(byteCount)); - smaller, but slower */
for (i = 0; i < 256; i++) {
byteCount[i] = 0;
mtfSymbol[i] = (uint8_t)i;
}
/* Loop through compressed symbols. */
runPos = dbufCount = selector = 0;
for (;;) {
int nextSym;
/* Fetch next Huffman coding group from list. */
symCount = GROUP_SIZE - 1;
if (selector >= nSelectors) return RETVAL_DATA_ERROR;
hufGroup = bd->groups + selectors[selector++];
base = hufGroup->base - 1;
limit = hufGroup->limit - 1;
continue_this_group:
/* Read next Huffman-coded symbol. */
/* Note: It is far cheaper to read maxLen bits and back up than it is
to read minLen bits and then add additional bit at a time, testing
as we go. Because there is a trailing last block (with file CRC),
there is no danger of the overread causing an unexpected EOF for a
valid compressed file.
*/
if (1) {
/* As a further optimization, we do the read inline
(falling back to a call to get_bits if the buffer runs dry).
*/
int new_cnt;
while ((new_cnt = bd->inbufBitCount - hufGroup->maxLen) < 0) {
/* bd->inbufBitCount < hufGroup->maxLen */
if (bd->inbufPos == bd->inbufCount) {
nextSym = get_bits(bd, hufGroup->maxLen);
goto got_huff_bits;
}
bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++];
bd->inbufBitCount += 8;
};
bd->inbufBitCount = new_cnt; /* "bd->inbufBitCount -= hufGroup->maxLen;" */
nextSym = (bd->inbufBits >> new_cnt) & ((1 << hufGroup->maxLen) - 1);
got_huff_bits: ;
} else { /* unoptimized equivalent */
nextSym = get_bits(bd, hufGroup->maxLen);
}
/* Figure how many bits are in next symbol and unget extras */
i = hufGroup->minLen;
while (nextSym > limit[i]) ++i;
j = hufGroup->maxLen - i;
if (j < 0)
return RETVAL_DATA_ERROR;
bd->inbufBitCount += j;
/* Huffman decode value to get nextSym (with bounds checking) */
nextSym = (nextSym >> j) - base[i];
if ((unsigned)nextSym >= MAX_SYMBOLS)
return RETVAL_DATA_ERROR;
nextSym = hufGroup->permute[nextSym];
/* We have now decoded the symbol, which indicates either a new literal
byte, or a repeated run of the most recent literal byte. First,
check if nextSym indicates a repeated run, and if so loop collecting
how many times to repeat the last literal. */
if ((unsigned)nextSym <= SYMBOL_RUNB) { /* RUNA or RUNB */
/* If this is the start of a new run, zero out counter */
if (runPos == 0) {
runPos = 1;
runCnt = 0;
}
/* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
each bit position, add 1 or 2 instead. For example,
1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
You can make any bit pattern that way using 1 less symbol than
the basic or 0/1 method (except all bits 0, which would use no
symbols, but a run of length 0 doesn't mean anything in this
context). Thus space is saved. */
runCnt += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */
////The 32-bit overflow of runCnt wasn't yet seen, but probably can happen.
////This would be the fix (catches too large count way before it can overflow):
//// if (runCnt > bd->dbufSize) {
//// dbg("runCnt:%u > dbufSize:%u RETVAL_DATA_ERROR",
//// runCnt, bd->dbufSize);
//// return RETVAL_DATA_ERROR;
//// }
if (runPos < bd->dbufSize) runPos <<= 1;
goto end_of_huffman_loop;
}
dbg("dbufCount:%d+runCnt:%d %d > dbufSize:%d RETVAL_DATA_ERROR",
dbufCount, runCnt, dbufCount + runCnt, dbufSize);
return RETVAL_DATA_ERROR;
literal used is the one at the head of the mtfSymbol array.) */
if (runPos != 0) {
uint8_t tmp_byte;
if (dbufCount + runCnt > bd->dbufSize) {
dbg("dbufCount:%u+runCnt:%u %u > dbufSize:%u RETVAL_DATA_ERROR",
dbufCount, runCnt, dbufCount + runCnt, bd->dbufSize);
return RETVAL_DATA_ERROR;
}
tmp_byte = symToByte[mtfSymbol[0]];
byteCount[tmp_byte] += runCnt;
while ((int)--runCnt >= 0)
dbuf[dbufCount++] = (uint32_t)tmp_byte;
runPos = 0;
}
as part of a run above. Therefore 1 unused mtf position minus
2 non-literal nextSym values equals -1.) */
if (dbufCount >= dbufSize) return RETVAL_DATA_ERROR;
i = nextSym - 1;
uc = mtfSymbol[i];
/* Adjust the MTF array. Since we typically expect to move only a
first symbol in the mtf array, position 0, would have been handled
as part of a run above. Therefore 1 unused mtf position minus
2 non-literal nextSym values equals -1.) */
if (dbufCount >= bd->dbufSize) return RETVAL_DATA_ERROR;
i = nextSym - 1;
uc = mtfSymbol[i];
uc = symToByte[uc];
/* We have our literal byte. Save it into dbuf. */
byteCount[uc]++;
dbuf[dbufCount++] = (uint32_t)uc;
/* Skip group initialization if we're not done with this group. Done
* this way to avoid compiler warning. */
end_of_huffman_loop:
if (--symCount >= 0) goto continue_this_group;
}
/* At this point, we've read all the Huffman-coded symbols (and repeated
runs) for this block from the input stream, and decoded them into the
intermediate buffer. There are dbufCount many decoded bytes in dbuf[].
Now undo the Burrows-Wheeler transform on dbuf.
See http://dogma.net/markn/articles/bwt/bwt.htm
*/
/* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
j = 0;
for (i = 0; i < 256; i++) {
int tmp_count = j + byteCount[i];
byteCount[i] = j;
j = tmp_count;
}
/* Figure out what order dbuf would be in if we sorted it. */
for (i = 0; i < dbufCount; i++) {
uint8_t tmp_byte = (uint8_t)dbuf[i];
int tmp_count = byteCount[tmp_byte];
dbuf[tmp_count] |= (i << 8);
byteCount[tmp_byte] = tmp_count + 1;
}
/* Decode first byte by hand to initialize "previous" byte. Note that it
doesn't get output, and if the first three characters are identical
it doesn't qualify as a run (hence writeRunCountdown=5). */
if (dbufCount) {
uint32_t tmp;
if ((int)origPtr >= dbufCount) return RETVAL_DATA_ERROR;
tmp = dbuf[origPtr];
bd->writeCurrent = (uint8_t)tmp;
bd->writePos = (tmp >> 8);
bd->writeRunCountdown = 5;
}
bd->writeCount = dbufCount;
return RETVAL_OK;
}
| 164,650 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: GDataFile* AddFile(GDataDirectory* parent,
GDataDirectoryService* directory_service,
int sequence_id) {
GDataFile* file = new GDataFile(NULL, directory_service);
const std::string title = "file" + base::IntToString(sequence_id);
const std::string resource_id = std::string("file_resource_id:") +
title;
file->set_title(title);
file->set_resource_id(resource_id);
file->set_file_md5(std::string("file_md5:") + title);
GDataFileError error = GDATA_FILE_ERROR_FAILED;
FilePath moved_file_path;
directory_service->MoveEntryToDirectory(
parent->GetFilePath(),
file,
base::Bind(&test_util::CopyResultsFromFileMoveCallback,
&error,
&moved_file_path));
test_util::RunBlockingPoolTask();
EXPECT_EQ(GDATA_FILE_OK, error);
EXPECT_EQ(parent->GetFilePath().AppendASCII(title), moved_file_path);
return file;
}
Commit Message: Remove parent* arg from GDataEntry ctor.
* Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry.
* Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry.
* Add GDataDirectoryService::FromDocumentEntry and use this everywhere.
* Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and
CreateGDataDirectory. Make GDataEntry ctor protected.
BUG=141494
TEST=unit tests.
Review URL: https://chromiumcodereview.appspot.com/10854083
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | GDataFile* AddFile(GDataDirectory* parent,
GDataDirectoryService* directory_service,
int sequence_id) {
GDataFile* file = directory_service->CreateGDataFile();
const std::string title = "file" + base::IntToString(sequence_id);
const std::string resource_id = std::string("file_resource_id:") +
title;
file->set_title(title);
file->set_resource_id(resource_id);
file->set_file_md5(std::string("file_md5:") + title);
GDataFileError error = GDATA_FILE_ERROR_FAILED;
FilePath moved_file_path;
directory_service->MoveEntryToDirectory(
parent->GetFilePath(),
file,
base::Bind(&test_util::CopyResultsFromFileMoveCallback,
&error,
&moved_file_path));
test_util::RunBlockingPoolTask();
EXPECT_EQ(GDATA_FILE_OK, error);
EXPECT_EQ(parent->GetFilePath().AppendASCII(title), moved_file_path);
return file;
}
| 171,495 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void watchdog_overflow_callback(struct perf_event *event, int nmi,
struct perf_sample_data *data,
struct pt_regs *regs)
{
/* Ensure the watchdog never gets throttled */
event->hw.interrupts = 0;
if (__this_cpu_read(watchdog_nmi_touch) == true) {
__this_cpu_write(watchdog_nmi_touch, false);
return;
}
/* check for a hardlockup
* This is done by making sure our timer interrupt
* is incrementing. The timer interrupt should have
* fired multiple times before we overflow'd. If it hasn't
* then this is a good indication the cpu is stuck
*/
if (is_hardlockup()) {
int this_cpu = smp_processor_id();
/* only print hardlockups once */
if (__this_cpu_read(hard_watchdog_warn) == true)
return;
if (hardlockup_panic)
panic("Watchdog detected hard LOCKUP on cpu %d", this_cpu);
else
WARN(1, "Watchdog detected hard LOCKUP on cpu %d", this_cpu);
__this_cpu_write(hard_watchdog_warn, true);
return;
}
__this_cpu_write(hard_watchdog_warn, false);
return;
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | static void watchdog_overflow_callback(struct perf_event *event, int nmi,
static void watchdog_overflow_callback(struct perf_event *event,
struct perf_sample_data *data,
struct pt_regs *regs)
{
/* Ensure the watchdog never gets throttled */
event->hw.interrupts = 0;
if (__this_cpu_read(watchdog_nmi_touch) == true) {
__this_cpu_write(watchdog_nmi_touch, false);
return;
}
/* check for a hardlockup
* This is done by making sure our timer interrupt
* is incrementing. The timer interrupt should have
* fired multiple times before we overflow'd. If it hasn't
* then this is a good indication the cpu is stuck
*/
if (is_hardlockup()) {
int this_cpu = smp_processor_id();
/* only print hardlockups once */
if (__this_cpu_read(hard_watchdog_warn) == true)
return;
if (hardlockup_panic)
panic("Watchdog detected hard LOCKUP on cpu %d", this_cpu);
else
WARN(1, "Watchdog detected hard LOCKUP on cpu %d", this_cpu);
__this_cpu_write(hard_watchdog_warn, true);
return;
}
__this_cpu_write(hard_watchdog_warn, false);
return;
}
| 165,844 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: const char* Track::GetCodecNameAsUTF8() const
{
return m_info.codecNameAsUTF8;
}
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::GetCodecNameAsUTF8() const
| 174,294 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void process_tree(struct rev_info *revs,
struct tree *tree,
show_object_fn show,
struct strbuf *base,
const char *name,
void *cb_data)
{
struct object *obj = &tree->object;
struct tree_desc desc;
struct name_entry entry;
enum interesting match = revs->diffopt.pathspec.nr == 0 ?
all_entries_interesting: entry_not_interesting;
int baselen = base->len;
if (!revs->tree_objects)
return;
if (!obj)
die("bad tree object");
if (obj->flags & (UNINTERESTING | SEEN))
return;
if (parse_tree_gently(tree, revs->ignore_missing_links) < 0) {
if (revs->ignore_missing_links)
return;
die("bad tree object %s", oid_to_hex(&obj->oid));
}
obj->flags |= SEEN;
show(obj, base, name, cb_data);
strbuf_addstr(base, name);
if (base->len)
strbuf_addch(base, '/');
init_tree_desc(&desc, tree->buffer, tree->size);
while (tree_entry(&desc, &entry)) {
if (match != all_entries_interesting) {
match = tree_entry_interesting(&entry, base, 0,
&revs->diffopt.pathspec);
if (match == all_entries_not_interesting)
break;
if (match == entry_not_interesting)
continue;
}
if (S_ISDIR(entry.mode))
process_tree(revs,
lookup_tree(entry.sha1),
show, base, entry.path,
cb_data);
else if (S_ISGITLINK(entry.mode))
process_gitlink(revs, entry.sha1,
show, base, entry.path,
cb_data);
else
process_blob(revs,
lookup_blob(entry.sha1),
show, base, entry.path,
cb_data);
}
strbuf_setlen(base, baselen);
free_tree_buffer(tree);
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[email protected]>
CWE ID: CWE-119 | static void process_tree(struct rev_info *revs,
struct tree *tree,
show_object_fn show,
struct strbuf *base,
const char *name,
void *cb_data)
{
struct object *obj = &tree->object;
struct tree_desc desc;
struct name_entry entry;
enum interesting match = revs->diffopt.pathspec.nr == 0 ?
all_entries_interesting: entry_not_interesting;
int baselen = base->len;
if (!revs->tree_objects)
return;
if (!obj)
die("bad tree object");
if (obj->flags & (UNINTERESTING | SEEN))
return;
if (parse_tree_gently(tree, revs->ignore_missing_links) < 0) {
if (revs->ignore_missing_links)
return;
die("bad tree object %s", oid_to_hex(&obj->oid));
}
obj->flags |= SEEN;
strbuf_addstr(base, name);
show(obj, base->buf, cb_data);
if (base->len)
strbuf_addch(base, '/');
init_tree_desc(&desc, tree->buffer, tree->size);
while (tree_entry(&desc, &entry)) {
if (match != all_entries_interesting) {
match = tree_entry_interesting(&entry, base, 0,
&revs->diffopt.pathspec);
if (match == all_entries_not_interesting)
break;
if (match == entry_not_interesting)
continue;
}
if (S_ISDIR(entry.mode))
process_tree(revs,
lookup_tree(entry.sha1),
show, base, entry.path,
cb_data);
else if (S_ISGITLINK(entry.mode))
process_gitlink(revs, entry.sha1,
show, base, entry.path,
cb_data);
else
process_blob(revs,
lookup_blob(entry.sha1),
show, base, entry.path,
cb_data);
}
strbuf_setlen(base, baselen);
free_tree_buffer(tree);
}
| 167,419 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ServiceWorkerHandler::ServiceWorkerHandler()
: DevToolsDomainHandler(ServiceWorker::Metainfo::domainName),
enabled_(false),
process_(nullptr),
weak_factory_(this) {}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | ServiceWorkerHandler::ServiceWorkerHandler()
: DevToolsDomainHandler(ServiceWorker::Metainfo::domainName),
enabled_(false),
browser_context_(nullptr),
storage_partition_(nullptr),
weak_factory_(this) {}
| 172,768 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void rds_tcp_kill_sock(struct net *net)
{
struct rds_tcp_connection *tc, *_tc;
LIST_HEAD(tmp_list);
struct rds_tcp_net *rtn = net_generic(net, rds_tcp_netid);
struct socket *lsock = rtn->rds_tcp_listen_sock;
rtn->rds_tcp_listen_sock = NULL;
rds_tcp_listen_stop(lsock, &rtn->rds_tcp_accept_w);
spin_lock_irq(&rds_tcp_conn_lock);
list_for_each_entry_safe(tc, _tc, &rds_tcp_conn_list, t_tcp_node) {
struct net *c_net = read_pnet(&tc->t_cpath->cp_conn->c_net);
if (net != c_net || !tc->t_sock)
continue;
if (!list_has_conn(&tmp_list, tc->t_cpath->cp_conn)) {
list_move_tail(&tc->t_tcp_node, &tmp_list);
} else {
list_del(&tc->t_tcp_node);
tc->t_tcp_node_detached = true;
}
}
spin_unlock_irq(&rds_tcp_conn_lock);
list_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node)
rds_conn_destroy(tc->t_cpath->cp_conn);
}
Commit Message: net: rds: force to destroy connection if t_sock is NULL in rds_tcp_kill_sock().
When it is to cleanup net namespace, rds_tcp_exit_net() will call
rds_tcp_kill_sock(), if t_sock is NULL, it will not call
rds_conn_destroy(), rds_conn_path_destroy() and rds_tcp_conn_free() to free
connection, and the worker cp_conn_w is not stopped, afterwards the net is freed in
net_drop_ns(); While cp_conn_w rds_connect_worker() will call rds_tcp_conn_path_connect()
and reference 'net' which has already been freed.
In rds_tcp_conn_path_connect(), rds_tcp_set_callbacks() will set t_sock = sock before
sock->ops->connect, but if connect() is failed, it will call
rds_tcp_restore_callbacks() and set t_sock = NULL, if connect is always
failed, rds_connect_worker() will try to reconnect all the time, so
rds_tcp_kill_sock() will never to cancel worker cp_conn_w and free the
connections.
Therefore, the condition !tc->t_sock is not needed if it is going to do
cleanup_net->rds_tcp_exit_net->rds_tcp_kill_sock, because tc->t_sock is always
NULL, and there is on other path to cancel cp_conn_w and free
connection. So this patch is to fix this.
rds_tcp_kill_sock():
...
if (net != c_net || !tc->t_sock)
...
Acked-by: Santosh Shilimkar <[email protected]>
==================================================================
BUG: KASAN: use-after-free in inet_create+0xbcc/0xd28
net/ipv4/af_inet.c:340
Read of size 4 at addr ffff8003496a4684 by task kworker/u8:4/3721
CPU: 3 PID: 3721 Comm: kworker/u8:4 Not tainted 5.1.0 #11
Hardware name: linux,dummy-virt (DT)
Workqueue: krdsd rds_connect_worker
Call trace:
dump_backtrace+0x0/0x3c0 arch/arm64/kernel/time.c:53
show_stack+0x28/0x38 arch/arm64/kernel/traps.c:152
__dump_stack lib/dump_stack.c:77 [inline]
dump_stack+0x120/0x188 lib/dump_stack.c:113
print_address_description+0x68/0x278 mm/kasan/report.c:253
kasan_report_error mm/kasan/report.c:351 [inline]
kasan_report+0x21c/0x348 mm/kasan/report.c:409
__asan_report_load4_noabort+0x30/0x40 mm/kasan/report.c:429
inet_create+0xbcc/0xd28 net/ipv4/af_inet.c:340
__sock_create+0x4f8/0x770 net/socket.c:1276
sock_create_kern+0x50/0x68 net/socket.c:1322
rds_tcp_conn_path_connect+0x2b4/0x690 net/rds/tcp_connect.c:114
rds_connect_worker+0x108/0x1d0 net/rds/threads.c:175
process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153
worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296
kthread+0x2f0/0x378 kernel/kthread.c:255
ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117
Allocated by task 687:
save_stack mm/kasan/kasan.c:448 [inline]
set_track mm/kasan/kasan.c:460 [inline]
kasan_kmalloc+0xd4/0x180 mm/kasan/kasan.c:553
kasan_slab_alloc+0x14/0x20 mm/kasan/kasan.c:490
slab_post_alloc_hook mm/slab.h:444 [inline]
slab_alloc_node mm/slub.c:2705 [inline]
slab_alloc mm/slub.c:2713 [inline]
kmem_cache_alloc+0x14c/0x388 mm/slub.c:2718
kmem_cache_zalloc include/linux/slab.h:697 [inline]
net_alloc net/core/net_namespace.c:384 [inline]
copy_net_ns+0xc4/0x2d0 net/core/net_namespace.c:424
create_new_namespaces+0x300/0x658 kernel/nsproxy.c:107
unshare_nsproxy_namespaces+0xa0/0x198 kernel/nsproxy.c:206
ksys_unshare+0x340/0x628 kernel/fork.c:2577
__do_sys_unshare kernel/fork.c:2645 [inline]
__se_sys_unshare kernel/fork.c:2643 [inline]
__arm64_sys_unshare+0x38/0x58 kernel/fork.c:2643
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall arch/arm64/kernel/syscall.c:47 [inline]
el0_svc_common+0x168/0x390 arch/arm64/kernel/syscall.c:83
el0_svc_handler+0x60/0xd0 arch/arm64/kernel/syscall.c:129
el0_svc+0x8/0xc arch/arm64/kernel/entry.S:960
Freed by task 264:
save_stack mm/kasan/kasan.c:448 [inline]
set_track mm/kasan/kasan.c:460 [inline]
__kasan_slab_free+0x114/0x220 mm/kasan/kasan.c:521
kasan_slab_free+0x10/0x18 mm/kasan/kasan.c:528
slab_free_hook mm/slub.c:1370 [inline]
slab_free_freelist_hook mm/slub.c:1397 [inline]
slab_free mm/slub.c:2952 [inline]
kmem_cache_free+0xb8/0x3a8 mm/slub.c:2968
net_free net/core/net_namespace.c:400 [inline]
net_drop_ns.part.6+0x78/0x90 net/core/net_namespace.c:407
net_drop_ns net/core/net_namespace.c:406 [inline]
cleanup_net+0x53c/0x6d8 net/core/net_namespace.c:569
process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153
worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296
kthread+0x2f0/0x378 kernel/kthread.c:255
ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117
The buggy address belongs to the object at ffff8003496a3f80
which belongs to the cache net_namespace of size 7872
The buggy address is located 1796 bytes inside of
7872-byte region [ffff8003496a3f80, ffff8003496a5e40)
The buggy address belongs to the page:
page:ffff7e000d25a800 count:1 mapcount:0 mapping:ffff80036ce4b000
index:0x0 compound_mapcount: 0
flags: 0xffffe0000008100(slab|head)
raw: 0ffffe0000008100 dead000000000100 dead000000000200 ffff80036ce4b000
raw: 0000000000000000 0000000080040004 00000001ffffffff 0000000000000000
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff8003496a4580: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff8003496a4600: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
>ffff8003496a4680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff8003496a4700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff8003496a4780: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
Fixes: 467fa15356ac("RDS-TCP: Support multiple RDS-TCP listen endpoints, one per netns.")
Reported-by: Hulk Robot <[email protected]>
Signed-off-by: Mao Wenan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static void rds_tcp_kill_sock(struct net *net)
{
struct rds_tcp_connection *tc, *_tc;
LIST_HEAD(tmp_list);
struct rds_tcp_net *rtn = net_generic(net, rds_tcp_netid);
struct socket *lsock = rtn->rds_tcp_listen_sock;
rtn->rds_tcp_listen_sock = NULL;
rds_tcp_listen_stop(lsock, &rtn->rds_tcp_accept_w);
spin_lock_irq(&rds_tcp_conn_lock);
list_for_each_entry_safe(tc, _tc, &rds_tcp_conn_list, t_tcp_node) {
struct net *c_net = read_pnet(&tc->t_cpath->cp_conn->c_net);
if (net != c_net)
continue;
if (!list_has_conn(&tmp_list, tc->t_cpath->cp_conn)) {
list_move_tail(&tc->t_tcp_node, &tmp_list);
} else {
list_del(&tc->t_tcp_node);
tc->t_tcp_node_detached = true;
}
}
spin_unlock_irq(&rds_tcp_conn_lock);
list_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node)
rds_conn_destroy(tc->t_cpath->cp_conn);
}
| 169,679 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Maybe<bool> IncludesValueImpl(Isolate* isolate,
Handle<JSObject> receiver,
Handle<Object> value,
uint32_t start_from, uint32_t length) {
DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));
bool search_for_hole = value->IsUndefined(isolate);
if (!search_for_hole) {
Maybe<bool> result = Nothing<bool>();
if (DictionaryElementsAccessor::IncludesValueFastPath(
isolate, receiver, value, start_from, length, &result)) {
return result;
}
}
Handle<SeededNumberDictionary> dictionary(
SeededNumberDictionary::cast(receiver->elements()), isolate);
for (uint32_t k = start_from; k < length; ++k) {
int entry = dictionary->FindEntry(isolate, k);
if (entry == SeededNumberDictionary::kNotFound) {
if (search_for_hole) return Just(true);
continue;
}
PropertyDetails details = GetDetailsImpl(*dictionary, entry);
switch (details.kind()) {
case kData: {
Object* element_k = dictionary->ValueAt(entry);
if (value->SameValueZero(element_k)) return Just(true);
break;
}
case kAccessor: {
LookupIterator it(isolate, receiver, k,
LookupIterator::OWN_SKIP_INTERCEPTOR);
DCHECK(it.IsFound());
DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
Handle<Object> element_k;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate, element_k, JSObject::GetPropertyWithAccessor(&it),
Nothing<bool>());
if (value->SameValueZero(*element_k)) return Just(true);
if (!JSObject::PrototypeHasNoElements(isolate, *receiver)) {
return IncludesValueSlowPath(isolate, receiver, value, k + 1,
length);
}
if (*dictionary == receiver->elements()) continue;
if (receiver->GetElementsKind() != DICTIONARY_ELEMENTS) {
if (receiver->map()->GetInitialElements() == receiver->elements()) {
return Just(search_for_hole);
}
return IncludesValueSlowPath(isolate, receiver, value, k + 1,
length);
}
dictionary = handle(
SeededNumberDictionary::cast(receiver->elements()), isolate);
break;
}
}
}
return Just(false);
}
Commit Message: Backport: Fix Object.entries/values with changing elements
Bug: 111274046
Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \
/data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest
Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb
(cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99)
CWE ID: CWE-704 | static Maybe<bool> IncludesValueImpl(Isolate* isolate,
Handle<JSObject> receiver,
Handle<Object> value,
uint32_t start_from, uint32_t length) {
DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));
bool search_for_hole = value->IsUndefined(isolate);
if (!search_for_hole) {
Maybe<bool> result = Nothing<bool>();
if (DictionaryElementsAccessor::IncludesValueFastPath(
isolate, receiver, value, start_from, length, &result)) {
return result;
}
}
Handle<Map> original_map(receiver->map(), isolate);
Handle<SeededNumberDictionary> dictionary(
SeededNumberDictionary::cast(receiver->elements()), isolate);
for (uint32_t k = start_from; k < length; ++k) {
DCHECK_EQ(receiver->map(), *original_map);
int entry = dictionary->FindEntry(isolate, k);
if (entry == SeededNumberDictionary::kNotFound) {
if (search_for_hole) return Just(true);
continue;
}
PropertyDetails details = GetDetailsImpl(*dictionary, entry);
switch (details.kind()) {
case kData: {
Object* element_k = dictionary->ValueAt(entry);
if (value->SameValueZero(element_k)) return Just(true);
break;
}
case kAccessor: {
LookupIterator it(isolate, receiver, k,
LookupIterator::OWN_SKIP_INTERCEPTOR);
DCHECK(it.IsFound());
DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
Handle<Object> element_k;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate, element_k, JSObject::GetPropertyWithAccessor(&it),
Nothing<bool>());
if (value->SameValueZero(*element_k)) return Just(true);
if (!JSObject::PrototypeHasNoElements(isolate, *receiver)) {
return IncludesValueSlowPath(isolate, receiver, value, k + 1,
length);
}
if (*dictionary == receiver->elements()) continue;
if (receiver->GetElementsKind() != DICTIONARY_ELEMENTS) {
if (receiver->map()->GetInitialElements() == receiver->elements()) {
return Just(search_for_hole);
}
return IncludesValueSlowPath(isolate, receiver, value, k + 1,
length);
}
dictionary = handle(
SeededNumberDictionary::cast(receiver->elements()), isolate);
break;
}
}
}
return Just(false);
}
| 174,096 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int raw_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct inet_sock *inet = inet_sk(sk);
struct net *net = sock_net(sk);
struct ipcm_cookie ipc;
struct rtable *rt = NULL;
struct flowi4 fl4;
int free = 0;
__be32 daddr;
__be32 saddr;
u8 tos;
int err;
struct ip_options_data opt_copy;
struct raw_frag_vec rfv;
err = -EMSGSIZE;
if (len > 0xFFFF)
goto out;
/*
* Check the flags.
*/
err = -EOPNOTSUPP;
if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message */
goto out; /* compatibility */
/*
* Get and verify the address.
*/
if (msg->msg_namelen) {
DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
err = -EINVAL;
if (msg->msg_namelen < sizeof(*usin))
goto out;
if (usin->sin_family != AF_INET) {
pr_info_once("%s: %s forgot to set AF_INET. Fix it!\n",
__func__, current->comm);
err = -EAFNOSUPPORT;
if (usin->sin_family)
goto out;
}
daddr = usin->sin_addr.s_addr;
/* ANK: I did not forget to get protocol from port field.
* I just do not know, who uses this weirdness.
* IP_HDRINCL is much more convenient.
*/
} else {
err = -EDESTADDRREQ;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
daddr = inet->inet_daddr;
}
ipc.sockc.tsflags = sk->sk_tsflags;
ipc.addr = inet->inet_saddr;
ipc.opt = NULL;
ipc.tx_flags = 0;
ipc.ttl = 0;
ipc.tos = -1;
ipc.oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
err = ip_cmsg_send(sk, msg, &ipc, false);
if (unlikely(err)) {
kfree(ipc.opt);
goto out;
}
if (ipc.opt)
free = 1;
}
saddr = ipc.addr;
ipc.addr = daddr;
if (!ipc.opt) {
struct ip_options_rcu *inet_opt;
rcu_read_lock();
inet_opt = rcu_dereference(inet->inet_opt);
if (inet_opt) {
memcpy(&opt_copy, inet_opt,
sizeof(*inet_opt) + inet_opt->opt.optlen);
ipc.opt = &opt_copy.opt;
}
rcu_read_unlock();
}
if (ipc.opt) {
err = -EINVAL;
/* Linux does not mangle headers on raw sockets,
* so that IP options + IP_HDRINCL is non-sense.
*/
if (inet->hdrincl)
goto done;
if (ipc.opt->opt.srr) {
if (!daddr)
goto done;
daddr = ipc.opt->opt.faddr;
}
}
tos = get_rtconn_flags(&ipc, sk);
if (msg->msg_flags & MSG_DONTROUTE)
tos |= RTO_ONLINK;
if (ipv4_is_multicast(daddr)) {
if (!ipc.oif)
ipc.oif = inet->mc_index;
if (!saddr)
saddr = inet->mc_addr;
} else if (!ipc.oif)
ipc.oif = inet->uc_index;
flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos,
RT_SCOPE_UNIVERSE,
inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol,
inet_sk_flowi_flags(sk) |
(inet->hdrincl ? FLOWI_FLAG_KNOWN_NH : 0),
daddr, saddr, 0, 0, sk->sk_uid);
if (!inet->hdrincl) {
rfv.msg = msg;
rfv.hlen = 0;
err = raw_probe_proto_opt(&rfv, &fl4);
if (err)
goto done;
}
security_sk_classify_flow(sk, flowi4_to_flowi(&fl4));
rt = ip_route_output_flow(net, &fl4, sk);
if (IS_ERR(rt)) {
err = PTR_ERR(rt);
rt = NULL;
goto done;
}
err = -EACCES;
if (rt->rt_flags & RTCF_BROADCAST && !sock_flag(sk, SOCK_BROADCAST))
goto done;
if (msg->msg_flags & MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
if (inet->hdrincl)
err = raw_send_hdrinc(sk, &fl4, msg, len,
&rt, msg->msg_flags, &ipc.sockc);
else {
sock_tx_timestamp(sk, ipc.sockc.tsflags, &ipc.tx_flags);
if (!ipc.addr)
ipc.addr = fl4.daddr;
lock_sock(sk);
err = ip_append_data(sk, &fl4, raw_getfrag,
&rfv, len, 0,
&ipc, &rt, msg->msg_flags);
if (err)
ip_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE)) {
err = ip_push_pending_frames(sk, &fl4);
if (err == -ENOBUFS && !inet->recverr)
err = 0;
}
release_sock(sk);
}
done:
if (free)
kfree(ipc.opt);
ip_rt_put(rt);
out:
if (err < 0)
return err;
return len;
do_confirm:
if (msg->msg_flags & MSG_PROBE)
dst_confirm_neigh(&rt->dst, &fl4.daddr);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
Commit Message: net: ipv4: fix for a race condition in raw_sendmsg
inet->hdrincl is racy, and could lead to uninitialized stack pointer
usage, so its value should be read only once.
Fixes: c008ba5bdc9f ("ipv4: Avoid reading user iov twice after raw_probe_proto_opt")
Signed-off-by: Mohamed Ghannam <[email protected]>
Reviewed-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static int raw_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct inet_sock *inet = inet_sk(sk);
struct net *net = sock_net(sk);
struct ipcm_cookie ipc;
struct rtable *rt = NULL;
struct flowi4 fl4;
int free = 0;
__be32 daddr;
__be32 saddr;
u8 tos;
int err;
struct ip_options_data opt_copy;
struct raw_frag_vec rfv;
int hdrincl;
err = -EMSGSIZE;
if (len > 0xFFFF)
goto out;
/* hdrincl should be READ_ONCE(inet->hdrincl)
* but READ_ONCE() doesn't work with bit fields
*/
hdrincl = inet->hdrincl;
/*
* Check the flags.
*/
err = -EOPNOTSUPP;
if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message */
goto out; /* compatibility */
/*
* Get and verify the address.
*/
if (msg->msg_namelen) {
DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
err = -EINVAL;
if (msg->msg_namelen < sizeof(*usin))
goto out;
if (usin->sin_family != AF_INET) {
pr_info_once("%s: %s forgot to set AF_INET. Fix it!\n",
__func__, current->comm);
err = -EAFNOSUPPORT;
if (usin->sin_family)
goto out;
}
daddr = usin->sin_addr.s_addr;
/* ANK: I did not forget to get protocol from port field.
* I just do not know, who uses this weirdness.
* IP_HDRINCL is much more convenient.
*/
} else {
err = -EDESTADDRREQ;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
daddr = inet->inet_daddr;
}
ipc.sockc.tsflags = sk->sk_tsflags;
ipc.addr = inet->inet_saddr;
ipc.opt = NULL;
ipc.tx_flags = 0;
ipc.ttl = 0;
ipc.tos = -1;
ipc.oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
err = ip_cmsg_send(sk, msg, &ipc, false);
if (unlikely(err)) {
kfree(ipc.opt);
goto out;
}
if (ipc.opt)
free = 1;
}
saddr = ipc.addr;
ipc.addr = daddr;
if (!ipc.opt) {
struct ip_options_rcu *inet_opt;
rcu_read_lock();
inet_opt = rcu_dereference(inet->inet_opt);
if (inet_opt) {
memcpy(&opt_copy, inet_opt,
sizeof(*inet_opt) + inet_opt->opt.optlen);
ipc.opt = &opt_copy.opt;
}
rcu_read_unlock();
}
if (ipc.opt) {
err = -EINVAL;
/* Linux does not mangle headers on raw sockets,
* so that IP options + IP_HDRINCL is non-sense.
*/
if (hdrincl)
goto done;
if (ipc.opt->opt.srr) {
if (!daddr)
goto done;
daddr = ipc.opt->opt.faddr;
}
}
tos = get_rtconn_flags(&ipc, sk);
if (msg->msg_flags & MSG_DONTROUTE)
tos |= RTO_ONLINK;
if (ipv4_is_multicast(daddr)) {
if (!ipc.oif)
ipc.oif = inet->mc_index;
if (!saddr)
saddr = inet->mc_addr;
} else if (!ipc.oif)
ipc.oif = inet->uc_index;
flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos,
RT_SCOPE_UNIVERSE,
hdrincl ? IPPROTO_RAW : sk->sk_protocol,
inet_sk_flowi_flags(sk) |
(hdrincl ? FLOWI_FLAG_KNOWN_NH : 0),
daddr, saddr, 0, 0, sk->sk_uid);
if (!hdrincl) {
rfv.msg = msg;
rfv.hlen = 0;
err = raw_probe_proto_opt(&rfv, &fl4);
if (err)
goto done;
}
security_sk_classify_flow(sk, flowi4_to_flowi(&fl4));
rt = ip_route_output_flow(net, &fl4, sk);
if (IS_ERR(rt)) {
err = PTR_ERR(rt);
rt = NULL;
goto done;
}
err = -EACCES;
if (rt->rt_flags & RTCF_BROADCAST && !sock_flag(sk, SOCK_BROADCAST))
goto done;
if (msg->msg_flags & MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
if (hdrincl)
err = raw_send_hdrinc(sk, &fl4, msg, len,
&rt, msg->msg_flags, &ipc.sockc);
else {
sock_tx_timestamp(sk, ipc.sockc.tsflags, &ipc.tx_flags);
if (!ipc.addr)
ipc.addr = fl4.daddr;
lock_sock(sk);
err = ip_append_data(sk, &fl4, raw_getfrag,
&rfv, len, 0,
&ipc, &rt, msg->msg_flags);
if (err)
ip_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE)) {
err = ip_push_pending_frames(sk, &fl4);
if (err == -ENOBUFS && !inet->recverr)
err = 0;
}
release_sock(sk);
}
done:
if (free)
kfree(ipc.opt);
ip_rt_put(rt);
out:
if (err < 0)
return err;
return len;
do_confirm:
if (msg->msg_flags & MSG_PROBE)
dst_confirm_neigh(&rt->dst, &fl4.daddr);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
| 167,653 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ssl3_get_new_session_ticket(SSL *s)
{
int ok, al, ret = 0, ticklen;
long n;
const unsigned char *p;
unsigned char *d;
n = s->method->ssl_get_message(s,
SSL3_ST_CR_SESSION_TICKET_A,
SSL3_ST_CR_SESSION_TICKET_B,
SSL3_MT_NEWSESSION_TICKET, 16384, &ok);
if (!ok)
return ((int)n);
if (n < 6) {
/* need at least ticket_lifetime_hint + ticket length */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
p = d = (unsigned char *)s->init_msg;
n2l(p, s->session->tlsext_tick_lifetime_hint);
n2s(p, ticklen);
/* ticket_lifetime_hint + ticket_length + ticket */
if (ticklen + 6 != n) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
OPENSSL_free(s->session->tlsext_tick);
s->session->tlsext_ticklen = 0;
s->session->tlsext_tick = OPENSSL_malloc(ticklen);
if (!s->session->tlsext_tick) {
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
goto err;
}
memcpy(s->session->tlsext_tick, p, ticklen);
s->session->tlsext_ticklen = ticklen;
/*
* There are two ways to detect a resumed ticket session. One is to set
* an appropriate session ID and then the server must return a match in
* ServerHello. This allows the normal client session ID matching to work
* and we know much earlier that the ticket has been accepted. The
* other way is to set zero length session ID when the ticket is
* presented and rely on the handshake to determine session resumption.
* We choose the former approach because this fits in with assumptions
* elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
* SHA256 is disabled) hash of the ticket.
*/
EVP_Digest(p, ticklen,
s->session->session_id, &s->session->session_id_length,
EVP_sha256(), NULL);
ret = 1;
return (ret);
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
s->state = SSL_ST_ERR;
return (-1);
}
Commit Message: Fix race condition in NewSessionTicket
If a NewSessionTicket is received by a multi-threaded client when
attempting to reuse a previous ticket then a race condition can occur
potentially leading to a double free of the ticket data.
CVE-2015-1791
This also fixes RT#3808 where a session ID is changed for a session already
in the client session cache. Since the session ID is the key to the cache
this breaks the cache access.
Parts of this patch were inspired by this Akamai change:
https://github.com/akamai/openssl/commit/c0bf69a791239ceec64509f9f19fcafb2461b0d3
Reviewed-by: Rich Salz <[email protected]>
CWE ID: CWE-362 | int ssl3_get_new_session_ticket(SSL *s)
{
int ok, al, ret = 0, ticklen;
long n;
const unsigned char *p;
unsigned char *d;
n = s->method->ssl_get_message(s,
SSL3_ST_CR_SESSION_TICKET_A,
SSL3_ST_CR_SESSION_TICKET_B,
SSL3_MT_NEWSESSION_TICKET, 16384, &ok);
if (!ok)
return ((int)n);
if (n < 6) {
/* need at least ticket_lifetime_hint + ticket length */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
p = d = (unsigned char *)s->init_msg;
if (s->session->session_id_length > 0) {
int i = s->session_ctx->session_cache_mode;
SSL_SESSION *new_sess;
/*
* We reused an existing session, so we need to replace it with a new
* one
*/
if (i & SSL_SESS_CACHE_CLIENT) {
/*
* Remove the old session from the cache
*/
if (i & SSL_SESS_CACHE_NO_INTERNAL_STORE) {
if (s->session_ctx->remove_session_cb != NULL)
s->session_ctx->remove_session_cb(s->session_ctx,
s->session);
} else {
/* We carry on if this fails */
SSL_CTX_remove_session(s->session_ctx, s->session);
}
}
if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
goto f_err;
}
SSL_SESSION_free(s->session);
s->session = new_sess;
}
n2l(p, s->session->tlsext_tick_lifetime_hint);
n2s(p, ticklen);
/* ticket_lifetime_hint + ticket_length + ticket */
if (ticklen + 6 != n) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
OPENSSL_free(s->session->tlsext_tick);
s->session->tlsext_ticklen = 0;
s->session->tlsext_tick = OPENSSL_malloc(ticklen);
if (!s->session->tlsext_tick) {
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
goto err;
}
memcpy(s->session->tlsext_tick, p, ticklen);
s->session->tlsext_ticklen = ticklen;
/*
* There are two ways to detect a resumed ticket session. One is to set
* an appropriate session ID and then the server must return a match in
* ServerHello. This allows the normal client session ID matching to work
* and we know much earlier that the ticket has been accepted. The
* other way is to set zero length session ID when the ticket is
* presented and rely on the handshake to determine session resumption.
* We choose the former approach because this fits in with assumptions
* elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
* SHA256 is disabled) hash of the ticket.
*/
EVP_Digest(p, ticklen,
s->session->session_id, &s->session->session_id_length,
EVP_sha256(), NULL);
ret = 1;
return (ret);
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
s->state = SSL_ST_ERR;
return (-1);
}
| 166,691 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ssl3_get_client_key_exchange(SSL *s)
{
int i, al, ok;
long n;
unsigned long alg_k;
unsigned char *p;
#ifndef OPENSSL_NO_RSA
RSA *rsa = NULL;
EVP_PKEY *pkey = NULL;
#endif
#ifndef OPENSSL_NO_DH
BIGNUM *pub = NULL;
DH *dh_srvr, *dh_clnt = NULL;
#endif
#ifndef OPENSSL_NO_KRB5
KSSL_ERR kssl_err;
#endif /* OPENSSL_NO_KRB5 */
#ifndef OPENSSL_NO_ECDH
EC_KEY *srvr_ecdh = NULL;
EVP_PKEY *clnt_pub_pkey = NULL;
EC_POINT *clnt_ecpoint = NULL;
BN_CTX *bn_ctx = NULL;
#endif
n = s->method->ssl_get_message(s,
SSL3_ST_SR_KEY_EXCH_A,
SSL3_ST_SR_KEY_EXCH_B,
SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
if (!ok)
return ((int)n);
p = (unsigned char *)s->init_msg;
alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
#ifndef OPENSSL_NO_RSA
if (alg_k & SSL_kRSA) {
unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
int decrypt_len;
unsigned char decrypt_good, version_good;
size_t j;
/* FIX THIS UP EAY EAY EAY EAY */
if (s->s3->tmp.use_rsa_tmp) {
if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
rsa = s->cert->rsa_tmp;
/*
* Don't do a callback because rsa_tmp should be sent already
*/
if (rsa == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_TMP_RSA_PKEY);
goto f_err;
}
} else {
pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
if ((pkey == NULL) ||
(pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_RSA_CERTIFICATE);
goto f_err;
}
rsa = pkey->pkey.rsa;
}
/* TLS and [incidentally] DTLS{0xFEFF} */
if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) {
n2s(p, i);
if (n != i + 2) {
if (!(s->options & SSL_OP_TLS_D5_BUG)) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
goto f_err;
} else
p -= 2;
} else
n = i;
}
/*
* Reject overly short RSA ciphertext because we want to be sure
* that the buffer size makes it safe to iterate over the entire
* size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The
* actual expected size is larger due to RSA padding, but the
* bound is sufficient to be safe.
*/
if (n < SSL_MAX_MASTER_KEY_LENGTH) {
al = SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
goto f_err;
}
/*
* We must not leak whether a decryption failure occurs because of
* Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
* section 7.4.7.1). The code follows that advice of the TLS RFC and
* generates a random premaster secret for the case that the decrypt
* fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
*/
/*
* should be RAND_bytes, but we cannot work around a failure.
*/
if (RAND_pseudo_bytes(rand_premaster_secret,
sizeof(rand_premaster_secret)) <= 0)
goto err;
decrypt_len =
RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
ERR_clear_error();
/*
* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
* be 0xff if so and zero otherwise.
*/
decrypt_good =
constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
/*
* If the version in the decrypted pre-master secret is correct then
* version_good will be 0xff, otherwise it'll be zero. The
* Klima-Pokorny-Rosa extension of Bleichenbacher's attack
* (http://eprint.iacr.org/2003/052/) exploits the version number
* check as a "bad version oracle". Thus version checks are done in
* constant time and are treated like any other decryption error.
*/
version_good =
constant_time_eq_8(p[0], (unsigned)(s->client_version >> 8));
version_good &=
constant_time_eq_8(p[1], (unsigned)(s->client_version & 0xff));
/*
* The premaster secret must contain the same version number as the
* ClientHello to detect version rollback attacks (strangely, the
* protocol does not offer such protection for DH ciphersuites).
* However, buggy clients exist that send the negotiated protocol
* version instead if the server does not support the requested
* protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
* clients.
*/
if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
unsigned char workaround_good;
workaround_good =
constant_time_eq_8(p[0], (unsigned)(s->version >> 8));
workaround_good &=
constant_time_eq_8(p[1], (unsigned)(s->version & 0xff));
version_good |= workaround_good;
}
/*
* Both decryption and version must be good for decrypt_good to
* remain non-zero (0xff).
*/
decrypt_good &= version_good;
/*
* Now copy rand_premaster_secret over from p using
* decrypt_good_mask. If decryption failed, then p does not
* contain valid plaintext, however, a check above guarantees
* it is still sufficiently large to read from.
*/
for (j = 0; j < sizeof(rand_premaster_secret); j++) {
p[j] = constant_time_select_8(decrypt_good, p[j],
rand_premaster_secret[j]);
}
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
p,
sizeof
(rand_premaster_secret));
OPENSSL_cleanse(p, sizeof(rand_premaster_secret));
} else
#endif
#ifndef OPENSSL_NO_DH
if (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) {
int idx = -1;
EVP_PKEY *skey = NULL;
if (n > 1) {
n2s(p, i);
} else {
if (alg_k & SSL_kDHE) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
goto f_err;
}
i = 0;
}
if (n && n != i + 2) {
if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
goto err;
} else {
p -= 2;
i = (int)n;
}
}
if (alg_k & SSL_kDHr)
idx = SSL_PKEY_DH_RSA;
else if (alg_k & SSL_kDHd)
idx = SSL_PKEY_DH_DSA;
if (idx >= 0) {
skey = s->cert->pkeys[idx].privatekey;
if ((skey == NULL) ||
(skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_RSA_CERTIFICATE);
goto f_err;
}
dh_srvr = skey->pkey.dh;
} else if (s->s3->tmp.dh == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_TMP_DH_KEY);
goto f_err;
} else
dh_srvr = s->s3->tmp.dh;
if (n == 0L) {
/* Get pubkey from cert */
EVP_PKEY *clkey = X509_get_pubkey(s->session->peer);
if (clkey) {
if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
dh_clnt = EVP_PKEY_get1_DH(clkey);
}
if (dh_clnt == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_TMP_DH_KEY);
goto f_err;
}
EVP_PKEY_free(clkey);
pub = dh_clnt->pub_key;
} else
pub = BN_bin2bn(p, i, NULL);
if (pub == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
goto err;
}
i = DH_compute_key(p, pub, dh_srvr);
if (i <= 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
BN_clear_free(pub);
goto err;
}
DH_free(s->s3->tmp.dh);
s->s3->tmp.dh = NULL;
if (dh_clnt)
DH_free(dh_clnt);
else
BN_clear_free(pub);
pub = NULL;
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
p, i);
OPENSSL_cleanse(p, i);
if (dh_clnt)
return 2;
} else
#endif
#ifndef OPENSSL_NO_KRB5
if (alg_k & SSL_kKRB5) {
krb5_error_code krb5rc;
krb5_data enc_ticket;
krb5_data authenticator;
krb5_data enc_pms;
KSSL_CTX *kssl_ctx = s->kssl_ctx;
EVP_CIPHER_CTX ciph_ctx;
const EVP_CIPHER *enc = NULL;
unsigned char iv[EVP_MAX_IV_LENGTH];
unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_BLOCK_LENGTH];
int padl, outl;
krb5_timestamp authtime = 0;
krb5_ticket_times ttimes;
int kerr = 0;
EVP_CIPHER_CTX_init(&ciph_ctx);
if (!kssl_ctx)
kssl_ctx = kssl_ctx_new();
n2s(p, i);
enc_ticket.length = i;
if (n < (long)(enc_ticket.length + 6)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto err;
}
enc_ticket.data = (char *)p;
p += enc_ticket.length;
n2s(p, i);
authenticator.length = i;
if (n < (long)(enc_ticket.length + authenticator.length + 6)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto err;
}
authenticator.data = (char *)p;
p += authenticator.length;
n2s(p, i);
enc_pms.length = i;
enc_pms.data = (char *)p;
p += enc_pms.length;
/*
* Note that the length is checked again below, ** after decryption
*/
if (enc_pms.length > sizeof pms) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto err;
}
if (n != (long)(enc_ticket.length + authenticator.length +
enc_pms.length + 6)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto err;
}
if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
&kssl_err)) != 0) {
# ifdef KSSL_DEBUG
fprintf(stderr, "kssl_sget_tkt rtn %d [%d]\n",
krb5rc, kssl_err.reason);
if (kssl_err.text)
fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
# endif /* KSSL_DEBUG */
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
goto err;
}
/*
* Note: no authenticator is not considered an error, ** but will
* return authtime == 0.
*/
if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
&authtime, &kssl_err)) != 0) {
# ifdef KSSL_DEBUG
fprintf(stderr, "kssl_check_authent rtn %d [%d]\n",
krb5rc, kssl_err.reason);
if (kssl_err.text)
fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
# endif /* KSSL_DEBUG */
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
goto err;
}
if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
goto err;
}
# ifdef KSSL_DEBUG
kssl_ctx_show(kssl_ctx);
# endif /* KSSL_DEBUG */
enc = kssl_map_enc(kssl_ctx->enctype);
if (enc == NULL)
goto err;
memset(iv, 0, sizeof iv); /* per RFC 1510 */
if (!EVP_DecryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DECRYPTION_FAILED);
goto err;
}
if (!EVP_DecryptUpdate(&ciph_ctx, pms, &outl,
(unsigned char *)enc_pms.data, enc_pms.length))
{
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DECRYPTION_FAILED);
kerr = 1;
goto kclean;
}
if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
kerr = 1;
goto kclean;
}
if (!EVP_DecryptFinal_ex(&ciph_ctx, &(pms[outl]), &padl)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DECRYPTION_FAILED);
kerr = 1;
goto kclean;
}
outl += padl;
if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
kerr = 1;
goto kclean;
}
if (!((pms[0] == (s->client_version >> 8))
&& (pms[1] == (s->client_version & 0xff)))) {
/*
* The premaster secret must contain the same version number as
* the ClientHello to detect version rollback attacks (strangely,
* the protocol does not offer such protection for DH
* ciphersuites). However, buggy clients exist that send random
* bytes instead of the protocol version. If
* SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients.
* (Perhaps we should have a separate BUG value for the Kerberos
* cipher)
*/
if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_AD_DECODE_ERROR);
kerr = 1;
goto kclean;
}
}
EVP_CIPHER_CTX_cleanup(&ciph_ctx);
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
pms, outl);
if (kssl_ctx->client_princ) {
size_t len = strlen(kssl_ctx->client_princ);
if (len < SSL_MAX_KRB5_PRINCIPAL_LENGTH) {
s->session->krb5_client_princ_len = len;
memcpy(s->session->krb5_client_princ, kssl_ctx->client_princ,
len);
}
}
/*- Was doing kssl_ctx_free() here,
* but it caused problems for apache.
* kssl_ctx = kssl_ctx_free(kssl_ctx);
* if (s->kssl_ctx) s->kssl_ctx = NULL;
*/
kclean:
OPENSSL_cleanse(pms, sizeof(pms));
if (kerr)
goto err;
} else
#endif /* OPENSSL_NO_KRB5 */
#ifndef OPENSSL_NO_ECDH
if (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)) {
int ret = 1;
int field_size = 0;
const EC_KEY *tkey;
const EC_GROUP *group;
const BIGNUM *priv_key;
/* initialize structures for server's ECDH key pair */
if ((srvr_ecdh = EC_KEY_new()) == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto err;
}
/* Let's get server private key and group information */
if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
/* use the certificate */
tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
} else {
/*
* use the ephermeral values we saved when generating the
* ServerKeyExchange msg.
*/
tkey = s->s3->tmp.ecdh;
}
group = EC_KEY_get0_group(tkey);
priv_key = EC_KEY_get0_private_key(tkey);
if (!EC_KEY_set_group(srvr_ecdh, group) ||
!EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
goto err;
}
/* Let's get client's public key */
if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto err;
}
if (n == 0L) {
/* Client Publickey was in Client Certificate */
if (alg_k & SSL_kEECDH) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_TMP_ECDH_KEY);
goto f_err;
}
if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
== NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
/*
* XXX: For now, we do not support client authentication
* using ECDH certificates so this branch (n == 0L) of the
* code is never executed. When that support is added, we
* ought to ensure the key received in the certificate is
* authorized for key agreement. ECDH_compute_key implicitly
* checks that the two ECDH shares are for the same group.
*/
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
goto f_err;
}
if (EC_POINT_copy(clnt_ecpoint,
EC_KEY_get0_public_key(clnt_pub_pkey->
pkey.ec)) == 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
goto err;
}
ret = 2; /* Skip certificate verify processing */
} else {
/*
* Get client's public key from encoded point in the
* ClientKeyExchange message.
*/
if ((bn_ctx = BN_CTX_new()) == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
ERR_R_MALLOC_FAILURE);
goto err;
}
/* Get encoded point length */
i = *p;
p += 1;
if (n != 1 + i) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
goto err;
}
if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
goto err;
}
/*
* p is pointing to somewhere in the buffer currently, so set it
* to the start
*/
p = (unsigned char *)s->init_buf->data;
}
/* Compute the shared pre-master secret */
field_size = EC_GROUP_get_degree(group);
if (field_size <= 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
goto err;
}
i = ECDH_compute_key(p, (field_size + 7) / 8, clnt_ecpoint, srvr_ecdh,
NULL);
if (i <= 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
goto err;
}
EVP_PKEY_free(clnt_pub_pkey);
EC_POINT_free(clnt_ecpoint);
EC_KEY_free(srvr_ecdh);
BN_CTX_free(bn_ctx);
EC_KEY_free(s->s3->tmp.ecdh);
s->s3->tmp.ecdh = NULL;
/* Compute the master secret */
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
p, i);
OPENSSL_cleanse(p, i);
return (ret);
} else
#endif
#ifndef OPENSSL_NO_PSK
if (alg_k & SSL_kPSK) {
unsigned char *t = NULL;
unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4];
unsigned int pre_ms_len = 0, psk_len = 0;
int psk_err = 1;
char tmp_id[PSK_MAX_IDENTITY_LEN + 1];
al = SSL_AD_HANDSHAKE_FAILURE;
n2s(p, i);
if (n != i + 2) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
goto psk_err;
}
if (i > PSK_MAX_IDENTITY_LEN) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto psk_err;
}
if (s->psk_server_callback == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_PSK_NO_SERVER_CB);
goto psk_err;
}
/*
* Create guaranteed NULL-terminated identity string for the callback
*/
memcpy(tmp_id, p, i);
memset(tmp_id + i, 0, PSK_MAX_IDENTITY_LEN + 1 - i);
psk_len = s->psk_server_callback(s, tmp_id,
psk_or_pre_ms,
sizeof(psk_or_pre_ms));
OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN + 1);
if (psk_len > PSK_MAX_PSK_LEN) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
goto psk_err;
} else if (psk_len == 0) {
/*
* PSK related to the given identity not found
*/
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_PSK_IDENTITY_NOT_FOUND);
al = SSL_AD_UNKNOWN_PSK_IDENTITY;
goto psk_err;
}
/* create PSK pre_master_secret */
pre_ms_len = 2 + psk_len + 2 + psk_len;
t = psk_or_pre_ms;
memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len);
s2n(psk_len, t);
memset(t, 0, psk_len);
t += psk_len;
s2n(psk_len, t);
if (s->session->psk_identity != NULL)
OPENSSL_free(s->session->psk_identity);
s->session->psk_identity = BUF_strdup((char *)p);
if (s->session->psk_identity == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto psk_err;
}
if (s->session->psk_identity_hint != NULL)
OPENSSL_free(s->session->psk_identity_hint);
s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
if (s->ctx->psk_identity_hint != NULL &&
s->session->psk_identity_hint == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto psk_err;
}
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
psk_or_pre_ms,
pre_ms_len);
psk_err = 0;
psk_err:
OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
if (psk_err != 0)
goto f_err;
} else
#endif
#ifndef OPENSSL_NO_SRP
if (alg_k & SSL_kSRP) {
int param_len;
n2s(p, i);
param_len = i + 2;
if (param_len > n) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_BAD_SRP_A_LENGTH);
goto f_err;
}
if (!(s->srp_ctx.A = BN_bin2bn(p, i, NULL))) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
goto err;
}
if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
|| BN_is_zero(s->srp_ctx.A)) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_BAD_SRP_PARAMETERS);
goto f_err;
}
if (s->session->srp_username != NULL)
OPENSSL_free(s->session->srp_username);
s->session->srp_username = BUF_strdup(s->srp_ctx.login);
if (s->session->srp_username == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto err;
}
if ((s->session->master_key_length =
SRP_generate_server_master_secret(s,
s->session->master_key)) < 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
goto err;
}
p += i;
} else
#endif /* OPENSSL_NO_SRP */
if (alg_k & SSL_kGOST) {
int ret = 0;
EVP_PKEY_CTX *pkey_ctx;
EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
unsigned char premaster_secret[32], *start;
size_t outlen = 32, inlen;
unsigned long alg_a;
int Ttag, Tclass;
long Tlen;
/* Get our certificate private key */
alg_a = s->s3->tmp.new_cipher->algorithm_auth;
if (alg_a & SSL_aGOST94)
pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
else if (alg_a & SSL_aGOST01)
pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
EVP_PKEY_decrypt_init(pkey_ctx);
/*
* If client certificate is present and is of the same type, maybe
* use it for key exchange. Don't mind errors from
* EVP_PKEY_derive_set_peer, because it is completely valid to use a
* client certificate for authorization only.
*/
client_pub_pkey = X509_get_pubkey(s->session->peer);
if (client_pub_pkey) {
if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
ERR_clear_error();
}
/* Decrypt session key */
if (ASN1_get_object
((const unsigned char **)&p, &Tlen, &Ttag, &Tclass,
n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE
|| Tclass != V_ASN1_UNIVERSAL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DECRYPTION_FAILED);
goto gerr;
}
start = p;
inlen = Tlen;
if (EVP_PKEY_decrypt
(pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DECRYPTION_FAILED);
goto gerr;
}
/* Generate master secret */
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
premaster_secret, 32);
OPENSSL_cleanse(premaster_secret, sizeof(premaster_secret));
/* Check if pubkey from client certificate was used */
if (EVP_PKEY_CTX_ctrl
(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
ret = 2;
else
ret = 1;
gerr:
EVP_PKEY_free(client_pub_pkey);
EVP_PKEY_CTX_free(pkey_ctx);
if (ret)
return ret;
else
goto err;
} else {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
goto f_err;
}
return (1);
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
#if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
err:
#endif
#ifndef OPENSSL_NO_ECDH
EVP_PKEY_free(clnt_pub_pkey);
EC_POINT_free(clnt_ecpoint);
if (srvr_ecdh != NULL)
EC_KEY_free(srvr_ecdh);
BN_CTX_free(bn_ctx);
#endif
s->state = SSL_ST_ERR;
return (-1);
}
Commit Message:
CWE ID: CWE-362 | int ssl3_get_client_key_exchange(SSL *s)
{
int i, al, ok;
long n;
unsigned long alg_k;
unsigned char *p;
#ifndef OPENSSL_NO_RSA
RSA *rsa = NULL;
EVP_PKEY *pkey = NULL;
#endif
#ifndef OPENSSL_NO_DH
BIGNUM *pub = NULL;
DH *dh_srvr, *dh_clnt = NULL;
#endif
#ifndef OPENSSL_NO_KRB5
KSSL_ERR kssl_err;
#endif /* OPENSSL_NO_KRB5 */
#ifndef OPENSSL_NO_ECDH
EC_KEY *srvr_ecdh = NULL;
EVP_PKEY *clnt_pub_pkey = NULL;
EC_POINT *clnt_ecpoint = NULL;
BN_CTX *bn_ctx = NULL;
#endif
n = s->method->ssl_get_message(s,
SSL3_ST_SR_KEY_EXCH_A,
SSL3_ST_SR_KEY_EXCH_B,
SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
if (!ok)
return ((int)n);
p = (unsigned char *)s->init_msg;
alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
#ifndef OPENSSL_NO_RSA
if (alg_k & SSL_kRSA) {
unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
int decrypt_len;
unsigned char decrypt_good, version_good;
size_t j;
/* FIX THIS UP EAY EAY EAY EAY */
if (s->s3->tmp.use_rsa_tmp) {
if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
rsa = s->cert->rsa_tmp;
/*
* Don't do a callback because rsa_tmp should be sent already
*/
if (rsa == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_TMP_RSA_PKEY);
goto f_err;
}
} else {
pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
if ((pkey == NULL) ||
(pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_RSA_CERTIFICATE);
goto f_err;
}
rsa = pkey->pkey.rsa;
}
/* TLS and [incidentally] DTLS{0xFEFF} */
if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) {
n2s(p, i);
if (n != i + 2) {
if (!(s->options & SSL_OP_TLS_D5_BUG)) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
goto f_err;
} else
p -= 2;
} else
n = i;
}
/*
* Reject overly short RSA ciphertext because we want to be sure
* that the buffer size makes it safe to iterate over the entire
* size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The
* actual expected size is larger due to RSA padding, but the
* bound is sufficient to be safe.
*/
if (n < SSL_MAX_MASTER_KEY_LENGTH) {
al = SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
goto f_err;
}
/*
* We must not leak whether a decryption failure occurs because of
* Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
* section 7.4.7.1). The code follows that advice of the TLS RFC and
* generates a random premaster secret for the case that the decrypt
* fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
*/
/*
* should be RAND_bytes, but we cannot work around a failure.
*/
if (RAND_pseudo_bytes(rand_premaster_secret,
sizeof(rand_premaster_secret)) <= 0)
goto err;
decrypt_len =
RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
ERR_clear_error();
/*
* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
* be 0xff if so and zero otherwise.
*/
decrypt_good =
constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
/*
* If the version in the decrypted pre-master secret is correct then
* version_good will be 0xff, otherwise it'll be zero. The
* Klima-Pokorny-Rosa extension of Bleichenbacher's attack
* (http://eprint.iacr.org/2003/052/) exploits the version number
* check as a "bad version oracle". Thus version checks are done in
* constant time and are treated like any other decryption error.
*/
version_good =
constant_time_eq_8(p[0], (unsigned)(s->client_version >> 8));
version_good &=
constant_time_eq_8(p[1], (unsigned)(s->client_version & 0xff));
/*
* The premaster secret must contain the same version number as the
* ClientHello to detect version rollback attacks (strangely, the
* protocol does not offer such protection for DH ciphersuites).
* However, buggy clients exist that send the negotiated protocol
* version instead if the server does not support the requested
* protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
* clients.
*/
if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
unsigned char workaround_good;
workaround_good =
constant_time_eq_8(p[0], (unsigned)(s->version >> 8));
workaround_good &=
constant_time_eq_8(p[1], (unsigned)(s->version & 0xff));
version_good |= workaround_good;
}
/*
* Both decryption and version must be good for decrypt_good to
* remain non-zero (0xff).
*/
decrypt_good &= version_good;
/*
* Now copy rand_premaster_secret over from p using
* decrypt_good_mask. If decryption failed, then p does not
* contain valid plaintext, however, a check above guarantees
* it is still sufficiently large to read from.
*/
for (j = 0; j < sizeof(rand_premaster_secret); j++) {
p[j] = constant_time_select_8(decrypt_good, p[j],
rand_premaster_secret[j]);
}
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
p,
sizeof
(rand_premaster_secret));
OPENSSL_cleanse(p, sizeof(rand_premaster_secret));
} else
#endif
#ifndef OPENSSL_NO_DH
if (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) {
int idx = -1;
EVP_PKEY *skey = NULL;
if (n > 1) {
n2s(p, i);
} else {
if (alg_k & SSL_kDHE) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
goto f_err;
}
i = 0;
}
if (n && n != i + 2) {
if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
goto err;
} else {
p -= 2;
i = (int)n;
}
}
if (alg_k & SSL_kDHr)
idx = SSL_PKEY_DH_RSA;
else if (alg_k & SSL_kDHd)
idx = SSL_PKEY_DH_DSA;
if (idx >= 0) {
skey = s->cert->pkeys[idx].privatekey;
if ((skey == NULL) ||
(skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_RSA_CERTIFICATE);
goto f_err;
}
dh_srvr = skey->pkey.dh;
} else if (s->s3->tmp.dh == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_TMP_DH_KEY);
goto f_err;
} else
dh_srvr = s->s3->tmp.dh;
if (n == 0L) {
/* Get pubkey from cert */
EVP_PKEY *clkey = X509_get_pubkey(s->session->peer);
if (clkey) {
if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
dh_clnt = EVP_PKEY_get1_DH(clkey);
}
if (dh_clnt == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_TMP_DH_KEY);
goto f_err;
}
EVP_PKEY_free(clkey);
pub = dh_clnt->pub_key;
} else
pub = BN_bin2bn(p, i, NULL);
if (pub == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
goto err;
}
i = DH_compute_key(p, pub, dh_srvr);
if (i <= 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
BN_clear_free(pub);
goto err;
}
DH_free(s->s3->tmp.dh);
s->s3->tmp.dh = NULL;
if (dh_clnt)
DH_free(dh_clnt);
else
BN_clear_free(pub);
pub = NULL;
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
p, i);
OPENSSL_cleanse(p, i);
if (dh_clnt)
return 2;
} else
#endif
#ifndef OPENSSL_NO_KRB5
if (alg_k & SSL_kKRB5) {
krb5_error_code krb5rc;
krb5_data enc_ticket;
krb5_data authenticator;
krb5_data enc_pms;
KSSL_CTX *kssl_ctx = s->kssl_ctx;
EVP_CIPHER_CTX ciph_ctx;
const EVP_CIPHER *enc = NULL;
unsigned char iv[EVP_MAX_IV_LENGTH];
unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_BLOCK_LENGTH];
int padl, outl;
krb5_timestamp authtime = 0;
krb5_ticket_times ttimes;
int kerr = 0;
EVP_CIPHER_CTX_init(&ciph_ctx);
if (!kssl_ctx)
kssl_ctx = kssl_ctx_new();
n2s(p, i);
enc_ticket.length = i;
if (n < (long)(enc_ticket.length + 6)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto err;
}
enc_ticket.data = (char *)p;
p += enc_ticket.length;
n2s(p, i);
authenticator.length = i;
if (n < (long)(enc_ticket.length + authenticator.length + 6)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto err;
}
authenticator.data = (char *)p;
p += authenticator.length;
n2s(p, i);
enc_pms.length = i;
enc_pms.data = (char *)p;
p += enc_pms.length;
/*
* Note that the length is checked again below, ** after decryption
*/
if (enc_pms.length > sizeof pms) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto err;
}
if (n != (long)(enc_ticket.length + authenticator.length +
enc_pms.length + 6)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto err;
}
if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
&kssl_err)) != 0) {
# ifdef KSSL_DEBUG
fprintf(stderr, "kssl_sget_tkt rtn %d [%d]\n",
krb5rc, kssl_err.reason);
if (kssl_err.text)
fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
# endif /* KSSL_DEBUG */
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
goto err;
}
/*
* Note: no authenticator is not considered an error, ** but will
* return authtime == 0.
*/
if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
&authtime, &kssl_err)) != 0) {
# ifdef KSSL_DEBUG
fprintf(stderr, "kssl_check_authent rtn %d [%d]\n",
krb5rc, kssl_err.reason);
if (kssl_err.text)
fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
# endif /* KSSL_DEBUG */
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
goto err;
}
if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
goto err;
}
# ifdef KSSL_DEBUG
kssl_ctx_show(kssl_ctx);
# endif /* KSSL_DEBUG */
enc = kssl_map_enc(kssl_ctx->enctype);
if (enc == NULL)
goto err;
memset(iv, 0, sizeof iv); /* per RFC 1510 */
if (!EVP_DecryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DECRYPTION_FAILED);
goto err;
}
if (!EVP_DecryptUpdate(&ciph_ctx, pms, &outl,
(unsigned char *)enc_pms.data, enc_pms.length))
{
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DECRYPTION_FAILED);
kerr = 1;
goto kclean;
}
if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
kerr = 1;
goto kclean;
}
if (!EVP_DecryptFinal_ex(&ciph_ctx, &(pms[outl]), &padl)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DECRYPTION_FAILED);
kerr = 1;
goto kclean;
}
outl += padl;
if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
kerr = 1;
goto kclean;
}
if (!((pms[0] == (s->client_version >> 8))
&& (pms[1] == (s->client_version & 0xff)))) {
/*
* The premaster secret must contain the same version number as
* the ClientHello to detect version rollback attacks (strangely,
* the protocol does not offer such protection for DH
* ciphersuites). However, buggy clients exist that send random
* bytes instead of the protocol version. If
* SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients.
* (Perhaps we should have a separate BUG value for the Kerberos
* cipher)
*/
if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_AD_DECODE_ERROR);
kerr = 1;
goto kclean;
}
}
EVP_CIPHER_CTX_cleanup(&ciph_ctx);
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
pms, outl);
if (kssl_ctx->client_princ) {
size_t len = strlen(kssl_ctx->client_princ);
if (len < SSL_MAX_KRB5_PRINCIPAL_LENGTH) {
s->session->krb5_client_princ_len = len;
memcpy(s->session->krb5_client_princ, kssl_ctx->client_princ,
len);
}
}
/*- Was doing kssl_ctx_free() here,
* but it caused problems for apache.
* kssl_ctx = kssl_ctx_free(kssl_ctx);
* if (s->kssl_ctx) s->kssl_ctx = NULL;
*/
kclean:
OPENSSL_cleanse(pms, sizeof(pms));
if (kerr)
goto err;
} else
#endif /* OPENSSL_NO_KRB5 */
#ifndef OPENSSL_NO_ECDH
if (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)) {
int ret = 1;
int field_size = 0;
const EC_KEY *tkey;
const EC_GROUP *group;
const BIGNUM *priv_key;
/* initialize structures for server's ECDH key pair */
if ((srvr_ecdh = EC_KEY_new()) == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto err;
}
/* Let's get server private key and group information */
if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
/* use the certificate */
tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
} else {
/*
* use the ephermeral values we saved when generating the
* ServerKeyExchange msg.
*/
tkey = s->s3->tmp.ecdh;
}
group = EC_KEY_get0_group(tkey);
priv_key = EC_KEY_get0_private_key(tkey);
if (!EC_KEY_set_group(srvr_ecdh, group) ||
!EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
goto err;
}
/* Let's get client's public key */
if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto err;
}
if (n == 0L) {
/* Client Publickey was in Client Certificate */
if (alg_k & SSL_kEECDH) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_TMP_ECDH_KEY);
goto f_err;
}
if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
== NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
/*
* XXX: For now, we do not support client authentication
* using ECDH certificates so this branch (n == 0L) of the
* code is never executed. When that support is added, we
* ought to ensure the key received in the certificate is
* authorized for key agreement. ECDH_compute_key implicitly
* checks that the two ECDH shares are for the same group.
*/
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
goto f_err;
}
if (EC_POINT_copy(clnt_ecpoint,
EC_KEY_get0_public_key(clnt_pub_pkey->
pkey.ec)) == 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
goto err;
}
ret = 2; /* Skip certificate verify processing */
} else {
/*
* Get client's public key from encoded point in the
* ClientKeyExchange message.
*/
if ((bn_ctx = BN_CTX_new()) == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
ERR_R_MALLOC_FAILURE);
goto err;
}
/* Get encoded point length */
i = *p;
p += 1;
if (n != 1 + i) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
goto err;
}
if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
goto err;
}
/*
* p is pointing to somewhere in the buffer currently, so set it
* to the start
*/
p = (unsigned char *)s->init_buf->data;
}
/* Compute the shared pre-master secret */
field_size = EC_GROUP_get_degree(group);
if (field_size <= 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
goto err;
}
i = ECDH_compute_key(p, (field_size + 7) / 8, clnt_ecpoint, srvr_ecdh,
NULL);
if (i <= 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
goto err;
}
EVP_PKEY_free(clnt_pub_pkey);
EC_POINT_free(clnt_ecpoint);
EC_KEY_free(srvr_ecdh);
BN_CTX_free(bn_ctx);
EC_KEY_free(s->s3->tmp.ecdh);
s->s3->tmp.ecdh = NULL;
/* Compute the master secret */
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
p, i);
OPENSSL_cleanse(p, i);
return (ret);
} else
#endif
#ifndef OPENSSL_NO_PSK
if (alg_k & SSL_kPSK) {
unsigned char *t = NULL;
unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4];
unsigned int pre_ms_len = 0, psk_len = 0;
int psk_err = 1;
char tmp_id[PSK_MAX_IDENTITY_LEN + 1];
al = SSL_AD_HANDSHAKE_FAILURE;
n2s(p, i);
if (n != i + 2) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
goto psk_err;
}
if (i > PSK_MAX_IDENTITY_LEN) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto psk_err;
}
if (s->psk_server_callback == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_PSK_NO_SERVER_CB);
goto psk_err;
}
/*
* Create guaranteed NULL-terminated identity string for the callback
*/
memcpy(tmp_id, p, i);
memset(tmp_id + i, 0, PSK_MAX_IDENTITY_LEN + 1 - i);
psk_len = s->psk_server_callback(s, tmp_id,
psk_or_pre_ms,
sizeof(psk_or_pre_ms));
OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN + 1);
if (psk_len > PSK_MAX_PSK_LEN) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
goto psk_err;
} else if (psk_len == 0) {
/*
* PSK related to the given identity not found
*/
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_PSK_IDENTITY_NOT_FOUND);
al = SSL_AD_UNKNOWN_PSK_IDENTITY;
goto psk_err;
}
/* create PSK pre_master_secret */
pre_ms_len = 2 + psk_len + 2 + psk_len;
t = psk_or_pre_ms;
memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len);
s2n(psk_len, t);
memset(t, 0, psk_len);
t += psk_len;
s2n(psk_len, t);
if (s->session->psk_identity != NULL)
OPENSSL_free(s->session->psk_identity);
s->session->psk_identity = BUF_strndup((char *)p, i);
if (s->session->psk_identity == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto psk_err;
}
if (s->session->psk_identity_hint != NULL)
OPENSSL_free(s->session->psk_identity_hint);
s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
if (s->ctx->psk_identity_hint != NULL &&
s->session->psk_identity_hint == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto psk_err;
}
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
psk_or_pre_ms,
pre_ms_len);
psk_err = 0;
psk_err:
OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
if (psk_err != 0)
goto f_err;
} else
#endif
#ifndef OPENSSL_NO_SRP
if (alg_k & SSL_kSRP) {
int param_len;
n2s(p, i);
param_len = i + 2;
if (param_len > n) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_BAD_SRP_A_LENGTH);
goto f_err;
}
if (!(s->srp_ctx.A = BN_bin2bn(p, i, NULL))) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
goto err;
}
if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
|| BN_is_zero(s->srp_ctx.A)) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_BAD_SRP_PARAMETERS);
goto f_err;
}
if (s->session->srp_username != NULL)
OPENSSL_free(s->session->srp_username);
s->session->srp_username = BUF_strdup(s->srp_ctx.login);
if (s->session->srp_username == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto err;
}
if ((s->session->master_key_length =
SRP_generate_server_master_secret(s,
s->session->master_key)) < 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
goto err;
}
p += i;
} else
#endif /* OPENSSL_NO_SRP */
if (alg_k & SSL_kGOST) {
int ret = 0;
EVP_PKEY_CTX *pkey_ctx;
EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
unsigned char premaster_secret[32], *start;
size_t outlen = 32, inlen;
unsigned long alg_a;
int Ttag, Tclass;
long Tlen;
/* Get our certificate private key */
alg_a = s->s3->tmp.new_cipher->algorithm_auth;
if (alg_a & SSL_aGOST94)
pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
else if (alg_a & SSL_aGOST01)
pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
EVP_PKEY_decrypt_init(pkey_ctx);
/*
* If client certificate is present and is of the same type, maybe
* use it for key exchange. Don't mind errors from
* EVP_PKEY_derive_set_peer, because it is completely valid to use a
* client certificate for authorization only.
*/
client_pub_pkey = X509_get_pubkey(s->session->peer);
if (client_pub_pkey) {
if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
ERR_clear_error();
}
/* Decrypt session key */
if (ASN1_get_object
((const unsigned char **)&p, &Tlen, &Ttag, &Tclass,
n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE
|| Tclass != V_ASN1_UNIVERSAL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DECRYPTION_FAILED);
goto gerr;
}
start = p;
inlen = Tlen;
if (EVP_PKEY_decrypt
(pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DECRYPTION_FAILED);
goto gerr;
}
/* Generate master secret */
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
premaster_secret, 32);
OPENSSL_cleanse(premaster_secret, sizeof(premaster_secret));
/* Check if pubkey from client certificate was used */
if (EVP_PKEY_CTX_ctrl
(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
ret = 2;
else
ret = 1;
gerr:
EVP_PKEY_free(client_pub_pkey);
EVP_PKEY_CTX_free(pkey_ctx);
if (ret)
return ret;
else
goto err;
} else {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
goto f_err;
}
return (1);
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
#if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
err:
#endif
#ifndef OPENSSL_NO_ECDH
EVP_PKEY_free(clnt_pub_pkey);
EC_POINT_free(clnt_ecpoint);
if (srvr_ecdh != NULL)
EC_KEY_free(srvr_ecdh);
BN_CTX_free(bn_ctx);
#endif
s->state = SSL_ST_ERR;
return (-1);
}
| 164,717 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static enum AVPixelFormat h263_get_format(AVCodecContext *avctx)
{
/* MPEG-4 Studio Profile only, not supported by hardware */
if (avctx->bits_per_raw_sample > 8) {
av_assert1(avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO);
return avctx->pix_fmt;
}
if (avctx->codec->id == AV_CODEC_ID_MSS2)
return AV_PIX_FMT_YUV420P;
if (CONFIG_GRAY && (avctx->flags & AV_CODEC_FLAG_GRAY)) {
if (avctx->color_range == AVCOL_RANGE_UNSPECIFIED)
avctx->color_range = AVCOL_RANGE_MPEG;
return AV_PIX_FMT_GRAY8;
}
return avctx->pix_fmt = ff_get_format(avctx, avctx->codec->pix_fmts);
}
Commit Message: avcodec/mpeg4videodec: Remove use of FF_PROFILE_MPEG4_SIMPLE_STUDIO as indicator of studio profile
The profile field is changed by code inside and outside the decoder,
its not a reliable indicator of the internal codec state.
Maintaining it consistency with studio_profile is messy.
Its easier to just avoid it and use only studio_profile
Fixes: assertion failure
Fixes: ffmpeg_crash_9.avi
Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-617 | static enum AVPixelFormat h263_get_format(AVCodecContext *avctx)
{
MpegEncContext *s = avctx->priv_data;
/* MPEG-4 Studio Profile only, not supported by hardware */
if (avctx->bits_per_raw_sample > 8) {
av_assert1(s->studio_profile);
return avctx->pix_fmt;
}
if (avctx->codec->id == AV_CODEC_ID_MSS2)
return AV_PIX_FMT_YUV420P;
if (CONFIG_GRAY && (avctx->flags & AV_CODEC_FLAG_GRAY)) {
if (avctx->color_range == AVCOL_RANGE_UNSPECIFIED)
avctx->color_range = AVCOL_RANGE_MPEG;
return AV_PIX_FMT_GRAY8;
}
return avctx->pix_fmt = ff_get_format(avctx, avctx->codec->pix_fmts);
}
| 169,156 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: standard_row_validate(standard_display *dp, png_const_structp pp,
int iImage, int iDisplay, png_uint_32 y)
{
int where;
png_byte std[STANDARD_ROWMAX];
/* The row must be pre-initialized to the magic number here for the size
* tests to pass:
*/
memset(std, 178, sizeof std);
standard_row(pp, std, dp->id, y);
/* At the end both the 'row' and 'display' arrays should end up identical.
* In earlier passes 'row' will be partially filled in, with only the pixels
* that have been read so far, but 'display' will have those pixels
* replicated to fill the unread pixels while reading an interlaced image.
#if PNG_LIBPNG_VER < 10506
* The side effect inside the libpng sequential reader is that the 'row'
* array retains the correct values for unwritten pixels within the row
* bytes, while the 'display' array gets bits off the end of the image (in
* the last byte) trashed. Unfortunately in the progressive reader the
* row bytes are always trashed, so we always do a pixel_cmp here even though
* a memcmp of all cbRow bytes will succeed for the sequential reader.
#endif
*/
if (iImage >= 0 &&
(where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y),
dp->bit_width)) != 0)
{
char msg[64];
sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x",
(unsigned long)y, where-1, std[where-1],
store_image_row(dp->ps, pp, iImage, y)[where-1]);
png_error(pp, msg);
}
#if PNG_LIBPNG_VER < 10506
/* In this case use pixel_cmp because we need to compare a partial
* byte at the end of the row if the row is not an exact multiple
* of 8 bits wide. (This is fixed in libpng-1.5.6 and pixel_cmp is
* changed to match!)
*/
#endif
if (iDisplay >= 0 &&
(where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y),
dp->bit_width)) != 0)
{
char msg[64];
sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x",
(unsigned long)y, where-1, std[where-1],
store_image_row(dp->ps, pp, iDisplay, y)[where-1]);
png_error(pp, msg);
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | standard_row_validate(standard_display *dp, png_const_structp pp,
int iImage, int iDisplay, png_uint_32 y)
{
int where;
png_byte std[STANDARD_ROWMAX];
/* The row must be pre-initialized to the magic number here for the size
* tests to pass:
*/
memset(std, 178, sizeof std);
standard_row(pp, std, dp->id, y);
/* At the end both the 'row' and 'display' arrays should end up identical.
* In earlier passes 'row' will be partially filled in, with only the pixels
* that have been read so far, but 'display' will have those pixels
* replicated to fill the unread pixels while reading an interlaced image.
*/
if (iImage >= 0 &&
(where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y),
dp->bit_width)) != 0)
{
char msg[64];
sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x",
(unsigned long)y, where-1, std[where-1],
store_image_row(dp->ps, pp, iImage, y)[where-1]);
png_error(pp, msg);
}
if (iDisplay >= 0 &&
(where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y),
dp->bit_width)) != 0)
{
char msg[64];
sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x",
(unsigned long)y, where-1, std[where-1],
store_image_row(dp->ps, pp, iDisplay, y)[where-1]);
png_error(pp, msg);
}
}
| 173,701 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ip_optprint(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int option_len;
const char *sep = "";
for (; length > 0; cp += option_len, length -= option_len) {
u_int option_code;
ND_PRINT((ndo, "%s", sep));
sep = ",";
ND_TCHECK(*cp);
option_code = *cp;
ND_PRINT((ndo, "%s",
tok2str(ip_option_values,"unknown %u",option_code)));
if (option_code == IPOPT_NOP ||
option_code == IPOPT_EOL)
option_len = 1;
else {
ND_TCHECK(cp[1]);
option_len = cp[1];
if (option_len < 2) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
}
if (option_len > length) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
ND_TCHECK2(*cp, option_len);
switch (option_code) {
case IPOPT_EOL:
return;
case IPOPT_TS:
ip_printts(ndo, cp, option_len);
break;
case IPOPT_RR: /* fall through */
case IPOPT_SSRR:
case IPOPT_LSRR:
ip_printroute(ndo, cp, option_len);
break;
case IPOPT_RA:
if (option_len < 4) {
ND_PRINT((ndo, " [bad length %u]", option_len));
break;
}
ND_TCHECK(cp[3]);
if (EXTRACT_16BITS(&cp[2]) != 0)
ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2])));
break;
case IPOPT_NOP: /* nothing to print - fall through */
case IPOPT_SECURITY:
default:
break;
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
Commit Message: CVE-2017-13022/IP: Add bounds checks to ip_printroute().
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125 | ip_optprint(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int option_len;
const char *sep = "";
for (; length > 0; cp += option_len, length -= option_len) {
u_int option_code;
ND_PRINT((ndo, "%s", sep));
sep = ",";
ND_TCHECK(*cp);
option_code = *cp;
ND_PRINT((ndo, "%s",
tok2str(ip_option_values,"unknown %u",option_code)));
if (option_code == IPOPT_NOP ||
option_code == IPOPT_EOL)
option_len = 1;
else {
ND_TCHECK(cp[1]);
option_len = cp[1];
if (option_len < 2) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
}
if (option_len > length) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
ND_TCHECK2(*cp, option_len);
switch (option_code) {
case IPOPT_EOL:
return;
case IPOPT_TS:
ip_printts(ndo, cp, option_len);
break;
case IPOPT_RR: /* fall through */
case IPOPT_SSRR:
case IPOPT_LSRR:
if (ip_printroute(ndo, cp, option_len) == -1)
goto trunc;
break;
case IPOPT_RA:
if (option_len < 4) {
ND_PRINT((ndo, " [bad length %u]", option_len));
break;
}
ND_TCHECK(cp[3]);
if (EXTRACT_16BITS(&cp[2]) != 0)
ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2])));
break;
case IPOPT_NOP: /* nothing to print - fall through */
case IPOPT_SECURITY:
default:
break;
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| 167,869 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WorkerFetchContext::DispatchDidBlockRequest(
const ResourceRequest& resource_request,
const FetchInitiatorInfo& fetch_initiator_info,
ResourceRequestBlockedReason blocked_reason) const {
probe::didBlockRequest(global_scope_, resource_request, nullptr,
fetch_initiator_info, blocked_reason);
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Andrey Lushnikov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119 | void WorkerFetchContext::DispatchDidBlockRequest(
const ResourceRequest& resource_request,
const FetchInitiatorInfo& fetch_initiator_info,
ResourceRequestBlockedReason blocked_reason,
Resource::Type resource_type) const {
probe::didBlockRequest(global_scope_, resource_request, nullptr,
fetch_initiator_info, blocked_reason, resource_type);
}
| 172,475 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: juniper_services_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
struct juniper_services_header {
uint8_t svc_id;
uint8_t flags_len;
uint8_t svc_set_id[2];
uint8_t dir_iif[4];
};
const struct juniper_services_header *sh;
l2info.pictype = DLT_JUNIPER_SERVICES;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
sh = (const struct juniper_services_header *)p;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "service-id %u flags 0x%02x service-set-id 0x%04x iif %u: ",
sh->svc_id,
sh->flags_len,
EXTRACT_16BITS(&sh->svc_set_id),
EXTRACT_24BITS(&sh->dir_iif[1])));
/* no proto field - lets guess by first byte of IP header*/
ip_heuristic_guess (ndo, p, l2info.length);
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_services_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
struct juniper_services_header {
uint8_t svc_id;
uint8_t flags_len;
uint8_t svc_set_id[2];
uint8_t dir_iif[4];
};
const struct juniper_services_header *sh;
l2info.pictype = DLT_JUNIPER_SERVICES;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
sh = (const struct juniper_services_header *)p;
ND_TCHECK(*sh);
if (ndo->ndo_eflag)
ND_PRINT((ndo, "service-id %u flags 0x%02x service-set-id 0x%04x iif %u: ",
sh->svc_id,
sh->flags_len,
EXTRACT_16BITS(&sh->svc_set_id),
EXTRACT_24BITS(&sh->dir_iif[1])));
/* no proto field - lets guess by first byte of IP header*/
ip_heuristic_guess (ndo, p, l2info.length);
return l2info.header_len;
trunc:
ND_PRINT((ndo, "[|juniper_services]"));
return l2info.header_len;
}
| 167,921 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id,
double file_gamma, double screen_gamma, png_byte sbit, int threshold_test,
int use_input_precision, int scale16, int expand16,
int do_background, PNG_CONST png_color_16 *pointer_to_the_background_color,
double background_gamma)
{
/* Standard fields */
standard_display_init(&dp->this, &pm->this, id, 0/*do_interlace*/,
pm->use_update_info);
/* Parameter fields */
dp->pm = pm;
dp->file_gamma = file_gamma;
dp->screen_gamma = screen_gamma;
dp->background_gamma = background_gamma;
dp->sbit = sbit;
dp->threshold_test = threshold_test;
dp->use_input_precision = use_input_precision;
dp->scale16 = scale16;
dp->expand16 = expand16;
dp->do_background = do_background;
if (do_background && pointer_to_the_background_color != 0)
dp->background_color = *pointer_to_the_background_color;
else
memset(&dp->background_color, 0, sizeof dp->background_color);
/* Local variable fields */
dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id,
double file_gamma, double screen_gamma, png_byte sbit, int threshold_test,
int use_input_precision, int scale16, int expand16,
int do_background, const png_color_16 *pointer_to_the_background_color,
double background_gamma)
{
/* Standard fields */
standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
pm->use_update_info);
/* Parameter fields */
dp->pm = pm;
dp->file_gamma = file_gamma;
dp->screen_gamma = screen_gamma;
dp->background_gamma = background_gamma;
dp->sbit = sbit;
dp->threshold_test = threshold_test;
dp->use_input_precision = use_input_precision;
dp->scale16 = scale16;
dp->expand16 = expand16;
dp->do_background = do_background;
if (do_background && pointer_to_the_background_color != 0)
dp->background_color = *pointer_to_the_background_color;
else
memset(&dp->background_color, 0, sizeof dp->background_color);
/* Local variable fields */
dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0;
}
| 173,611 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void mp_encode_lua_table_as_map(lua_State *L, mp_buf *buf, int level) {
size_t len = 0;
/* First step: count keys into table. No other way to do it with the
* Lua API, we need to iterate a first time. Note that an alternative
* would be to do a single run, and then hack the buffer to insert the
* map opcodes for message pack. Too hackish for this lib. */
lua_pushnil(L);
while(lua_next(L,-2)) {
lua_pop(L,1); /* remove value, keep key for next iteration. */
len++;
}
/* Step two: actually encoding of the map. */
mp_encode_map(L,buf,len);
lua_pushnil(L);
while(lua_next(L,-2)) {
/* Stack: ... key value */
lua_pushvalue(L,-2); /* Stack: ... key value key */
mp_encode_lua_type(L,buf,level+1); /* encode key */
mp_encode_lua_type(L,buf,level+1); /* encode val */
}
}
Commit Message: Security: more cmsgpack fixes by @soloestoy.
@soloestoy sent me this additional fixes, after searching for similar
problems to the one reported in mp_pack(). I'm committing the changes
because it was not possible during to make a public PR to protect Redis
users and give Redis providers some time to patch their systems.
CWE ID: CWE-119 | void mp_encode_lua_table_as_map(lua_State *L, mp_buf *buf, int level) {
size_t len = 0;
/* First step: count keys into table. No other way to do it with the
* Lua API, we need to iterate a first time. Note that an alternative
* would be to do a single run, and then hack the buffer to insert the
* map opcodes for message pack. Too hackish for this lib. */
luaL_checkstack(L, 3, "in function mp_encode_lua_table_as_map");
lua_pushnil(L);
while(lua_next(L,-2)) {
lua_pop(L,1); /* remove value, keep key for next iteration. */
len++;
}
/* Step two: actually encoding of the map. */
mp_encode_map(L,buf,len);
lua_pushnil(L);
while(lua_next(L,-2)) {
/* Stack: ... key value */
lua_pushvalue(L,-2); /* Stack: ... key value key */
mp_encode_lua_type(L,buf,level+1); /* encode key */
mp_encode_lua_type(L,buf,level+1); /* encode val */
}
}
| 169,240 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: juniper_parse_header(netdissect_options *ndo,
const u_char *p, const struct pcap_pkthdr *h, struct juniper_l2info_t *l2info)
{
const struct juniper_cookie_table_t *lp = juniper_cookie_table;
u_int idx, jnx_ext_len, jnx_header_len = 0;
uint8_t tlv_type,tlv_len;
uint32_t control_word;
int tlv_value;
const u_char *tptr;
l2info->header_len = 0;
l2info->cookie_len = 0;
l2info->proto = 0;
l2info->length = h->len;
l2info->caplen = h->caplen;
ND_TCHECK2(p[0], 4);
l2info->flags = p[3];
l2info->direction = p[3]&JUNIPER_BPF_PKT_IN;
if (EXTRACT_24BITS(p) != JUNIPER_MGC_NUMBER) { /* magic number found ? */
ND_PRINT((ndo, "no magic-number found!"));
return 0;
}
if (ndo->ndo_eflag) /* print direction */
ND_PRINT((ndo, "%3s ", tok2str(juniper_direction_values, "---", l2info->direction)));
/* magic number + flags */
jnx_header_len = 4;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\tJuniper PCAP Flags [%s]",
bittok2str(jnx_flag_values, "none", l2info->flags)));
/* extensions present ? - calculate how much bytes to skip */
if ((l2info->flags & JUNIPER_BPF_EXT ) == JUNIPER_BPF_EXT ) {
tptr = p+jnx_header_len;
/* ok to read extension length ? */
ND_TCHECK2(tptr[0], 2);
jnx_ext_len = EXTRACT_16BITS(tptr);
jnx_header_len += 2;
tptr +=2;
/* nail up the total length -
* just in case something goes wrong
* with TLV parsing */
jnx_header_len += jnx_ext_len;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, ", PCAP Extension(s) total length %u", jnx_ext_len));
ND_TCHECK2(tptr[0], jnx_ext_len);
while (jnx_ext_len > JUNIPER_EXT_TLV_OVERHEAD) {
tlv_type = *(tptr++);
tlv_len = *(tptr++);
tlv_value = 0;
/* sanity checks */
if (tlv_type == 0 || tlv_len == 0)
break;
if (tlv_len+JUNIPER_EXT_TLV_OVERHEAD > jnx_ext_len)
goto trunc;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t %s Extension TLV #%u, length %u, value ",
tok2str(jnx_ext_tlv_values,"Unknown",tlv_type),
tlv_type,
tlv_len));
tlv_value = juniper_read_tlv_value(tptr, tlv_type, tlv_len);
switch (tlv_type) {
case JUNIPER_EXT_TLV_IFD_NAME:
/* FIXME */
break;
case JUNIPER_EXT_TLV_IFD_MEDIATYPE:
case JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%s (%u)",
tok2str(juniper_ifmt_values, "Unknown", tlv_value),
tlv_value));
}
break;
case JUNIPER_EXT_TLV_IFL_ENCAPS:
case JUNIPER_EXT_TLV_TTP_IFL_ENCAPS:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%s (%u)",
tok2str(juniper_ifle_values, "Unknown", tlv_value),
tlv_value));
}
break;
case JUNIPER_EXT_TLV_IFL_IDX: /* fall through */
case JUNIPER_EXT_TLV_IFL_UNIT:
case JUNIPER_EXT_TLV_IFD_IDX:
default:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%u", tlv_value));
}
break;
}
tptr+=tlv_len;
jnx_ext_len -= tlv_len+JUNIPER_EXT_TLV_OVERHEAD;
}
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t-----original packet-----\n\t"));
}
if ((l2info->flags & JUNIPER_BPF_NO_L2 ) == JUNIPER_BPF_NO_L2 ) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "no-L2-hdr, "));
/* there is no link-layer present -
* perform the v4/v6 heuristics
* to figure out what it is
*/
ND_TCHECK2(p[jnx_header_len + 4], 1);
if (ip_heuristic_guess(ndo, p + jnx_header_len + 4,
l2info->length - (jnx_header_len + 4)) == 0)
ND_PRINT((ndo, "no IP-hdr found!"));
l2info->header_len=jnx_header_len+4;
return 0; /* stop parsing the output further */
}
l2info->header_len = jnx_header_len;
p+=l2info->header_len;
l2info->length -= l2info->header_len;
l2info->caplen -= l2info->header_len;
/* search through the cookie table and copy values matching for our PIC type */
while (lp->s != NULL) {
if (lp->pictype == l2info->pictype) {
l2info->cookie_len += lp->cookie_len;
switch (p[0]) {
case LS_COOKIE_ID:
l2info->cookie_type = LS_COOKIE_ID;
l2info->cookie_len += 2;
break;
case AS_COOKIE_ID:
l2info->cookie_type = AS_COOKIE_ID;
l2info->cookie_len = 8;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
#ifdef DLT_JUNIPER_MFR
/* MFR child links don't carry cookies */
if (l2info->pictype == DLT_JUNIPER_MFR &&
(p[0] & MFR_BE_MASK) == MFR_BE_MASK) {
l2info->cookie_len = 0;
}
#endif
l2info->header_len += l2info->cookie_len;
l2info->length -= l2info->cookie_len;
l2info->caplen -= l2info->cookie_len;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%s-PIC, cookie-len %u",
lp->s,
l2info->cookie_len));
if (l2info->cookie_len > 0) {
ND_TCHECK2(p[0], l2info->cookie_len);
if (ndo->ndo_eflag)
ND_PRINT((ndo, ", cookie 0x"));
for (idx = 0; idx < l2info->cookie_len; idx++) {
l2info->cookie[idx] = p[idx]; /* copy cookie data */
if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x", p[idx]));
}
}
if (ndo->ndo_eflag) ND_PRINT((ndo, ": ")); /* print demarc b/w L2/L3*/
l2info->proto = EXTRACT_16BITS(p+l2info->cookie_len);
break;
}
++lp;
}
p+=l2info->cookie_len;
/* DLT_ specific parsing */
switch(l2info->pictype) {
#ifdef DLT_JUNIPER_MLPPP
case DLT_JUNIPER_MLPPP:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
l2info->bundle = l2info->cookie[1];
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
break;
#endif
#ifdef DLT_JUNIPER_MLFR
case DLT_JUNIPER_MLFR:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
l2info->bundle = l2info->cookie[1];
l2info->proto = EXTRACT_16BITS(p);
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
}
break;
#endif
#ifdef DLT_JUNIPER_MFR
case DLT_JUNIPER_MFR:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
l2info->bundle = l2info->cookie[1];
l2info->proto = EXTRACT_16BITS(p);
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
break;
#endif
#ifdef DLT_JUNIPER_ATM2
case DLT_JUNIPER_ATM2:
ND_TCHECK2(p[0], 4);
/* ATM cell relay control word present ? */
if (l2info->cookie[7] & ATM2_PKT_TYPE_MASK) {
control_word = EXTRACT_32BITS(p);
/* some control word heuristics */
switch(control_word) {
case 0: /* zero control word */
case 0x08000000: /* < JUNOS 7.4 control-word */
case 0x08380000: /* cntl word plus cell length (56) >= JUNOS 7.4*/
l2info->header_len += 4;
break;
default:
break;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "control-word 0x%08x ", control_word));
}
break;
#endif
#ifdef DLT_JUNIPER_GGSN
case DLT_JUNIPER_GGSN:
break;
#endif
#ifdef DLT_JUNIPER_ATM1
case DLT_JUNIPER_ATM1:
break;
#endif
#ifdef DLT_JUNIPER_PPP
case DLT_JUNIPER_PPP:
break;
#endif
#ifdef DLT_JUNIPER_CHDLC
case DLT_JUNIPER_CHDLC:
break;
#endif
#ifdef DLT_JUNIPER_ETHER
case DLT_JUNIPER_ETHER:
break;
#endif
#ifdef DLT_JUNIPER_FRELAY
case DLT_JUNIPER_FRELAY:
break;
#endif
default:
ND_PRINT((ndo, "Unknown Juniper DLT_ type %u: ", l2info->pictype));
break;
}
if (ndo->ndo_eflag > 1)
ND_PRINT((ndo, "hlen %u, proto 0x%04x, ", l2info->header_len, l2info->proto));
return 1; /* everything went ok so far. continue parsing */
trunc:
ND_PRINT((ndo, "[|juniper_hdr], length %u", h->len));
return 0;
}
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_parse_header(netdissect_options *ndo,
const u_char *p, const struct pcap_pkthdr *h, struct juniper_l2info_t *l2info)
{
const struct juniper_cookie_table_t *lp = juniper_cookie_table;
u_int idx, jnx_ext_len, jnx_header_len = 0;
uint8_t tlv_type,tlv_len;
uint32_t control_word;
int tlv_value;
const u_char *tptr;
l2info->header_len = 0;
l2info->cookie_len = 0;
l2info->proto = 0;
l2info->length = h->len;
l2info->caplen = h->caplen;
ND_TCHECK2(p[0], 4);
l2info->flags = p[3];
l2info->direction = p[3]&JUNIPER_BPF_PKT_IN;
if (EXTRACT_24BITS(p) != JUNIPER_MGC_NUMBER) { /* magic number found ? */
ND_PRINT((ndo, "no magic-number found!"));
return 0;
}
if (ndo->ndo_eflag) /* print direction */
ND_PRINT((ndo, "%3s ", tok2str(juniper_direction_values, "---", l2info->direction)));
/* magic number + flags */
jnx_header_len = 4;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\tJuniper PCAP Flags [%s]",
bittok2str(jnx_flag_values, "none", l2info->flags)));
/* extensions present ? - calculate how much bytes to skip */
if ((l2info->flags & JUNIPER_BPF_EXT ) == JUNIPER_BPF_EXT ) {
tptr = p+jnx_header_len;
/* ok to read extension length ? */
ND_TCHECK2(tptr[0], 2);
jnx_ext_len = EXTRACT_16BITS(tptr);
jnx_header_len += 2;
tptr +=2;
/* nail up the total length -
* just in case something goes wrong
* with TLV parsing */
jnx_header_len += jnx_ext_len;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, ", PCAP Extension(s) total length %u", jnx_ext_len));
ND_TCHECK2(tptr[0], jnx_ext_len);
while (jnx_ext_len > JUNIPER_EXT_TLV_OVERHEAD) {
tlv_type = *(tptr++);
tlv_len = *(tptr++);
tlv_value = 0;
/* sanity checks */
if (tlv_type == 0 || tlv_len == 0)
break;
if (tlv_len+JUNIPER_EXT_TLV_OVERHEAD > jnx_ext_len)
goto trunc;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t %s Extension TLV #%u, length %u, value ",
tok2str(jnx_ext_tlv_values,"Unknown",tlv_type),
tlv_type,
tlv_len));
tlv_value = juniper_read_tlv_value(tptr, tlv_type, tlv_len);
switch (tlv_type) {
case JUNIPER_EXT_TLV_IFD_NAME:
/* FIXME */
break;
case JUNIPER_EXT_TLV_IFD_MEDIATYPE:
case JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%s (%u)",
tok2str(juniper_ifmt_values, "Unknown", tlv_value),
tlv_value));
}
break;
case JUNIPER_EXT_TLV_IFL_ENCAPS:
case JUNIPER_EXT_TLV_TTP_IFL_ENCAPS:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%s (%u)",
tok2str(juniper_ifle_values, "Unknown", tlv_value),
tlv_value));
}
break;
case JUNIPER_EXT_TLV_IFL_IDX: /* fall through */
case JUNIPER_EXT_TLV_IFL_UNIT:
case JUNIPER_EXT_TLV_IFD_IDX:
default:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%u", tlv_value));
}
break;
}
tptr+=tlv_len;
jnx_ext_len -= tlv_len+JUNIPER_EXT_TLV_OVERHEAD;
}
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t-----original packet-----\n\t"));
}
if ((l2info->flags & JUNIPER_BPF_NO_L2 ) == JUNIPER_BPF_NO_L2 ) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "no-L2-hdr, "));
/* there is no link-layer present -
* perform the v4/v6 heuristics
* to figure out what it is
*/
ND_TCHECK2(p[jnx_header_len + 4], 1);
if (ip_heuristic_guess(ndo, p + jnx_header_len + 4,
l2info->length - (jnx_header_len + 4)) == 0)
ND_PRINT((ndo, "no IP-hdr found!"));
l2info->header_len=jnx_header_len+4;
return 0; /* stop parsing the output further */
}
l2info->header_len = jnx_header_len;
p+=l2info->header_len;
l2info->length -= l2info->header_len;
l2info->caplen -= l2info->header_len;
/* search through the cookie table and copy values matching for our PIC type */
ND_TCHECK(p[0]);
while (lp->s != NULL) {
if (lp->pictype == l2info->pictype) {
l2info->cookie_len += lp->cookie_len;
switch (p[0]) {
case LS_COOKIE_ID:
l2info->cookie_type = LS_COOKIE_ID;
l2info->cookie_len += 2;
break;
case AS_COOKIE_ID:
l2info->cookie_type = AS_COOKIE_ID;
l2info->cookie_len = 8;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
#ifdef DLT_JUNIPER_MFR
/* MFR child links don't carry cookies */
if (l2info->pictype == DLT_JUNIPER_MFR &&
(p[0] & MFR_BE_MASK) == MFR_BE_MASK) {
l2info->cookie_len = 0;
}
#endif
l2info->header_len += l2info->cookie_len;
l2info->length -= l2info->cookie_len;
l2info->caplen -= l2info->cookie_len;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%s-PIC, cookie-len %u",
lp->s,
l2info->cookie_len));
if (l2info->cookie_len > 0) {
ND_TCHECK2(p[0], l2info->cookie_len);
if (ndo->ndo_eflag)
ND_PRINT((ndo, ", cookie 0x"));
for (idx = 0; idx < l2info->cookie_len; idx++) {
l2info->cookie[idx] = p[idx]; /* copy cookie data */
if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x", p[idx]));
}
}
if (ndo->ndo_eflag) ND_PRINT((ndo, ": ")); /* print demarc b/w L2/L3*/
l2info->proto = EXTRACT_16BITS(p+l2info->cookie_len);
break;
}
++lp;
}
p+=l2info->cookie_len;
/* DLT_ specific parsing */
switch(l2info->pictype) {
#ifdef DLT_JUNIPER_MLPPP
case DLT_JUNIPER_MLPPP:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
l2info->bundle = l2info->cookie[1];
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
break;
#endif
#ifdef DLT_JUNIPER_MLFR
case DLT_JUNIPER_MLFR:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
ND_TCHECK2(p[0], 2);
l2info->bundle = l2info->cookie[1];
l2info->proto = EXTRACT_16BITS(p);
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
}
break;
#endif
#ifdef DLT_JUNIPER_MFR
case DLT_JUNIPER_MFR:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
ND_TCHECK2(p[0], 2);
l2info->bundle = l2info->cookie[1];
l2info->proto = EXTRACT_16BITS(p);
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
break;
#endif
#ifdef DLT_JUNIPER_ATM2
case DLT_JUNIPER_ATM2:
ND_TCHECK2(p[0], 4);
/* ATM cell relay control word present ? */
if (l2info->cookie[7] & ATM2_PKT_TYPE_MASK) {
control_word = EXTRACT_32BITS(p);
/* some control word heuristics */
switch(control_word) {
case 0: /* zero control word */
case 0x08000000: /* < JUNOS 7.4 control-word */
case 0x08380000: /* cntl word plus cell length (56) >= JUNOS 7.4*/
l2info->header_len += 4;
break;
default:
break;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "control-word 0x%08x ", control_word));
}
break;
#endif
#ifdef DLT_JUNIPER_GGSN
case DLT_JUNIPER_GGSN:
break;
#endif
#ifdef DLT_JUNIPER_ATM1
case DLT_JUNIPER_ATM1:
break;
#endif
#ifdef DLT_JUNIPER_PPP
case DLT_JUNIPER_PPP:
break;
#endif
#ifdef DLT_JUNIPER_CHDLC
case DLT_JUNIPER_CHDLC:
break;
#endif
#ifdef DLT_JUNIPER_ETHER
case DLT_JUNIPER_ETHER:
break;
#endif
#ifdef DLT_JUNIPER_FRELAY
case DLT_JUNIPER_FRELAY:
break;
#endif
default:
ND_PRINT((ndo, "Unknown Juniper DLT_ type %u: ", l2info->pictype));
break;
}
if (ndo->ndo_eflag > 1)
ND_PRINT((ndo, "hlen %u, proto 0x%04x, ", l2info->header_len, l2info->proto));
return 1; /* everything went ok so far. continue parsing */
trunc:
ND_PRINT((ndo, "[|juniper_hdr], length %u", h->len));
return 0;
}
| 167,919 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CopyToOMX(const OMX_BUFFERHEADERTYPE *header) {
if (!mIsBackup) {
return;
}
memcpy(header->pBuffer + header->nOffset,
(const OMX_U8 *)mMem->pointer() + header->nOffset,
header->nFilledLen);
}
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 | void CopyToOMX(const OMX_BUFFERHEADERTYPE *header) {
if (!mCopyToOmx) {
return;
}
memcpy(header->pBuffer + header->nOffset,
(const OMX_U8 *)mMem->pointer() + header->nOffset,
header->nFilledLen);
}
| 174,128 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuVideoDecodeAccelerator::Initialize(
const media::VideoCodecProfile profile,
IPC::Message* init_done_msg,
base::ProcessHandle renderer_process) {
DCHECK(!video_decode_accelerator_.get());
DCHECK(!init_done_msg_);
DCHECK(init_done_msg);
init_done_msg_ = init_done_msg;
#if (defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)) || defined(OS_WIN)
DCHECK(stub_ && stub_->decoder());
#if defined(OS_WIN)
if (base::win::GetVersion() < base::win::VERSION_WIN7) {
NOTIMPLEMENTED() << "HW video decode acceleration not available.";
NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE);
return;
}
DLOG(INFO) << "Initializing DXVA HW decoder for windows.";
DXVAVideoDecodeAccelerator* video_decoder =
new DXVAVideoDecodeAccelerator(this, renderer_process);
#else // OS_WIN
OmxVideoDecodeAccelerator* video_decoder =
new OmxVideoDecodeAccelerator(this);
video_decoder->SetEglState(
gfx::GLSurfaceEGL::GetHardwareDisplay(),
stub_->decoder()->GetGLContext()->GetHandle());
#endif // OS_WIN
video_decode_accelerator_ = video_decoder;
if (!video_decode_accelerator_->Initialize(profile))
NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE);
#else // Update RenderViewImpl::createMediaPlayer when adding clauses.
NOTIMPLEMENTED() << "HW video decode acceleration not available.";
NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE);
#endif // defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)
}
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 GpuVideoDecodeAccelerator::Initialize(
const media::VideoCodecProfile profile,
IPC::Message* init_done_msg) {
DCHECK(!video_decode_accelerator_.get());
DCHECK(!init_done_msg_);
DCHECK(init_done_msg);
init_done_msg_ = init_done_msg;
#if (defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)) || defined(OS_WIN)
DCHECK(stub_ && stub_->decoder());
#if defined(OS_WIN)
if (base::win::GetVersion() < base::win::VERSION_WIN7) {
NOTIMPLEMENTED() << "HW video decode acceleration not available.";
NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE);
return;
}
DLOG(INFO) << "Initializing DXVA HW decoder for windows.";
DXVAVideoDecodeAccelerator* video_decoder =
new DXVAVideoDecodeAccelerator(this);
#else // OS_WIN
OmxVideoDecodeAccelerator* video_decoder =
new OmxVideoDecodeAccelerator(this);
video_decoder->SetEglState(
gfx::GLSurfaceEGL::GetHardwareDisplay(),
stub_->decoder()->GetGLContext()->GetHandle());
#endif // OS_WIN
video_decode_accelerator_ = video_decoder;
if (!video_decode_accelerator_->Initialize(profile))
NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE);
#else // Update RenderViewImpl::createMediaPlayer when adding clauses.
NOTIMPLEMENTED() << "HW video decode acceleration not available.";
NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE);
#endif // defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)
}
| 170,942 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: CatalogueRescan (FontPathElementPtr fpe)
{
CataloguePtr cat = fpe->private;
char link[MAXFONTFILENAMELEN];
char dest[MAXFONTFILENAMELEN];
char *attrib;
FontPathElementPtr subfpe;
struct stat statbuf;
const char *path;
DIR *dir;
struct dirent *entry;
int len;
int pathlen;
path = fpe->name + strlen(CataloguePrefix);
if (stat(path, &statbuf) < 0 || !S_ISDIR(statbuf.st_mode))
return BadFontPath;
if (statbuf.st_mtime <= cat->mtime)
return Successful;
dir = opendir(path);
if (dir == NULL)
{
xfree(cat);
return BadFontPath;
}
CatalogueUnrefFPEs (fpe);
while (entry = readdir(dir), entry != NULL)
{
snprintf(link, sizeof link, "%s/%s", path, entry->d_name);
len = readlink(link, dest, sizeof dest);
if (len < 0)
continue;
dest[len] = '\0';
if (dest[0] != '/')
{
pathlen = strlen(path);
memmove(dest + pathlen + 1, dest, sizeof dest - pathlen - 1);
memcpy(dest, path, pathlen);
memcpy(dest + pathlen, "/", 1);
len += pathlen + 1;
}
attrib = strchr(link, ':');
if (attrib && len + strlen(attrib) < sizeof dest)
{
memcpy(dest + len, attrib, strlen(attrib));
len += strlen(attrib);
}
subfpe = xalloc(sizeof *subfpe);
if (subfpe == NULL)
continue;
/* The fonts returned by OpenFont will point back to the
* subfpe they come from. So set the type of the subfpe to
* what the catalogue fpe was assigned, so calls to CloseFont
* (which uses font->fpe->type) goes to CatalogueCloseFont. */
subfpe->type = fpe->type;
subfpe->name_length = len;
subfpe->name = xalloc (len + 1);
if (subfpe == NULL)
{
xfree(subfpe);
continue;
}
memcpy(subfpe->name, dest, len);
subfpe->name[len] = '\0';
/* The X server will manipulate the subfpe ref counts
* associated with the font in OpenFont and CloseFont, so we
* have to make sure it's valid. */
subfpe->refcount = 1;
if (FontFileInitFPE (subfpe) != Successful)
{
xfree(subfpe->name);
xfree(subfpe);
continue;
}
if (CatalogueAddFPE(cat, subfpe) != Successful)
{
FontFileFreeFPE (subfpe);
xfree(subfpe);
continue;
}
}
closedir(dir);
qsort(cat->fpeList,
cat->fpeCount, sizeof cat->fpeList[0], ComparePriority);
cat->mtime = statbuf.st_mtime;
return Successful;
}
Commit Message:
CWE ID: CWE-119 | CatalogueRescan (FontPathElementPtr fpe)
{
CataloguePtr cat = fpe->private;
char link[MAXFONTFILENAMELEN];
char dest[MAXFONTFILENAMELEN];
char *attrib;
FontPathElementPtr subfpe;
struct stat statbuf;
const char *path;
DIR *dir;
struct dirent *entry;
int len;
int pathlen;
path = fpe->name + strlen(CataloguePrefix);
if (stat(path, &statbuf) < 0 || !S_ISDIR(statbuf.st_mode))
return BadFontPath;
if (statbuf.st_mtime <= cat->mtime)
return Successful;
dir = opendir(path);
if (dir == NULL)
{
xfree(cat);
return BadFontPath;
}
CatalogueUnrefFPEs (fpe);
while (entry = readdir(dir), entry != NULL)
{
snprintf(link, sizeof link, "%s/%s", path, entry->d_name);
len = readlink(link, dest, sizeof dest - 1);
if (len < 0)
continue;
dest[len] = '\0';
if (dest[0] != '/')
{
pathlen = strlen(path);
memmove(dest + pathlen + 1, dest, sizeof dest - pathlen - 1);
memcpy(dest, path, pathlen);
memcpy(dest + pathlen, "/", 1);
len += pathlen + 1;
}
attrib = strchr(link, ':');
if (attrib && len + strlen(attrib) < sizeof dest)
{
memcpy(dest + len, attrib, strlen(attrib));
len += strlen(attrib);
}
subfpe = xalloc(sizeof *subfpe);
if (subfpe == NULL)
continue;
/* The fonts returned by OpenFont will point back to the
* subfpe they come from. So set the type of the subfpe to
* what the catalogue fpe was assigned, so calls to CloseFont
* (which uses font->fpe->type) goes to CatalogueCloseFont. */
subfpe->type = fpe->type;
subfpe->name_length = len;
subfpe->name = xalloc (len + 1);
if (subfpe == NULL)
{
xfree(subfpe);
continue;
}
memcpy(subfpe->name, dest, len);
subfpe->name[len] = '\0';
/* The X server will manipulate the subfpe ref counts
* associated with the font in OpenFont and CloseFont, so we
* have to make sure it's valid. */
subfpe->refcount = 1;
if (FontFileInitFPE (subfpe) != Successful)
{
xfree(subfpe->name);
xfree(subfpe);
continue;
}
if (CatalogueAddFPE(cat, subfpe) != Successful)
{
FontFileFreeFPE (subfpe);
xfree(subfpe);
continue;
}
}
closedir(dir);
qsort(cat->fpeList,
cat->fpeCount, sizeof cat->fpeList[0], ComparePriority);
cat->mtime = statbuf.st_mtime;
return Successful;
}
| 165,425 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FrameSelection::DocumentAttached(Document* document) {
DCHECK(document);
use_secure_keyboard_entry_when_active_ = false;
selection_editor_->DocumentAttached(document);
SetContext(document);
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID: | void FrameSelection::DocumentAttached(Document* document) {
DCHECK(document);
selection_editor_->DocumentAttached(document);
SetContext(document);
}
| 171,853 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed 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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintMsg_Print_Params::Reset() {
page_size = gfx::Size();
content_size = gfx::Size();
printable_area = gfx::Rect();
margin_top = 0;
margin_left = 0;
dpi = 0;
scale_factor = 1.0f;
rasterize_pdf = false;
document_cookie = 0;
selection_only = false;
supports_alpha_blend = false;
preview_ui_id = -1;
preview_request_id = 0;
is_first_request = false;
print_scaling_option = blink::kWebPrintScalingOptionSourceSize;
print_to_pdf = false;
display_header_footer = false;
title = base::string16();
url = base::string16();
should_print_backgrounds = false;
printed_doc_type = printing::SkiaDocumentType::PDF;
}
Commit Message: DevTools: allow styling the page number element when printing over the protocol.
Bug: none
Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4
Reviewed-on: https://chromium-review.googlesource.com/809759
Commit-Queue: Pavel Feldman <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: Tom Sepez <[email protected]>
Reviewed-by: Jianzhou Feng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#523966}
CWE ID: CWE-20 | void PrintMsg_Print_Params::Reset() {
page_size = gfx::Size();
content_size = gfx::Size();
printable_area = gfx::Rect();
margin_top = 0;
margin_left = 0;
dpi = 0;
scale_factor = 1.0f;
rasterize_pdf = false;
document_cookie = 0;
selection_only = false;
supports_alpha_blend = false;
preview_ui_id = -1;
preview_request_id = 0;
is_first_request = false;
print_scaling_option = blink::kWebPrintScalingOptionSourceSize;
print_to_pdf = false;
display_header_footer = false;
title = base::string16();
url = base::string16();
header_template = base::string16();
footer_template = base::string16();
should_print_backgrounds = false;
printed_doc_type = printing::SkiaDocumentType::PDF;
}
| 172,898 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int sock_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
union {
int val;
struct linger ling;
struct timeval tm;
} v;
int lv = sizeof(int);
int len;
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
memset(&v, 0, sizeof(v));
switch (optname) {
case SO_DEBUG:
v.val = sock_flag(sk, SOCK_DBG);
break;
case SO_DONTROUTE:
v.val = sock_flag(sk, SOCK_LOCALROUTE);
break;
case SO_BROADCAST:
v.val = !!sock_flag(sk, SOCK_BROADCAST);
break;
case SO_SNDBUF:
v.val = sk->sk_sndbuf;
break;
case SO_RCVBUF:
v.val = sk->sk_rcvbuf;
break;
case SO_REUSEADDR:
v.val = sk->sk_reuse;
break;
case SO_KEEPALIVE:
v.val = !!sock_flag(sk, SOCK_KEEPOPEN);
break;
case SO_TYPE:
v.val = sk->sk_type;
break;
case SO_PROTOCOL:
v.val = sk->sk_protocol;
break;
case SO_DOMAIN:
v.val = sk->sk_family;
break;
case SO_ERROR:
v.val = -sock_error(sk);
if (v.val == 0)
v.val = xchg(&sk->sk_err_soft, 0);
break;
case SO_OOBINLINE:
v.val = !!sock_flag(sk, SOCK_URGINLINE);
break;
case SO_NO_CHECK:
v.val = sk->sk_no_check;
break;
case SO_PRIORITY:
v.val = sk->sk_priority;
break;
case SO_LINGER:
lv = sizeof(v.ling);
v.ling.l_onoff = !!sock_flag(sk, SOCK_LINGER);
v.ling.l_linger = sk->sk_lingertime / HZ;
break;
case SO_BSDCOMPAT:
sock_warn_obsolete_bsdism("getsockopt");
break;
case SO_TIMESTAMP:
v.val = sock_flag(sk, SOCK_RCVTSTAMP) &&
!sock_flag(sk, SOCK_RCVTSTAMPNS);
break;
case SO_TIMESTAMPNS:
v.val = sock_flag(sk, SOCK_RCVTSTAMPNS);
break;
case SO_TIMESTAMPING:
v.val = 0;
if (sock_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE))
v.val |= SOF_TIMESTAMPING_TX_HARDWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE))
v.val |= SOF_TIMESTAMPING_TX_SOFTWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE))
v.val |= SOF_TIMESTAMPING_RX_HARDWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_RX_SOFTWARE))
v.val |= SOF_TIMESTAMPING_RX_SOFTWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_SOFTWARE))
v.val |= SOF_TIMESTAMPING_SOFTWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE))
v.val |= SOF_TIMESTAMPING_SYS_HARDWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE))
v.val |= SOF_TIMESTAMPING_RAW_HARDWARE;
break;
case SO_RCVTIMEO:
lv = sizeof(struct timeval);
if (sk->sk_rcvtimeo == MAX_SCHEDULE_TIMEOUT) {
v.tm.tv_sec = 0;
v.tm.tv_usec = 0;
} else {
v.tm.tv_sec = sk->sk_rcvtimeo / HZ;
v.tm.tv_usec = ((sk->sk_rcvtimeo % HZ) * 1000000) / HZ;
}
break;
case SO_SNDTIMEO:
lv = sizeof(struct timeval);
if (sk->sk_sndtimeo == MAX_SCHEDULE_TIMEOUT) {
v.tm.tv_sec = 0;
v.tm.tv_usec = 0;
} else {
v.tm.tv_sec = sk->sk_sndtimeo / HZ;
v.tm.tv_usec = ((sk->sk_sndtimeo % HZ) * 1000000) / HZ;
}
break;
case SO_RCVLOWAT:
v.val = sk->sk_rcvlowat;
break;
case SO_SNDLOWAT:
v.val = 1;
break;
case SO_PASSCRED:
v.val = test_bit(SOCK_PASSCRED, &sock->flags) ? 1 : 0;
break;
case SO_PEERCRED:
{
struct ucred peercred;
if (len > sizeof(peercred))
len = sizeof(peercred);
cred_to_ucred(sk->sk_peer_pid, sk->sk_peer_cred, &peercred);
if (copy_to_user(optval, &peercred, len))
return -EFAULT;
goto lenout;
}
case SO_PEERNAME:
{
char address[128];
if (sock->ops->getname(sock, (struct sockaddr *)address, &lv, 2))
return -ENOTCONN;
if (lv < len)
return -EINVAL;
if (copy_to_user(optval, address, len))
return -EFAULT;
goto lenout;
}
/* Dubious BSD thing... Probably nobody even uses it, but
* the UNIX standard wants it for whatever reason... -DaveM
*/
case SO_ACCEPTCONN:
v.val = sk->sk_state == TCP_LISTEN;
break;
case SO_PASSSEC:
v.val = test_bit(SOCK_PASSSEC, &sock->flags) ? 1 : 0;
break;
case SO_PEERSEC:
return security_socket_getpeersec_stream(sock, optval, optlen, len);
case SO_MARK:
v.val = sk->sk_mark;
break;
case SO_RXQ_OVFL:
v.val = !!sock_flag(sk, SOCK_RXQ_OVFL);
break;
case SO_WIFI_STATUS:
v.val = !!sock_flag(sk, SOCK_WIFI_STATUS);
break;
case SO_PEEK_OFF:
if (!sock->ops->set_peek_off)
return -EOPNOTSUPP;
v.val = sk->sk_peek_off;
break;
case SO_NOFCS:
v.val = !!sock_flag(sk, SOCK_NOFCS);
break;
default:
return -ENOPROTOOPT;
}
if (len > lv)
len = lv;
if (copy_to_user(optval, &v, len))
return -EFAULT;
lenout:
if (put_user(len, optlen))
return -EFAULT;
return 0;
}
Commit Message: net: cleanups in sock_setsockopt()
Use min_t()/max_t() macros, reformat two comments, use !!test_bit() to
match !!sock_flag()
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | int sock_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
union {
int val;
struct linger ling;
struct timeval tm;
} v;
int lv = sizeof(int);
int len;
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
memset(&v, 0, sizeof(v));
switch (optname) {
case SO_DEBUG:
v.val = sock_flag(sk, SOCK_DBG);
break;
case SO_DONTROUTE:
v.val = sock_flag(sk, SOCK_LOCALROUTE);
break;
case SO_BROADCAST:
v.val = !!sock_flag(sk, SOCK_BROADCAST);
break;
case SO_SNDBUF:
v.val = sk->sk_sndbuf;
break;
case SO_RCVBUF:
v.val = sk->sk_rcvbuf;
break;
case SO_REUSEADDR:
v.val = sk->sk_reuse;
break;
case SO_KEEPALIVE:
v.val = !!sock_flag(sk, SOCK_KEEPOPEN);
break;
case SO_TYPE:
v.val = sk->sk_type;
break;
case SO_PROTOCOL:
v.val = sk->sk_protocol;
break;
case SO_DOMAIN:
v.val = sk->sk_family;
break;
case SO_ERROR:
v.val = -sock_error(sk);
if (v.val == 0)
v.val = xchg(&sk->sk_err_soft, 0);
break;
case SO_OOBINLINE:
v.val = !!sock_flag(sk, SOCK_URGINLINE);
break;
case SO_NO_CHECK:
v.val = sk->sk_no_check;
break;
case SO_PRIORITY:
v.val = sk->sk_priority;
break;
case SO_LINGER:
lv = sizeof(v.ling);
v.ling.l_onoff = !!sock_flag(sk, SOCK_LINGER);
v.ling.l_linger = sk->sk_lingertime / HZ;
break;
case SO_BSDCOMPAT:
sock_warn_obsolete_bsdism("getsockopt");
break;
case SO_TIMESTAMP:
v.val = sock_flag(sk, SOCK_RCVTSTAMP) &&
!sock_flag(sk, SOCK_RCVTSTAMPNS);
break;
case SO_TIMESTAMPNS:
v.val = sock_flag(sk, SOCK_RCVTSTAMPNS);
break;
case SO_TIMESTAMPING:
v.val = 0;
if (sock_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE))
v.val |= SOF_TIMESTAMPING_TX_HARDWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE))
v.val |= SOF_TIMESTAMPING_TX_SOFTWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE))
v.val |= SOF_TIMESTAMPING_RX_HARDWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_RX_SOFTWARE))
v.val |= SOF_TIMESTAMPING_RX_SOFTWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_SOFTWARE))
v.val |= SOF_TIMESTAMPING_SOFTWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE))
v.val |= SOF_TIMESTAMPING_SYS_HARDWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE))
v.val |= SOF_TIMESTAMPING_RAW_HARDWARE;
break;
case SO_RCVTIMEO:
lv = sizeof(struct timeval);
if (sk->sk_rcvtimeo == MAX_SCHEDULE_TIMEOUT) {
v.tm.tv_sec = 0;
v.tm.tv_usec = 0;
} else {
v.tm.tv_sec = sk->sk_rcvtimeo / HZ;
v.tm.tv_usec = ((sk->sk_rcvtimeo % HZ) * 1000000) / HZ;
}
break;
case SO_SNDTIMEO:
lv = sizeof(struct timeval);
if (sk->sk_sndtimeo == MAX_SCHEDULE_TIMEOUT) {
v.tm.tv_sec = 0;
v.tm.tv_usec = 0;
} else {
v.tm.tv_sec = sk->sk_sndtimeo / HZ;
v.tm.tv_usec = ((sk->sk_sndtimeo % HZ) * 1000000) / HZ;
}
break;
case SO_RCVLOWAT:
v.val = sk->sk_rcvlowat;
break;
case SO_SNDLOWAT:
v.val = 1;
break;
case SO_PASSCRED:
v.val = !!test_bit(SOCK_PASSCRED, &sock->flags);
break;
case SO_PEERCRED:
{
struct ucred peercred;
if (len > sizeof(peercred))
len = sizeof(peercred);
cred_to_ucred(sk->sk_peer_pid, sk->sk_peer_cred, &peercred);
if (copy_to_user(optval, &peercred, len))
return -EFAULT;
goto lenout;
}
case SO_PEERNAME:
{
char address[128];
if (sock->ops->getname(sock, (struct sockaddr *)address, &lv, 2))
return -ENOTCONN;
if (lv < len)
return -EINVAL;
if (copy_to_user(optval, address, len))
return -EFAULT;
goto lenout;
}
/* Dubious BSD thing... Probably nobody even uses it, but
* the UNIX standard wants it for whatever reason... -DaveM
*/
case SO_ACCEPTCONN:
v.val = sk->sk_state == TCP_LISTEN;
break;
case SO_PASSSEC:
v.val = !!test_bit(SOCK_PASSSEC, &sock->flags);
break;
case SO_PEERSEC:
return security_socket_getpeersec_stream(sock, optval, optlen, len);
case SO_MARK:
v.val = sk->sk_mark;
break;
case SO_RXQ_OVFL:
v.val = !!sock_flag(sk, SOCK_RXQ_OVFL);
break;
case SO_WIFI_STATUS:
v.val = !!sock_flag(sk, SOCK_WIFI_STATUS);
break;
case SO_PEEK_OFF:
if (!sock->ops->set_peek_off)
return -EOPNOTSUPP;
v.val = sk->sk_peek_off;
break;
case SO_NOFCS:
v.val = !!sock_flag(sk, SOCK_NOFCS);
break;
default:
return -ENOPROTOOPT;
}
if (len > lv)
len = lv;
if (copy_to_user(optval, &v, len))
return -EFAULT;
lenout:
if (put_user(len, optlen))
return -EFAULT;
return 0;
}
| 167,608 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PlatformSensorProviderLinux::CreateFusionSensor(
mojom::SensorType type,
mojo::ScopedSharedBufferMapping mapping,
const CreateSensorCallback& callback) {
DCHECK(IsFusionSensorType(type));
std::unique_ptr<PlatformSensorFusionAlgorithm> fusion_algorithm;
switch (type) {
case mojom::SensorType::LINEAR_ACCELERATION:
fusion_algorithm = std::make_unique<
LinearAccelerationFusionAlgorithmUsingAccelerometer>();
break;
case mojom::SensorType::RELATIVE_ORIENTATION_EULER_ANGLES:
fusion_algorithm = std::make_unique<
RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometer>();
break;
case mojom::SensorType::RELATIVE_ORIENTATION_QUATERNION:
fusion_algorithm = std::make_unique<
OrientationQuaternionFusionAlgorithmUsingEulerAngles>(
false /* absolute */);
break;
default:
NOTREACHED();
}
DCHECK(fusion_algorithm);
PlatformSensorFusion::Create(std::move(mapping), this,
std::move(fusion_algorithm), callback);
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732 | void PlatformSensorProviderLinux::CreateFusionSensor(
mojom::SensorType type,
SensorReadingSharedBuffer* reading_buffer,
const CreateSensorCallback& callback) {
DCHECK(IsFusionSensorType(type));
std::unique_ptr<PlatformSensorFusionAlgorithm> fusion_algorithm;
switch (type) {
case mojom::SensorType::LINEAR_ACCELERATION:
fusion_algorithm = std::make_unique<
LinearAccelerationFusionAlgorithmUsingAccelerometer>();
break;
case mojom::SensorType::RELATIVE_ORIENTATION_EULER_ANGLES:
fusion_algorithm = std::make_unique<
RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometer>();
break;
case mojom::SensorType::RELATIVE_ORIENTATION_QUATERNION:
fusion_algorithm = std::make_unique<
OrientationQuaternionFusionAlgorithmUsingEulerAngles>(
false /* absolute */);
break;
default:
NOTREACHED();
}
DCHECK(fusion_algorithm);
PlatformSensorFusion::Create(reading_buffer, this,
std::move(fusion_algorithm), callback);
}
| 172,842 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ContentEncoding::GetCompressionByIndex(unsigned long idx) const {
const ptrdiff_t count = compression_entries_end_ - compression_entries_;
assert(count >= 0);
if (idx >= static_cast<unsigned long>(count))
return NULL;
return compression_entries_[idx];
}
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 | ContentEncoding::GetCompressionByIndex(unsigned long idx) const {
ContentEncoding::GetCompressionByIndex(unsigned long idx) const {
const ptrdiff_t count = compression_entries_end_ - compression_entries_;
assert(count >= 0);
if (idx >= static_cast<unsigned long>(count))
return NULL;
return compression_entries_[idx];
}
| 173,815 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PrintMsg_Print_Params::PrintMsg_Print_Params()
: page_size(),
content_size(),
printable_area(),
margin_top(0),
margin_left(0),
dpi(0),
min_shrink(0),
max_shrink(0),
desired_dpi(0),
document_cookie(0),
selection_only(false),
supports_alpha_blend(false),
preview_ui_addr(),
preview_request_id(0),
is_first_request(false),
print_scaling_option(WebKit::WebPrintScalingOptionSourceSize),
print_to_pdf(false),
display_header_footer(false),
date(),
title(),
url() {
}
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 | PrintMsg_Print_Params::PrintMsg_Print_Params()
: page_size(),
content_size(),
printable_area(),
margin_top(0),
margin_left(0),
dpi(0),
min_shrink(0),
max_shrink(0),
desired_dpi(0),
document_cookie(0),
selection_only(false),
supports_alpha_blend(false),
preview_ui_id(-1),
preview_request_id(0),
is_first_request(false),
print_scaling_option(WebKit::WebPrintScalingOptionSourceSize),
print_to_pdf(false),
display_header_footer(false),
date(),
title(),
url() {
}
| 170,845 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long mkvparser::GetUIntLength(
IMkvReader* pReader,
long long pos,
long& len)
{
assert(pReader);
assert(pos >= 0);
long long total, available;
int status = pReader->Length(&total, &available);
assert(status >= 0);
assert((total < 0) || (available <= total));
len = 1;
if (pos >= available)
return pos; //too few bytes available
//// TODO(vigneshv): This function assumes that unsigned values never have their
//// high bit set.
unsigned char b;
status = pReader->Read(pos, 1, &b);
if (status < 0)
return status;
assert(status == 0);
if (b == 0) //we can't handle u-int values larger than 8 bytes
return E_FILE_FORMAT_INVALID;
unsigned char m = 0x80;
while (!(b & m))
{
m >>= 1;
++len;
}
return 0; //success
}
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 mkvparser::GetUIntLength(
long long mkvparser::GetUIntLength(IMkvReader* pReader, long long pos,
long& len) {
assert(pReader);
assert(pos >= 0);
long long total, available;
int status = pReader->Length(&total, &available);
assert(status >= 0);
assert((total < 0) || (available <= total));
len = 1;
if (pos >= available)
return pos; // too few bytes available
unsigned char b;
status = pReader->Read(pos, 1, &b);
if (status < 0)
return status;
assert(status == 0);
if (b == 0) // we can't handle u-int values larger than 8 bytes
return E_FILE_FORMAT_INVALID;
unsigned char m = 0x80;
while (!(b & m)) {
m >>= 1;
++len;
}
return 0; // success
}
//// TODO(vigneshv): This function assumes that unsigned values never have their
//// high bit set.
long long mkvparser::UnserializeUInt(IMkvReader* pReader, long long pos,
long long size) {
assert(pReader);
assert(pos >= 0);
if ((size <= 0) || (size > 8))
return E_FILE_FORMAT_INVALID;
long long result = 0;
for (long long i = 0; i < size; ++i) {
unsigned char b;
const long status = pReader->Read(pos, 1, &b);
if (status < 0)
return status;
result <<= 8;
result |= b;
++pos;
}
return result;
}
| 174,377 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool SyncManager::SyncInternal::Init(
const FilePath& database_location,
const WeakHandle<JsEventHandler>& event_handler,
const std::string& sync_server_and_path,
int port,
bool use_ssl,
const scoped_refptr<base::TaskRunner>& blocking_task_runner,
HttpPostProviderFactory* post_factory,
ModelSafeWorkerRegistrar* model_safe_worker_registrar,
browser_sync::ExtensionsActivityMonitor* extensions_activity_monitor,
ChangeDelegate* change_delegate,
const std::string& user_agent,
const SyncCredentials& credentials,
bool enable_sync_tabs_for_other_clients,
sync_notifier::SyncNotifier* sync_notifier,
const std::string& restored_key_for_bootstrapping,
TestingMode testing_mode,
Encryptor* encryptor,
UnrecoverableErrorHandler* unrecoverable_error_handler,
ReportUnrecoverableErrorFunction report_unrecoverable_error_function) {
CHECK(!initialized_);
DCHECK(thread_checker_.CalledOnValidThread());
DVLOG(1) << "Starting SyncInternal initialization.";
weak_handle_this_ = MakeWeakHandle(weak_ptr_factory_.GetWeakPtr());
blocking_task_runner_ = blocking_task_runner;
registrar_ = model_safe_worker_registrar;
change_delegate_ = change_delegate;
testing_mode_ = testing_mode;
enable_sync_tabs_for_other_clients_ = enable_sync_tabs_for_other_clients;
sync_notifier_.reset(sync_notifier);
AddObserver(&js_sync_manager_observer_);
SetJsEventHandler(event_handler);
AddObserver(&debug_info_event_listener_);
database_path_ = database_location.Append(
syncable::Directory::kSyncDatabaseFilename);
encryptor_ = encryptor;
unrecoverable_error_handler_ = unrecoverable_error_handler;
report_unrecoverable_error_function_ = report_unrecoverable_error_function;
share_.directory.reset(
new syncable::Directory(encryptor_,
unrecoverable_error_handler_,
report_unrecoverable_error_function_));
connection_manager_.reset(new SyncAPIServerConnectionManager(
sync_server_and_path, port, use_ssl, user_agent, post_factory));
net::NetworkChangeNotifier::AddIPAddressObserver(this);
observing_ip_address_changes_ = true;
connection_manager()->AddListener(this);
if (testing_mode_ == NON_TEST) {
DVLOG(1) << "Sync is bringing up SyncSessionContext.";
std::vector<SyncEngineEventListener*> listeners;
listeners.push_back(&allstatus_);
listeners.push_back(this);
SyncSessionContext* context = new SyncSessionContext(
connection_manager_.get(),
directory(),
model_safe_worker_registrar,
extensions_activity_monitor,
listeners,
&debug_info_event_listener_,
&traffic_recorder_);
context->set_account_name(credentials.email);
scheduler_.reset(new SyncScheduler(name_, context, new Syncer()));
}
bool signed_in = SignIn(credentials);
if (signed_in) {
if (scheduler()) {
scheduler()->Start(
browser_sync::SyncScheduler::CONFIGURATION_MODE, base::Closure());
}
initialized_ = true;
ReadTransaction trans(FROM_HERE, GetUserShare());
trans.GetCryptographer()->Bootstrap(restored_key_for_bootstrapping);
trans.GetCryptographer()->AddObserver(this);
}
FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
OnInitializationComplete(
MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()),
signed_in));
if (!signed_in && testing_mode_ == NON_TEST)
return false;
sync_notifier_->AddObserver(this);
return signed_in;
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | bool SyncManager::SyncInternal::Init(
const FilePath& database_location,
const WeakHandle<JsEventHandler>& event_handler,
const std::string& sync_server_and_path,
int port,
bool use_ssl,
const scoped_refptr<base::TaskRunner>& blocking_task_runner,
HttpPostProviderFactory* post_factory,
ModelSafeWorkerRegistrar* model_safe_worker_registrar,
browser_sync::ExtensionsActivityMonitor* extensions_activity_monitor,
ChangeDelegate* change_delegate,
const std::string& user_agent,
const SyncCredentials& credentials,
sync_notifier::SyncNotifier* sync_notifier,
const std::string& restored_key_for_bootstrapping,
TestingMode testing_mode,
Encryptor* encryptor,
UnrecoverableErrorHandler* unrecoverable_error_handler,
ReportUnrecoverableErrorFunction report_unrecoverable_error_function) {
CHECK(!initialized_);
DCHECK(thread_checker_.CalledOnValidThread());
DVLOG(1) << "Starting SyncInternal initialization.";
weak_handle_this_ = MakeWeakHandle(weak_ptr_factory_.GetWeakPtr());
blocking_task_runner_ = blocking_task_runner;
registrar_ = model_safe_worker_registrar;
change_delegate_ = change_delegate;
testing_mode_ = testing_mode;
sync_notifier_.reset(sync_notifier);
AddObserver(&js_sync_manager_observer_);
SetJsEventHandler(event_handler);
AddObserver(&debug_info_event_listener_);
database_path_ = database_location.Append(
syncable::Directory::kSyncDatabaseFilename);
encryptor_ = encryptor;
unrecoverable_error_handler_ = unrecoverable_error_handler;
report_unrecoverable_error_function_ = report_unrecoverable_error_function;
share_.directory.reset(
new syncable::Directory(encryptor_,
unrecoverable_error_handler_,
report_unrecoverable_error_function_));
connection_manager_.reset(new SyncAPIServerConnectionManager(
sync_server_and_path, port, use_ssl, user_agent, post_factory));
net::NetworkChangeNotifier::AddIPAddressObserver(this);
observing_ip_address_changes_ = true;
connection_manager()->AddListener(this);
if (testing_mode_ == NON_TEST) {
DVLOG(1) << "Sync is bringing up SyncSessionContext.";
std::vector<SyncEngineEventListener*> listeners;
listeners.push_back(&allstatus_);
listeners.push_back(this);
SyncSessionContext* context = new SyncSessionContext(
connection_manager_.get(),
directory(),
model_safe_worker_registrar,
extensions_activity_monitor,
listeners,
&debug_info_event_listener_,
&traffic_recorder_);
context->set_account_name(credentials.email);
scheduler_.reset(new SyncScheduler(name_, context, new Syncer()));
}
bool signed_in = SignIn(credentials);
if (signed_in) {
if (scheduler()) {
scheduler()->Start(
browser_sync::SyncScheduler::CONFIGURATION_MODE, base::Closure());
}
initialized_ = true;
ReadTransaction trans(FROM_HERE, GetUserShare());
trans.GetCryptographer()->Bootstrap(restored_key_for_bootstrapping);
trans.GetCryptographer()->AddObserver(this);
}
FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
OnInitializationComplete(
MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()),
signed_in));
if (!signed_in && testing_mode_ == NON_TEST)
return false;
sync_notifier_->AddObserver(this);
return signed_in;
}
| 170,793 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuCommandBufferStub::OnRegisterTransferBuffer(
base::SharedMemoryHandle transfer_buffer,
size_t size,
int32 id_request,
IPC::Message* reply_message) {
#if defined(OS_WIN)
base::SharedMemory shared_memory(transfer_buffer,
false,
channel_->renderer_process());
#else
#endif
if (command_buffer_.get()) {
int32 id = command_buffer_->RegisterTransferBuffer(&shared_memory,
size,
id_request);
GpuCommandBufferMsg_RegisterTransferBuffer::WriteReplyParams(reply_message,
id);
} else {
reply_message->set_reply_error();
}
Send(reply_message);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuCommandBufferStub::OnRegisterTransferBuffer(
base::SharedMemoryHandle transfer_buffer,
size_t size,
int32 id_request,
IPC::Message* reply_message) {
if (command_buffer_.get()) {
int32 id = command_buffer_->RegisterTransferBuffer(&shared_memory,
size,
id_request);
GpuCommandBufferMsg_RegisterTransferBuffer::WriteReplyParams(reply_message,
id);
} else {
reply_message->set_reply_error();
}
Send(reply_message);
}
| 170,938 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: read_Header(struct archive_read *a, struct _7z_header_info *h,
int check_header_id)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
const unsigned char *p;
struct _7z_folder *folders;
struct _7z_stream_info *si = &(zip->si);
struct _7zip_entry *entries;
uint32_t folderIndex, indexInFolder;
unsigned i;
int eindex, empty_streams, sindex;
if (check_header_id) {
/*
* Read Header.
*/
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p != kHeader)
return (-1);
}
/*
* Read ArchiveProperties.
*/
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p == kArchiveProperties) {
for (;;) {
uint64_t size;
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p == 0)
break;
if (parse_7zip_uint64(a, &size) < 0)
return (-1);
}
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
}
/*
* Read MainStreamsInfo.
*/
if (*p == kMainStreamsInfo) {
if (read_StreamsInfo(a, &(zip->si)) < 0)
return (-1);
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
}
if (*p == kEnd)
return (0);
/*
* Read FilesInfo.
*/
if (*p != kFilesInfo)
return (-1);
if (parse_7zip_uint64(a, &(zip->numFiles)) < 0)
return (-1);
if (UMAX_ENTRY < zip->numFiles)
return (-1);
zip->entries = calloc((size_t)zip->numFiles, sizeof(*zip->entries));
if (zip->entries == NULL)
return (-1);
entries = zip->entries;
empty_streams = 0;
for (;;) {
int type;
uint64_t size;
size_t ll;
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
type = *p;
if (type == kEnd)
break;
if (parse_7zip_uint64(a, &size) < 0)
return (-1);
if (zip->header_bytes_remaining < size)
return (-1);
ll = (size_t)size;
switch (type) {
case kEmptyStream:
h->emptyStreamBools = calloc((size_t)zip->numFiles,
sizeof(*h->emptyStreamBools));
if (h->emptyStreamBools == NULL)
return (-1);
if (read_Bools(
a, h->emptyStreamBools, (size_t)zip->numFiles) < 0)
return (-1);
empty_streams = 0;
for (i = 0; i < zip->numFiles; i++) {
if (h->emptyStreamBools[i])
empty_streams++;
}
break;
case kEmptyFile:
if (empty_streams <= 0) {
/* Unexcepted sequence. Skip this. */
if (header_bytes(a, ll) == NULL)
return (-1);
break;
}
h->emptyFileBools = calloc(empty_streams,
sizeof(*h->emptyFileBools));
if (h->emptyFileBools == NULL)
return (-1);
if (read_Bools(a, h->emptyFileBools, empty_streams) < 0)
return (-1);
break;
case kAnti:
if (empty_streams <= 0) {
/* Unexcepted sequence. Skip this. */
if (header_bytes(a, ll) == NULL)
return (-1);
break;
}
h->antiBools = calloc(empty_streams,
sizeof(*h->antiBools));
if (h->antiBools == NULL)
return (-1);
if (read_Bools(a, h->antiBools, empty_streams) < 0)
return (-1);
break;
case kCTime:
case kATime:
case kMTime:
if (read_Times(a, h, type) < 0)
return (-1);
break;
case kName:
{
unsigned char *np;
size_t nl, nb;
/* Skip one byte. */
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
ll--;
if ((ll & 1) || ll < zip->numFiles * 4)
return (-1);
zip->entry_names = malloc(ll);
if (zip->entry_names == NULL)
return (-1);
np = zip->entry_names;
nb = ll;
/*
* Copy whole file names.
* NOTE: This loop prevents from expanding
* the uncompressed buffer in order not to
* use extra memory resource.
*/
while (nb) {
size_t b;
if (nb > UBUFF_SIZE)
b = UBUFF_SIZE;
else
b = nb;
if ((p = header_bytes(a, b)) == NULL)
return (-1);
memcpy(np, p, b);
np += b;
nb -= b;
}
np = zip->entry_names;
nl = ll;
for (i = 0; i < zip->numFiles; i++) {
entries[i].utf16name = np;
#if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG)
entries[i].wname = (wchar_t *)np;
#endif
/* Find a terminator. */
while (nl >= 2 && (np[0] || np[1])) {
np += 2;
nl -= 2;
}
if (nl < 2)
return (-1);/* Terminator not found */
entries[i].name_len = np - entries[i].utf16name;
np += 2;
nl -= 2;
}
break;
}
case kAttributes:
{
int allAreDefined;
if ((p = header_bytes(a, 2)) == NULL)
return (-1);
allAreDefined = *p;
h->attrBools = calloc((size_t)zip->numFiles,
sizeof(*h->attrBools));
if (h->attrBools == NULL)
return (-1);
if (allAreDefined)
memset(h->attrBools, 1, (size_t)zip->numFiles);
else {
if (read_Bools(a, h->attrBools,
(size_t)zip->numFiles) < 0)
return (-1);
}
for (i = 0; i < zip->numFiles; i++) {
if (h->attrBools[i]) {
if ((p = header_bytes(a, 4)) == NULL)
return (-1);
entries[i].attr = archive_le32dec(p);
}
}
break;
}
case kDummy:
if (ll == 0)
break;
default:
if (header_bytes(a, ll) == NULL)
return (-1);
break;
}
}
/*
* Set up entry's attributes.
*/
folders = si->ci.folders;
eindex = sindex = 0;
folderIndex = indexInFolder = 0;
for (i = 0; i < zip->numFiles; i++) {
if (h->emptyStreamBools == NULL || h->emptyStreamBools[i] == 0)
entries[i].flg |= HAS_STREAM;
/* The high 16 bits of attributes is a posix file mode. */
entries[i].mode = entries[i].attr >> 16;
if (entries[i].flg & HAS_STREAM) {
if ((size_t)sindex >= si->ss.unpack_streams)
return (-1);
if (entries[i].mode == 0)
entries[i].mode = AE_IFREG | 0666;
if (si->ss.digestsDefined[sindex])
entries[i].flg |= CRC32_IS_SET;
entries[i].ssIndex = sindex;
sindex++;
} else {
int dir;
if (h->emptyFileBools == NULL)
dir = 1;
else {
if (h->emptyFileBools[eindex])
dir = 0;
else
dir = 1;
eindex++;
}
if (entries[i].mode == 0) {
if (dir)
entries[i].mode = AE_IFDIR | 0777;
else
entries[i].mode = AE_IFREG | 0666;
} else if (dir &&
(entries[i].mode & AE_IFMT) != AE_IFDIR) {
entries[i].mode &= ~AE_IFMT;
entries[i].mode |= AE_IFDIR;
}
if ((entries[i].mode & AE_IFMT) == AE_IFDIR &&
entries[i].name_len >= 2 &&
(entries[i].utf16name[entries[i].name_len-2] != '/' ||
entries[i].utf16name[entries[i].name_len-1] != 0)) {
entries[i].utf16name[entries[i].name_len] = '/';
entries[i].utf16name[entries[i].name_len+1] = 0;
entries[i].name_len += 2;
}
entries[i].ssIndex = -1;
}
if (entries[i].attr & 0x01)
entries[i].mode &= ~0222;/* Read only. */
if ((entries[i].flg & HAS_STREAM) == 0 && indexInFolder == 0) {
/*
* The entry is an empty file or a directory file,
* those both have no contents.
*/
entries[i].folderIndex = -1;
continue;
}
if (indexInFolder == 0) {
for (;;) {
if (folderIndex >= si->ci.numFolders)
return (-1);
if (folders[folderIndex].numUnpackStreams)
break;
folderIndex++;
}
}
entries[i].folderIndex = folderIndex;
if ((entries[i].flg & HAS_STREAM) == 0)
continue;
indexInFolder++;
if (indexInFolder >= folders[folderIndex].numUnpackStreams) {
folderIndex++;
indexInFolder = 0;
}
}
return (0);
}
Commit Message: Issue 761: Heap overflow reading corrupted 7Zip files
The sample file that demonstrated this had multiple 'EmptyStream'
attributes. The first one ended up being used to calculate
certain statistics, then was overwritten by the second which
was incompatible with those statistics.
The fix here is to reject any header with multiple EmptyStream
attributes. While here, also reject headers with multiple
EmptyFile, AntiFile, Name, or Attributes markers.
CWE ID: CWE-125 | read_Header(struct archive_read *a, struct _7z_header_info *h,
int check_header_id)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
const unsigned char *p;
struct _7z_folder *folders;
struct _7z_stream_info *si = &(zip->si);
struct _7zip_entry *entries;
uint32_t folderIndex, indexInFolder;
unsigned i;
int eindex, empty_streams, sindex;
if (check_header_id) {
/*
* Read Header.
*/
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p != kHeader)
return (-1);
}
/*
* Read ArchiveProperties.
*/
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p == kArchiveProperties) {
for (;;) {
uint64_t size;
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p == 0)
break;
if (parse_7zip_uint64(a, &size) < 0)
return (-1);
}
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
}
/*
* Read MainStreamsInfo.
*/
if (*p == kMainStreamsInfo) {
if (read_StreamsInfo(a, &(zip->si)) < 0)
return (-1);
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
}
if (*p == kEnd)
return (0);
/*
* Read FilesInfo.
*/
if (*p != kFilesInfo)
return (-1);
if (parse_7zip_uint64(a, &(zip->numFiles)) < 0)
return (-1);
if (UMAX_ENTRY < zip->numFiles)
return (-1);
zip->entries = calloc((size_t)zip->numFiles, sizeof(*zip->entries));
if (zip->entries == NULL)
return (-1);
entries = zip->entries;
empty_streams = 0;
for (;;) {
int type;
uint64_t size;
size_t ll;
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
type = *p;
if (type == kEnd)
break;
if (parse_7zip_uint64(a, &size) < 0)
return (-1);
if (zip->header_bytes_remaining < size)
return (-1);
ll = (size_t)size;
switch (type) {
case kEmptyStream:
if (h->emptyStreamBools != NULL)
return (-1);
h->emptyStreamBools = calloc((size_t)zip->numFiles,
sizeof(*h->emptyStreamBools));
if (h->emptyStreamBools == NULL)
return (-1);
if (read_Bools(
a, h->emptyStreamBools, (size_t)zip->numFiles) < 0)
return (-1);
empty_streams = 0;
for (i = 0; i < zip->numFiles; i++) {
if (h->emptyStreamBools[i])
empty_streams++;
}
break;
case kEmptyFile:
if (empty_streams <= 0) {
/* Unexcepted sequence. Skip this. */
if (header_bytes(a, ll) == NULL)
return (-1);
break;
}
if (h->emptyFileBools != NULL)
return (-1);
h->emptyFileBools = calloc(empty_streams,
sizeof(*h->emptyFileBools));
if (h->emptyFileBools == NULL)
return (-1);
if (read_Bools(a, h->emptyFileBools, empty_streams) < 0)
return (-1);
break;
case kAnti:
if (empty_streams <= 0) {
/* Unexcepted sequence. Skip this. */
if (header_bytes(a, ll) == NULL)
return (-1);
break;
}
if (h->antiBools != NULL)
return (-1);
h->antiBools = calloc(empty_streams,
sizeof(*h->antiBools));
if (h->antiBools == NULL)
return (-1);
if (read_Bools(a, h->antiBools, empty_streams) < 0)
return (-1);
break;
case kCTime:
case kATime:
case kMTime:
if (read_Times(a, h, type) < 0)
return (-1);
break;
case kName:
{
unsigned char *np;
size_t nl, nb;
/* Skip one byte. */
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
ll--;
if ((ll & 1) || ll < zip->numFiles * 4)
return (-1);
if (zip->entry_names != NULL)
return (-1);
zip->entry_names = malloc(ll);
if (zip->entry_names == NULL)
return (-1);
np = zip->entry_names;
nb = ll;
/*
* Copy whole file names.
* NOTE: This loop prevents from expanding
* the uncompressed buffer in order not to
* use extra memory resource.
*/
while (nb) {
size_t b;
if (nb > UBUFF_SIZE)
b = UBUFF_SIZE;
else
b = nb;
if ((p = header_bytes(a, b)) == NULL)
return (-1);
memcpy(np, p, b);
np += b;
nb -= b;
}
np = zip->entry_names;
nl = ll;
for (i = 0; i < zip->numFiles; i++) {
entries[i].utf16name = np;
#if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG)
entries[i].wname = (wchar_t *)np;
#endif
/* Find a terminator. */
while (nl >= 2 && (np[0] || np[1])) {
np += 2;
nl -= 2;
}
if (nl < 2)
return (-1);/* Terminator not found */
entries[i].name_len = np - entries[i].utf16name;
np += 2;
nl -= 2;
}
break;
}
case kAttributes:
{
int allAreDefined;
if ((p = header_bytes(a, 2)) == NULL)
return (-1);
allAreDefined = *p;
if (h->attrBools != NULL)
return (-1);
h->attrBools = calloc((size_t)zip->numFiles,
sizeof(*h->attrBools));
if (h->attrBools == NULL)
return (-1);
if (allAreDefined)
memset(h->attrBools, 1, (size_t)zip->numFiles);
else {
if (read_Bools(a, h->attrBools,
(size_t)zip->numFiles) < 0)
return (-1);
}
for (i = 0; i < zip->numFiles; i++) {
if (h->attrBools[i]) {
if ((p = header_bytes(a, 4)) == NULL)
return (-1);
entries[i].attr = archive_le32dec(p);
}
}
break;
}
case kDummy:
if (ll == 0)
break;
default:
if (header_bytes(a, ll) == NULL)
return (-1);
break;
}
}
/*
* Set up entry's attributes.
*/
folders = si->ci.folders;
eindex = sindex = 0;
folderIndex = indexInFolder = 0;
for (i = 0; i < zip->numFiles; i++) {
if (h->emptyStreamBools == NULL || h->emptyStreamBools[i] == 0)
entries[i].flg |= HAS_STREAM;
/* The high 16 bits of attributes is a posix file mode. */
entries[i].mode = entries[i].attr >> 16;
if (entries[i].flg & HAS_STREAM) {
if ((size_t)sindex >= si->ss.unpack_streams)
return (-1);
if (entries[i].mode == 0)
entries[i].mode = AE_IFREG | 0666;
if (si->ss.digestsDefined[sindex])
entries[i].flg |= CRC32_IS_SET;
entries[i].ssIndex = sindex;
sindex++;
} else {
int dir;
if (h->emptyFileBools == NULL)
dir = 1;
else {
if (h->emptyFileBools[eindex])
dir = 0;
else
dir = 1;
eindex++;
}
if (entries[i].mode == 0) {
if (dir)
entries[i].mode = AE_IFDIR | 0777;
else
entries[i].mode = AE_IFREG | 0666;
} else if (dir &&
(entries[i].mode & AE_IFMT) != AE_IFDIR) {
entries[i].mode &= ~AE_IFMT;
entries[i].mode |= AE_IFDIR;
}
if ((entries[i].mode & AE_IFMT) == AE_IFDIR &&
entries[i].name_len >= 2 &&
(entries[i].utf16name[entries[i].name_len-2] != '/' ||
entries[i].utf16name[entries[i].name_len-1] != 0)) {
entries[i].utf16name[entries[i].name_len] = '/';
entries[i].utf16name[entries[i].name_len+1] = 0;
entries[i].name_len += 2;
}
entries[i].ssIndex = -1;
}
if (entries[i].attr & 0x01)
entries[i].mode &= ~0222;/* Read only. */
if ((entries[i].flg & HAS_STREAM) == 0 && indexInFolder == 0) {
/*
* The entry is an empty file or a directory file,
* those both have no contents.
*/
entries[i].folderIndex = -1;
continue;
}
if (indexInFolder == 0) {
for (;;) {
if (folderIndex >= si->ci.numFolders)
return (-1);
if (folders[folderIndex].numUnpackStreams)
break;
folderIndex++;
}
}
entries[i].folderIndex = folderIndex;
if ((entries[i].flg & HAS_STREAM) == 0)
continue;
indexInFolder++;
if (indexInFolder >= folders[folderIndex].numUnpackStreams) {
folderIndex++;
indexInFolder = 0;
}
}
return (0);
}
| 168,764 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool has_byte(const eager_reader_t *reader) {
assert(reader != NULL);
fd_set read_fds;
FD_ZERO(&read_fds);
FD_SET(reader->bytes_available_fd, &read_fds);
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
select(reader->bytes_available_fd + 1, &read_fds, NULL, NULL, &timeout);
return FD_ISSET(reader->bytes_available_fd, &read_fds);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static bool has_byte(const eager_reader_t *reader) {
assert(reader != NULL);
fd_set read_fds;
FD_ZERO(&read_fds);
FD_SET(reader->bytes_available_fd, &read_fds);
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
TEMP_FAILURE_RETRY(select(reader->bytes_available_fd + 1, &read_fds, NULL, NULL, &timeout));
return FD_ISSET(reader->bytes_available_fd, &read_fds);
}
| 173,480 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: isoclns_print(netdissect_options *ndo,
const uint8_t *p, u_int length, u_int caplen)
{
if (caplen <= 1) { /* enough bytes on the wire ? */
ND_PRINT((ndo, "|OSI"));
return;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p));
switch (*p) {
case NLPID_CLNP:
if (!clnp_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", caplen);
break;
case NLPID_ESIS:
esis_print(ndo, p, length);
return;
case NLPID_ISIS:
if (!isis_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", caplen);
break;
case NLPID_NULLNS:
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
break;
case NLPID_Q933:
q933_print(ndo, p + 1, length - 1);
break;
case NLPID_IP:
ip_print(ndo, p + 1, length - 1);
break;
case NLPID_IP6:
ip6_print(ndo, p + 1, length - 1);
break;
case NLPID_PPP:
ppp_print(ndo, p + 1, length - 1);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p));
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
if (caplen > 1)
print_unknown_data(ndo, p, "\n\t", caplen);
break;
}
}
Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | isoclns_print(netdissect_options *ndo,
isoclns_print(netdissect_options *ndo, const uint8_t *p, u_int length)
{
if (!ND_TTEST(*p)) { /* enough bytes on the wire ? */
ND_PRINT((ndo, "|OSI"));
return;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p));
switch (*p) {
case NLPID_CLNP:
if (!clnp_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_ESIS:
esis_print(ndo, p, length);
return;
case NLPID_ISIS:
if (!isis_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_NULLNS:
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
break;
case NLPID_Q933:
q933_print(ndo, p + 1, length - 1);
break;
case NLPID_IP:
ip_print(ndo, p + 1, length - 1);
break;
case NLPID_IP6:
ip6_print(ndo, p + 1, length - 1);
break;
case NLPID_PPP:
ppp_print(ndo, p + 1, length - 1);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p));
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
if (length > 1)
print_unknown_data(ndo, p, "\n\t", length);
break;
}
}
| 167,947 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
{
u32 data, tpr;
int max_irr, max_isr;
struct kvm_lapic *apic = vcpu->arch.apic;
void *vapic;
apic_sync_pv_eoi_to_guest(vcpu, apic);
if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
return;
tpr = kvm_apic_get_reg(apic, APIC_TASKPRI) & 0xff;
max_irr = apic_find_highest_irr(apic);
if (max_irr < 0)
max_irr = 0;
max_isr = apic_find_highest_isr(apic);
if (max_isr < 0)
max_isr = 0;
data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
vapic = kmap_atomic(vcpu->arch.apic->vapic_page);
*(u32 *)(vapic + offset_in_page(vcpu->arch.apic->vapic_addr)) = data;
kunmap_atomic(vapic);
}
Commit Message: KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368)
In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the
potential to corrupt kernel memory if userspace provides an address that
is at the end of a page. This patches concerts those functions to use
kvm_write_guest_cached and kvm_read_guest_cached. It also checks the
vapic_address specified by userspace during ioctl processing and returns
an error to userspace if the address is not a valid GPA.
This is generally not guest triggerable, because the required write is
done by firmware that runs before the guest. Also, it only affects AMD
processors and oldish Intel that do not have the FlexPriority feature
(unless you disable FlexPriority, of course; then newer processors are
also affected).
Fixes: b93463aa59d6 ('KVM: Accelerated apic support')
Reported-by: Andrew Honig <[email protected]>
Cc: [email protected]
Signed-off-by: Andrew Honig <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-20 | void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
{
u32 data, tpr;
int max_irr, max_isr;
struct kvm_lapic *apic = vcpu->arch.apic;
apic_sync_pv_eoi_to_guest(vcpu, apic);
if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
return;
tpr = kvm_apic_get_reg(apic, APIC_TASKPRI) & 0xff;
max_irr = apic_find_highest_irr(apic);
if (max_irr < 0)
max_irr = 0;
max_isr = apic_find_highest_isr(apic);
if (max_isr < 0)
max_isr = 0;
data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
sizeof(u32));
}
| 165,946 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int tls_construct_cke_dhe(SSL *s, unsigned char **p, int *len, int *al)
{
#ifndef OPENSSL_NO_DH
DH *dh_clnt = NULL;
const BIGNUM *pub_key;
EVP_PKEY *ckey = NULL, *skey = NULL;
skey = s->s3->peer_tmp;
if (skey == NULL) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
return 0;
}
ckey = ssl_generate_pkey(skey);
dh_clnt = EVP_PKEY_get0_DH(ckey);
if (dh_clnt == NULL || ssl_derive(s, ckey, skey) == 0) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
EVP_PKEY_free(ckey);
return 0;
}
/* send off the data */
DH_get0_key(dh_clnt, &pub_key, NULL);
*len = BN_num_bytes(pub_key);
s2n(*len, *p);
BN_bn2bin(pub_key, *p);
*len += 2;
EVP_PKEY_free(ckey);
return 1;
#else
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
#endif
}
Commit Message: Fix missing NULL checks in CKE processing
Reviewed-by: Rich Salz <[email protected]>
CWE ID: CWE-476 | static int tls_construct_cke_dhe(SSL *s, unsigned char **p, int *len, int *al)
{
#ifndef OPENSSL_NO_DH
DH *dh_clnt = NULL;
const BIGNUM *pub_key;
EVP_PKEY *ckey = NULL, *skey = NULL;
skey = s->s3->peer_tmp;
if (skey == NULL) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
return 0;
}
ckey = ssl_generate_pkey(skey);
if (ckey == NULL) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
return 0;
}
dh_clnt = EVP_PKEY_get0_DH(ckey);
if (dh_clnt == NULL || ssl_derive(s, ckey, skey) == 0) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
EVP_PKEY_free(ckey);
return 0;
}
/* send off the data */
DH_get0_key(dh_clnt, &pub_key, NULL);
*len = BN_num_bytes(pub_key);
s2n(*len, *p);
BN_bn2bin(pub_key, *p);
*len += 2;
EVP_PKEY_free(ckey);
return 1;
#else
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
#endif
}
| 168,433 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: local void process(char *path)
{
int method = -1; /* get_header() return value */
size_t len; /* length of base name (minus suffix) */
struct stat st; /* to get file type and mod time */
/* all compressed suffixes for decoding search, in length order */
static char *sufs[] = {".z", "-z", "_z", ".Z", ".gz", "-gz", ".zz", "-zz",
".zip", ".ZIP", ".tgz", NULL};
/* open input file with name in, descriptor ind -- set name and mtime */
if (path == NULL) {
strcpy(g.inf, "<stdin>");
g.ind = 0;
g.name = NULL;
g.mtime = g.headis & 2 ?
(fstat(g.ind, &st) ? time(NULL) : st.st_mtime) : 0;
len = 0;
}
else {
/* set input file name (already set if recursed here) */
if (path != g.inf) {
strncpy(g.inf, path, sizeof(g.inf));
if (g.inf[sizeof(g.inf) - 1])
bail("name too long: ", path);
}
len = strlen(g.inf);
/* try to stat input file -- if not there and decoding, look for that
name with compressed suffixes */
if (lstat(g.inf, &st)) {
if (errno == ENOENT && (g.list || g.decode)) {
char **try = sufs;
do {
if (*try == NULL || len + strlen(*try) >= sizeof(g.inf))
break;
strcpy(g.inf + len, *try++);
errno = 0;
} while (lstat(g.inf, &st) && errno == ENOENT);
}
#ifdef EOVERFLOW
if (errno == EOVERFLOW || errno == EFBIG)
bail(g.inf,
" too large -- not compiled with large file support");
#endif
if (errno) {
g.inf[len] = 0;
complain("%s does not exist -- skipping", g.inf);
return;
}
len = strlen(g.inf);
}
/* only process regular files, but allow symbolic links if -f,
recurse into directory if -r */
if ((st.st_mode & S_IFMT) != S_IFREG &&
(st.st_mode & S_IFMT) != S_IFLNK &&
(st.st_mode & S_IFMT) != S_IFDIR) {
complain("%s is a special file or device -- skipping", g.inf);
return;
}
if ((st.st_mode & S_IFMT) == S_IFLNK && !g.force && !g.pipeout) {
complain("%s is a symbolic link -- skipping", g.inf);
return;
}
if ((st.st_mode & S_IFMT) == S_IFDIR && !g.recurse) {
complain("%s is a directory -- skipping", g.inf);
return;
}
/* recurse into directory (assumes Unix) */
if ((st.st_mode & S_IFMT) == S_IFDIR) {
char *roll, *item, *cut, *base, *bigger;
size_t len, hold;
DIR *here;
struct dirent *next;
/* accumulate list of entries (need to do this, since readdir()
behavior not defined if directory modified between calls) */
here = opendir(g.inf);
if (here == NULL)
return;
hold = 512;
roll = MALLOC(hold);
if (roll == NULL)
bail("not enough memory", "");
*roll = 0;
item = roll;
while ((next = readdir(here)) != NULL) {
if (next->d_name[0] == 0 ||
(next->d_name[0] == '.' && (next->d_name[1] == 0 ||
(next->d_name[1] == '.' && next->d_name[2] == 0))))
continue;
len = strlen(next->d_name) + 1;
if (item + len + 1 > roll + hold) {
do { /* make roll bigger */
hold <<= 1;
} while (item + len + 1 > roll + hold);
bigger = REALLOC(roll, hold);
if (bigger == NULL) {
FREE(roll);
bail("not enough memory", "");
}
item = bigger + (item - roll);
roll = bigger;
}
strcpy(item, next->d_name);
item += len;
*item = 0;
}
closedir(here);
/* run process() for each entry in the directory */
cut = base = g.inf + strlen(g.inf);
if (base > g.inf && base[-1] != (unsigned char)'/') {
if ((size_t)(base - g.inf) >= sizeof(g.inf))
bail("path too long", g.inf);
*base++ = '/';
}
item = roll;
while (*item) {
strncpy(base, item, sizeof(g.inf) - (base - g.inf));
if (g.inf[sizeof(g.inf) - 1]) {
strcpy(g.inf + (sizeof(g.inf) - 4), "...");
bail("path too long: ", g.inf);
}
process(g.inf);
item += strlen(item) + 1;
}
*cut = 0;
/* release list of entries */
FREE(roll);
return;
}
/* don't compress .gz (or provided suffix) files, unless -f */
if (!(g.force || g.list || g.decode) && len >= strlen(g.sufx) &&
strcmp(g.inf + len - strlen(g.sufx), g.sufx) == 0) {
complain("%s ends with %s -- skipping", g.inf, g.sufx);
return;
}
/* create output file only if input file has compressed suffix */
if (g.decode == 1 && !g.pipeout && !g.list) {
int suf = compressed_suffix(g.inf);
if (suf == 0) {
complain("%s does not have compressed suffix -- skipping",
g.inf);
return;
}
len -= suf;
}
/* open input file */
g.ind = open(g.inf, O_RDONLY, 0);
if (g.ind < 0)
bail("read error on ", g.inf);
/* prepare gzip header information for compression */
g.name = g.headis & 1 ? justname(g.inf) : NULL;
g.mtime = g.headis & 2 ? st.st_mtime : 0;
}
SET_BINARY_MODE(g.ind);
/* if decoding or testing, try to read gzip header */
g.hname = NULL;
if (g.decode) {
in_init();
method = get_header(1);
if (method != 8 && method != 257 &&
/* gzip -cdf acts like cat on uncompressed input */
!(method == -2 && g.force && g.pipeout && g.decode != 2 &&
!g.list)) {
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
if (method != -1)
complain(method < 0 ? "%s is not compressed -- skipping" :
"%s has unknown compression method -- skipping",
g.inf);
return;
}
/* if requested, test input file (possibly a special list) */
if (g.decode == 2) {
if (method == 8)
infchk();
else {
unlzw();
if (g.list) {
g.in_tot -= 3;
show_info(method, 0, g.out_tot, 0);
}
}
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
return;
}
}
/* if requested, just list information about input file */
if (g.list) {
list_info();
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
return;
}
/* create output file out, descriptor outd */
if (path == NULL || g.pipeout) {
/* write to stdout */
g.outf = MALLOC(strlen("<stdout>") + 1);
if (g.outf == NULL)
bail("not enough memory", "");
strcpy(g.outf, "<stdout>");
g.outd = 1;
if (!g.decode && !g.force && isatty(g.outd))
bail("trying to write compressed data to a terminal",
" (use -f to force)");
}
else {
char *to, *repl;
/* use header name for output when decompressing with -N */
to = g.inf;
if (g.decode && (g.headis & 1) != 0 && g.hname != NULL) {
to = g.hname;
len = strlen(g.hname);
}
/* replace .tgz with .tar when decoding */
repl = g.decode && strcmp(to + len, ".tgz") ? "" : ".tar";
/* create output file and open to write */
g.outf = MALLOC(len + (g.decode ? strlen(repl) : strlen(g.sufx)) + 1);
if (g.outf == NULL)
bail("not enough memory", "");
memcpy(g.outf, to, len);
strcpy(g.outf + len, g.decode ? repl : g.sufx);
g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY |
(g.force ? 0 : O_EXCL), 0600);
/* if exists and not -f, give user a chance to overwrite */
if (g.outd < 0 && errno == EEXIST && isatty(0) && g.verbosity) {
int ch, reply;
fprintf(stderr, "%s exists -- overwrite (y/n)? ", g.outf);
fflush(stderr);
reply = -1;
do {
ch = getchar();
if (reply < 0 && ch != ' ' && ch != '\t')
reply = ch == 'y' || ch == 'Y' ? 1 : 0;
} while (ch != EOF && ch != '\n' && ch != '\r');
if (reply == 1)
g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY,
0600);
}
/* if exists and no overwrite, report and go on to next */
if (g.outd < 0 && errno == EEXIST) {
complain("%s exists -- skipping", g.outf);
RELEASE(g.outf);
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
return;
}
/* if some other error, give up */
if (g.outd < 0)
bail("write error on ", g.outf);
}
SET_BINARY_MODE(g.outd);
RELEASE(g.hname);
/* process ind to outd */
if (g.verbosity > 1)
fprintf(stderr, "%s to %s ", g.inf, g.outf);
if (g.decode) {
if (method == 8)
infchk();
else if (method == 257)
unlzw();
else
cat();
}
#ifndef NOTHREAD
else if (g.procs > 1)
parallel_compress();
#endif
else
single_compress(0);
if (g.verbosity > 1) {
putc('\n', stderr);
fflush(stderr);
}
/* finish up, copy attributes, set times, delete original */
if (g.ind != 0)
close(g.ind);
if (g.outd != 1) {
if (close(g.outd))
bail("write error on ", g.outf);
g.outd = -1; /* now prevent deletion on interrupt */
if (g.ind != 0) {
copymeta(g.inf, g.outf);
if (!g.keep)
unlink(g.inf);
}
if (g.decode && (g.headis & 2) != 0 && g.stamp)
touch(g.outf, g.stamp);
}
RELEASE(g.outf);
}
Commit Message: When decompressing with -N or -NT, strip any path from header name.
This uses the path of the compressed file combined with the name
from the header as the name of the decompressed output file. Any
path information in the header name is stripped. This avoids a
possible vulnerability where absolute or descending paths are put
in the gzip header.
CWE ID: CWE-22 | local void process(char *path)
{
int method = -1; /* get_header() return value */
size_t len; /* length of base name (minus suffix) */
struct stat st; /* to get file type and mod time */
/* all compressed suffixes for decoding search, in length order */
static char *sufs[] = {".z", "-z", "_z", ".Z", ".gz", "-gz", ".zz", "-zz",
".zip", ".ZIP", ".tgz", NULL};
/* open input file with name in, descriptor ind -- set name and mtime */
if (path == NULL) {
strcpy(g.inf, "<stdin>");
g.ind = 0;
g.name = NULL;
g.mtime = g.headis & 2 ?
(fstat(g.ind, &st) ? time(NULL) : st.st_mtime) : 0;
len = 0;
}
else {
/* set input file name (already set if recursed here) */
if (path != g.inf) {
strncpy(g.inf, path, sizeof(g.inf));
if (g.inf[sizeof(g.inf) - 1])
bail("name too long: ", path);
}
len = strlen(g.inf);
/* try to stat input file -- if not there and decoding, look for that
name with compressed suffixes */
if (lstat(g.inf, &st)) {
if (errno == ENOENT && (g.list || g.decode)) {
char **try = sufs;
do {
if (*try == NULL || len + strlen(*try) >= sizeof(g.inf))
break;
strcpy(g.inf + len, *try++);
errno = 0;
} while (lstat(g.inf, &st) && errno == ENOENT);
}
#ifdef EOVERFLOW
if (errno == EOVERFLOW || errno == EFBIG)
bail(g.inf,
" too large -- not compiled with large file support");
#endif
if (errno) {
g.inf[len] = 0;
complain("%s does not exist -- skipping", g.inf);
return;
}
len = strlen(g.inf);
}
/* only process regular files, but allow symbolic links if -f,
recurse into directory if -r */
if ((st.st_mode & S_IFMT) != S_IFREG &&
(st.st_mode & S_IFMT) != S_IFLNK &&
(st.st_mode & S_IFMT) != S_IFDIR) {
complain("%s is a special file or device -- skipping", g.inf);
return;
}
if ((st.st_mode & S_IFMT) == S_IFLNK && !g.force && !g.pipeout) {
complain("%s is a symbolic link -- skipping", g.inf);
return;
}
if ((st.st_mode & S_IFMT) == S_IFDIR && !g.recurse) {
complain("%s is a directory -- skipping", g.inf);
return;
}
/* recurse into directory (assumes Unix) */
if ((st.st_mode & S_IFMT) == S_IFDIR) {
char *roll, *item, *cut, *base, *bigger;
size_t len, hold;
DIR *here;
struct dirent *next;
/* accumulate list of entries (need to do this, since readdir()
behavior not defined if directory modified between calls) */
here = opendir(g.inf);
if (here == NULL)
return;
hold = 512;
roll = MALLOC(hold);
if (roll == NULL)
bail("not enough memory", "");
*roll = 0;
item = roll;
while ((next = readdir(here)) != NULL) {
if (next->d_name[0] == 0 ||
(next->d_name[0] == '.' && (next->d_name[1] == 0 ||
(next->d_name[1] == '.' && next->d_name[2] == 0))))
continue;
len = strlen(next->d_name) + 1;
if (item + len + 1 > roll + hold) {
do { /* make roll bigger */
hold <<= 1;
} while (item + len + 1 > roll + hold);
bigger = REALLOC(roll, hold);
if (bigger == NULL) {
FREE(roll);
bail("not enough memory", "");
}
item = bigger + (item - roll);
roll = bigger;
}
strcpy(item, next->d_name);
item += len;
*item = 0;
}
closedir(here);
/* run process() for each entry in the directory */
cut = base = g.inf + strlen(g.inf);
if (base > g.inf && base[-1] != (unsigned char)'/') {
if ((size_t)(base - g.inf) >= sizeof(g.inf))
bail("path too long", g.inf);
*base++ = '/';
}
item = roll;
while (*item) {
strncpy(base, item, sizeof(g.inf) - (base - g.inf));
if (g.inf[sizeof(g.inf) - 1]) {
strcpy(g.inf + (sizeof(g.inf) - 4), "...");
bail("path too long: ", g.inf);
}
process(g.inf);
item += strlen(item) + 1;
}
*cut = 0;
/* release list of entries */
FREE(roll);
return;
}
/* don't compress .gz (or provided suffix) files, unless -f */
if (!(g.force || g.list || g.decode) && len >= strlen(g.sufx) &&
strcmp(g.inf + len - strlen(g.sufx), g.sufx) == 0) {
complain("%s ends with %s -- skipping", g.inf, g.sufx);
return;
}
/* create output file only if input file has compressed suffix */
if (g.decode == 1 && !g.pipeout && !g.list) {
int suf = compressed_suffix(g.inf);
if (suf == 0) {
complain("%s does not have compressed suffix -- skipping",
g.inf);
return;
}
len -= suf;
}
/* open input file */
g.ind = open(g.inf, O_RDONLY, 0);
if (g.ind < 0)
bail("read error on ", g.inf);
/* prepare gzip header information for compression */
g.name = g.headis & 1 ? justname(g.inf) : NULL;
g.mtime = g.headis & 2 ? st.st_mtime : 0;
}
SET_BINARY_MODE(g.ind);
/* if decoding or testing, try to read gzip header */
g.hname = NULL;
if (g.decode) {
in_init();
method = get_header(1);
if (method != 8 && method != 257 &&
/* gzip -cdf acts like cat on uncompressed input */
!(method == -2 && g.force && g.pipeout && g.decode != 2 &&
!g.list)) {
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
if (method != -1)
complain(method < 0 ? "%s is not compressed -- skipping" :
"%s has unknown compression method -- skipping",
g.inf);
return;
}
/* if requested, test input file (possibly a special list) */
if (g.decode == 2) {
if (method == 8)
infchk();
else {
unlzw();
if (g.list) {
g.in_tot -= 3;
show_info(method, 0, g.out_tot, 0);
}
}
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
return;
}
}
/* if requested, just list information about input file */
if (g.list) {
list_info();
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
return;
}
/* create output file out, descriptor outd */
if (path == NULL || g.pipeout) {
/* write to stdout */
g.outf = MALLOC(strlen("<stdout>") + 1);
if (g.outf == NULL)
bail("not enough memory", "");
strcpy(g.outf, "<stdout>");
g.outd = 1;
if (!g.decode && !g.force && isatty(g.outd))
bail("trying to write compressed data to a terminal",
" (use -f to force)");
}
else {
char *to = g.inf, *sufx = "";
size_t pre = 0;
/* select parts of the output file name */
if (g.decode) {
/* for -dN or -dNT, use the path from the input file and the name
from the header, stripping any path in the header name */
if ((g.headis & 1) != 0 && g.hname != NULL) {
pre = justname(g.inf) - g.inf;
to = justname(g.hname);
len = strlen(to);
}
/* for -d or -dNn, replace abbreviated suffixes */
else if (strcmp(to + len, ".tgz") == 0)
sufx = ".tar";
}
else
/* add appropriate suffix when compressing */
sufx = g.sufx;
/* create output file and open to write */
g.outf = MALLOC(pre + len + strlen(sufx) + 1);
if (g.outf == NULL)
bail("not enough memory", "");
memcpy(g.outf, g.inf, pre);
memcpy(g.outf + pre, to, len);
strcpy(g.outf + pre + len, sufx);
g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY |
(g.force ? 0 : O_EXCL), 0600);
/* if exists and not -f, give user a chance to overwrite */
if (g.outd < 0 && errno == EEXIST && isatty(0) && g.verbosity) {
int ch, reply;
fprintf(stderr, "%s exists -- overwrite (y/n)? ", g.outf);
fflush(stderr);
reply = -1;
do {
ch = getchar();
if (reply < 0 && ch != ' ' && ch != '\t')
reply = ch == 'y' || ch == 'Y' ? 1 : 0;
} while (ch != EOF && ch != '\n' && ch != '\r');
if (reply == 1)
g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY,
0600);
}
/* if exists and no overwrite, report and go on to next */
if (g.outd < 0 && errno == EEXIST) {
complain("%s exists -- skipping", g.outf);
RELEASE(g.outf);
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
return;
}
/* if some other error, give up */
if (g.outd < 0)
bail("write error on ", g.outf);
}
SET_BINARY_MODE(g.outd);
RELEASE(g.hname);
/* process ind to outd */
if (g.verbosity > 1)
fprintf(stderr, "%s to %s ", g.inf, g.outf);
if (g.decode) {
if (method == 8)
infchk();
else if (method == 257)
unlzw();
else
cat();
}
#ifndef NOTHREAD
else if (g.procs > 1)
parallel_compress();
#endif
else
single_compress(0);
if (g.verbosity > 1) {
putc('\n', stderr);
fflush(stderr);
}
/* finish up, copy attributes, set times, delete original */
if (g.ind != 0)
close(g.ind);
if (g.outd != 1) {
if (close(g.outd))
bail("write error on ", g.outf);
g.outd = -1; /* now prevent deletion on interrupt */
if (g.ind != 0) {
copymeta(g.inf, g.outf);
if (!g.keep)
unlink(g.inf);
}
if (g.decode && (g.headis & 2) != 0 && g.stamp)
touch(g.outf, g.stamp);
}
RELEASE(g.outf);
}
| 166,727 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderThread::Init() {
TRACE_EVENT_BEGIN_ETW("RenderThread::Init", 0, "");
#if defined(OS_MACOSX)
WebKit::WebView::setUseExternalPopupMenus(true);
#endif
lazy_tls.Pointer()->Set(this);
#if defined(OS_WIN)
if (RenderProcessImpl::InProcessPlugins())
CoInitialize(0);
#endif
suspend_webkit_shared_timer_ = true;
notify_webkit_of_modal_loop_ = true;
plugin_refresh_allowed_ = true;
widget_count_ = 0;
hidden_widget_count_ = 0;
idle_notification_delay_in_s_ = kInitialIdleHandlerDelayS;
task_factory_.reset(new ScopedRunnableMethodFactory<RenderThread>(this));
appcache_dispatcher_.reset(new AppCacheDispatcher(this));
indexed_db_dispatcher_.reset(new IndexedDBDispatcher());
db_message_filter_ = new DBMessageFilter();
AddFilter(db_message_filter_.get());
vc_manager_ = new VideoCaptureImplManager();
AddFilter(vc_manager_->video_capture_message_filter());
audio_input_message_filter_ = new AudioInputMessageFilter();
AddFilter(audio_input_message_filter_.get());
audio_message_filter_ = new AudioMessageFilter();
AddFilter(audio_message_filter_.get());
content::GetContentClient()->renderer()->RenderThreadStarted();
TRACE_EVENT_END_ETW("RenderThread::Init", 0, "");
}
Commit Message: DevTools: move DevToolsAgent/Client into content.
BUG=84078
TEST=
Review URL: http://codereview.chromium.org/7461019
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void RenderThread::Init() {
TRACE_EVENT_BEGIN_ETW("RenderThread::Init", 0, "");
#if defined(OS_MACOSX)
WebKit::WebView::setUseExternalPopupMenus(true);
#endif
lazy_tls.Pointer()->Set(this);
#if defined(OS_WIN)
if (RenderProcessImpl::InProcessPlugins())
CoInitialize(0);
#endif
suspend_webkit_shared_timer_ = true;
notify_webkit_of_modal_loop_ = true;
plugin_refresh_allowed_ = true;
widget_count_ = 0;
hidden_widget_count_ = 0;
idle_notification_delay_in_s_ = kInitialIdleHandlerDelayS;
task_factory_.reset(new ScopedRunnableMethodFactory<RenderThread>(this));
appcache_dispatcher_.reset(new AppCacheDispatcher(this));
indexed_db_dispatcher_.reset(new IndexedDBDispatcher());
db_message_filter_ = new DBMessageFilter();
AddFilter(db_message_filter_.get());
vc_manager_ = new VideoCaptureImplManager();
AddFilter(vc_manager_->video_capture_message_filter());
audio_input_message_filter_ = new AudioInputMessageFilter();
AddFilter(audio_input_message_filter_.get());
audio_message_filter_ = new AudioMessageFilter();
AddFilter(audio_message_filter_.get());
devtools_agent_message_filter_ = new DevToolsAgentFilter();
AddFilter(devtools_agent_message_filter_.get());
content::GetContentClient()->renderer()->RenderThreadStarted();
TRACE_EVENT_END_ETW("RenderThread::Init", 0, "");
}
| 170,326 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void CreateSensorFusion(
mojo::ScopedSharedBufferMapping mapping,
std::unique_ptr<PlatformSensorFusionAlgorithm> fusion_algorithm,
const PlatformSensorProviderBase::CreateSensorCallback& callback,
PlatformSensorProvider* provider) {
scoped_refptr<Factory> factory(new Factory(std::move(mapping),
std::move(fusion_algorithm),
std::move(callback), provider));
factory->FetchSources();
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732 | static void CreateSensorFusion(
SensorReadingSharedBuffer* reading_buffer,
std::unique_ptr<PlatformSensorFusionAlgorithm> fusion_algorithm,
const PlatformSensorProviderBase::CreateSensorCallback& callback,
PlatformSensorProvider* provider) {
scoped_refptr<Factory> factory(new Factory(reading_buffer,
std::move(fusion_algorithm),
std::move(callback), provider));
factory->FetchSources();
}
| 172,828 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void nlmclnt_unlock_callback(struct rpc_task *task, void *data)
{
struct nlm_rqst *req = data;
u32 status = ntohl(req->a_res.status);
if (RPC_ASSASSINATED(task))
goto die;
if (task->tk_status < 0) {
dprintk("lockd: unlock failed (err = %d)\n", -task->tk_status);
goto retry_rebind;
}
if (status == NLM_LCK_DENIED_GRACE_PERIOD) {
rpc_delay(task, NLMCLNT_GRACE_WAIT);
goto retry_unlock;
}
if (status != NLM_LCK_GRANTED)
printk(KERN_WARNING "lockd: unexpected unlock status: %d\n", status);
die:
return;
retry_rebind:
nlm_rebind_host(req->a_host);
retry_unlock:
rpc_restart_call(task);
}
Commit Message: NLM: Don't hang forever on NLM unlock requests
If the NLM daemon is killed on the NFS server, we can currently end up
hanging forever on an 'unlock' request, instead of aborting. Basically,
if the rpcbind request fails, or the server keeps returning garbage, we
really want to quit instead of retrying.
Tested-by: Vasily Averin <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
Cc: [email protected]
CWE ID: CWE-399 | static void nlmclnt_unlock_callback(struct rpc_task *task, void *data)
{
struct nlm_rqst *req = data;
u32 status = ntohl(req->a_res.status);
if (RPC_ASSASSINATED(task))
goto die;
if (task->tk_status < 0) {
dprintk("lockd: unlock failed (err = %d)\n", -task->tk_status);
switch (task->tk_status) {
case -EACCES:
case -EIO:
goto die;
default:
goto retry_rebind;
}
}
if (status == NLM_LCK_DENIED_GRACE_PERIOD) {
rpc_delay(task, NLMCLNT_GRACE_WAIT);
goto retry_unlock;
}
if (status != NLM_LCK_GRANTED)
printk(KERN_WARNING "lockd: unexpected unlock status: %d\n", status);
die:
return;
retry_rebind:
nlm_rebind_host(req->a_host);
retry_unlock:
rpc_restart_call(task);
}
| 166,221 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: transform_info_imp(transform_display *dp, png_structp pp, png_infop pi)
{
/* Reuse the standard stuff as appropriate. */
standard_info_part1(&dp->this, pp, pi);
/* Now set the list of transforms. */
dp->transform_list->set(dp->transform_list, dp, pp, pi);
/* Update the info structure for these transforms: */
{
int i = dp->this.use_update_info;
/* Always do one call, even if use_update_info is 0. */
do
png_read_update_info(pp, pi);
while (--i > 0);
}
/* And get the output information into the standard_display */
standard_info_part2(&dp->this, pp, pi, 1/*images*/);
/* Plus the extra stuff we need for the transform tests: */
dp->output_colour_type = png_get_color_type(pp, pi);
dp->output_bit_depth = png_get_bit_depth(pp, pi);
/* Validate the combination of colour type and bit depth that we are getting
* out of libpng; the semantics of something not in the PNG spec are, at
* best, unclear.
*/
switch (dp->output_colour_type)
{
case PNG_COLOR_TYPE_PALETTE:
if (dp->output_bit_depth > 8) goto error;
/*FALL THROUGH*/
case PNG_COLOR_TYPE_GRAY:
if (dp->output_bit_depth == 1 || dp->output_bit_depth == 2 ||
dp->output_bit_depth == 4)
break;
/*FALL THROUGH*/
default:
if (dp->output_bit_depth == 8 || dp->output_bit_depth == 16)
break;
/*FALL THROUGH*/
error:
{
char message[128];
size_t pos;
pos = safecat(message, sizeof message, 0,
"invalid final bit depth: colour type(");
pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
pos = safecat(message, sizeof message, pos, ") with bit depth: ");
pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
png_error(pp, message);
}
}
/* Use a test pixel to check that the output agrees with what we expect -
* this avoids running the whole test if the output is unexpected.
*/
{
image_pixel test_pixel;
memset(&test_pixel, 0, sizeof test_pixel);
test_pixel.colour_type = dp->this.colour_type; /* input */
test_pixel.bit_depth = dp->this.bit_depth;
if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE)
test_pixel.sample_depth = 8;
else
test_pixel.sample_depth = test_pixel.bit_depth;
/* Don't need sBIT here, but it must be set to non-zero to avoid
* arithmetic overflows.
*/
test_pixel.have_tRNS = dp->this.is_transparent;
test_pixel.red_sBIT = test_pixel.green_sBIT = test_pixel.blue_sBIT =
test_pixel.alpha_sBIT = test_pixel.sample_depth;
dp->transform_list->mod(dp->transform_list, &test_pixel, pp, dp);
if (test_pixel.colour_type != dp->output_colour_type)
{
char message[128];
size_t pos = safecat(message, sizeof message, 0, "colour type ");
pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
pos = safecat(message, sizeof message, pos, " expected ");
pos = safecatn(message, sizeof message, pos, test_pixel.colour_type);
png_error(pp, message);
}
if (test_pixel.bit_depth != dp->output_bit_depth)
{
char message[128];
size_t pos = safecat(message, sizeof message, 0, "bit depth ");
pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
pos = safecat(message, sizeof message, pos, " expected ");
pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
png_error(pp, message);
}
/* If both bit depth and colour type are correct check the sample depth.
* I believe these are both internal errors.
*/
if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE)
{
if (test_pixel.sample_depth != 8) /* oops - internal error! */
png_error(pp, "pngvalid: internal: palette sample depth not 8");
}
else if (test_pixel.sample_depth != dp->output_bit_depth)
{
char message[128];
size_t pos = safecat(message, sizeof message, 0,
"internal: sample depth ");
pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
pos = safecat(message, sizeof message, pos, " expected ");
pos = safecatn(message, sizeof message, pos, test_pixel.sample_depth);
png_error(pp, message);
}
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | transform_info_imp(transform_display *dp, png_structp pp, png_infop pi)
{
/* Reuse the standard stuff as appropriate. */
standard_info_part1(&dp->this, pp, pi);
/* Now set the list of transforms. */
dp->transform_list->set(dp->transform_list, dp, pp, pi);
/* Update the info structure for these transforms: */
{
int i = dp->this.use_update_info;
/* Always do one call, even if use_update_info is 0. */
do
png_read_update_info(pp, pi);
while (--i > 0);
}
/* And get the output information into the standard_display */
standard_info_part2(&dp->this, pp, pi, 1/*images*/);
/* Plus the extra stuff we need for the transform tests: */
dp->output_colour_type = png_get_color_type(pp, pi);
dp->output_bit_depth = png_get_bit_depth(pp, pi);
/* If png_set_filler is in action then fake the output color type to include
* an alpha channel where appropriate.
*/
if (dp->output_bit_depth >= 8 &&
(dp->output_colour_type == PNG_COLOR_TYPE_RGB ||
dp->output_colour_type == PNG_COLOR_TYPE_GRAY) && dp->this.filler)
dp->output_colour_type |= 4;
/* Validate the combination of colour type and bit depth that we are getting
* out of libpng; the semantics of something not in the PNG spec are, at
* best, unclear.
*/
switch (dp->output_colour_type)
{
case PNG_COLOR_TYPE_PALETTE:
if (dp->output_bit_depth > 8) goto error;
/*FALL THROUGH*/
case PNG_COLOR_TYPE_GRAY:
if (dp->output_bit_depth == 1 || dp->output_bit_depth == 2 ||
dp->output_bit_depth == 4)
break;
/*FALL THROUGH*/
default:
if (dp->output_bit_depth == 8 || dp->output_bit_depth == 16)
break;
/*FALL THROUGH*/
error:
{
char message[128];
size_t pos;
pos = safecat(message, sizeof message, 0,
"invalid final bit depth: colour type(");
pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
pos = safecat(message, sizeof message, pos, ") with bit depth: ");
pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
png_error(pp, message);
}
}
/* Use a test pixel to check that the output agrees with what we expect -
* this avoids running the whole test if the output is unexpected. This also
* checks for internal errors.
*/
{
image_pixel test_pixel;
memset(&test_pixel, 0, sizeof test_pixel);
test_pixel.colour_type = dp->this.colour_type; /* input */
test_pixel.bit_depth = dp->this.bit_depth;
if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE)
test_pixel.sample_depth = 8;
else
test_pixel.sample_depth = test_pixel.bit_depth;
/* Don't need sBIT here, but it must be set to non-zero to avoid
* arithmetic overflows.
*/
test_pixel.have_tRNS = dp->this.is_transparent != 0;
test_pixel.red_sBIT = test_pixel.green_sBIT = test_pixel.blue_sBIT =
test_pixel.alpha_sBIT = test_pixel.sample_depth;
dp->transform_list->mod(dp->transform_list, &test_pixel, pp, dp);
if (test_pixel.colour_type != dp->output_colour_type)
{
char message[128];
size_t pos = safecat(message, sizeof message, 0, "colour type ");
pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
pos = safecat(message, sizeof message, pos, " expected ");
pos = safecatn(message, sizeof message, pos, test_pixel.colour_type);
png_error(pp, message);
}
if (test_pixel.bit_depth != dp->output_bit_depth)
{
char message[128];
size_t pos = safecat(message, sizeof message, 0, "bit depth ");
pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
pos = safecat(message, sizeof message, pos, " expected ");
pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
png_error(pp, message);
}
/* If both bit depth and colour type are correct check the sample depth.
*/
if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE &&
test_pixel.sample_depth != 8) /* oops - internal error! */
png_error(pp, "pngvalid: internal: palette sample depth not 8");
else if (dp->unpacked && test_pixel.bit_depth != 8)
png_error(pp, "pngvalid: internal: bad unpacked pixel depth");
else if (!dp->unpacked && test_pixel.colour_type != PNG_COLOR_TYPE_PALETTE
&& test_pixel.bit_depth != test_pixel.sample_depth)
{
char message[128];
size_t pos = safecat(message, sizeof message, 0,
"internal: sample depth ");
/* Because unless something has set 'unpacked' or the image is palette
* mapped we expect the transform to keep sample depth and bit depth
* the same.
*/
pos = safecatn(message, sizeof message, pos, test_pixel.sample_depth);
pos = safecat(message, sizeof message, pos, " expected ");
pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
png_error(pp, message);
}
else if (test_pixel.bit_depth != dp->output_bit_depth)
{
/* This could be a libpng error too; libpng has not produced what we
* expect for the output bit depth.
*/
char message[128];
size_t pos = safecat(message, sizeof message, 0,
"internal: bit depth ");
pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
pos = safecat(message, sizeof message, pos, " expected ");
pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
png_error(pp, message);
}
}
}
| 173,715 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms,
CMS_RecipientInfo *ri)
{
CMS_KeyTransRecipientInfo *ktri = ri->d.ktri;
EVP_PKEY *pkey = ktri->pkey;
unsigned char *ek = NULL;
size_t eklen;
int ret = 0;
CMS_EncryptedContentInfo *ec;
ec = cms->d.envelopedData->encryptedContentInfo;
CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_NO_PRIVATE_KEY);
return 0;
return 0;
}
Commit Message:
CWE ID: CWE-311 | static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms,
CMS_RecipientInfo *ri)
{
CMS_KeyTransRecipientInfo *ktri = ri->d.ktri;
EVP_PKEY *pkey = ktri->pkey;
unsigned char *ek = NULL;
size_t eklen;
int ret = 0;
size_t fixlen = 0;
CMS_EncryptedContentInfo *ec;
ec = cms->d.envelopedData->encryptedContentInfo;
CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_NO_PRIVATE_KEY);
return 0;
return 0;
}
| 165,137 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gfx::Size ShellWindowFrameView::GetMaximumSize() {
gfx::Size max_size = frame_->client_view()->GetMaximumSize();
if (!max_size.IsEmpty()) {
gfx::Rect client_bounds = GetBoundsForClientView();
max_size.Enlarge(0, client_bounds.y());
}
return max_size;
}
Commit Message: [views] Remove header bar on shell windows created with {frame: none}.
BUG=130182
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10597003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79 | gfx::Size ShellWindowFrameView::GetMaximumSize() {
gfx::Size max_size = frame_->client_view()->GetMaximumSize();
if (is_frameless_)
return max_size;
if (!max_size.IsEmpty()) {
gfx::Rect client_bounds = GetBoundsForClientView();
max_size.Enlarge(0, client_bounds.y());
}
return max_size;
}
| 170,712 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: INST_HANDLER (sbrx) { // SBRC Rr, b
int b = buf[0] & 0x7;
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x01) << 4);
RAnalOp next_op;
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
ESIL_A ("%d,1,<<,r%d,&,", b, r); // Rr(b)
ESIL_A ((buf[1] & 0xe) == 0xc
? "!," // SBRC => branch if cleared
: "!,!,"); // SBRS => branch if set
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
Commit Message: Fix invalid free in RAnal.avr
CWE ID: CWE-125 | INST_HANDLER (sbrx) { // SBRC Rr, b
int b = buf[0] & 0x7;
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x01) << 4);
RAnalOp next_op = {0};
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
ESIL_A ("%d,1,<<,r%d,&,", b, r); // Rr(b)
ESIL_A ((buf[1] & 0xe) == 0xc
? "!," // SBRC => branch if cleared
: "!,!,"); // SBRS => branch if set
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
| 169,231 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xfs_da3_fixhashpath(
struct xfs_da_state *state,
struct xfs_da_state_path *path)
{
struct xfs_da_state_blk *blk;
struct xfs_da_intnode *node;
struct xfs_da_node_entry *btree;
xfs_dahash_t lasthash=0;
int level;
int count;
struct xfs_inode *dp = state->args->dp;
trace_xfs_da_fixhashpath(state->args);
level = path->active-1;
blk = &path->blk[ level ];
switch (blk->magic) {
case XFS_ATTR_LEAF_MAGIC:
lasthash = xfs_attr_leaf_lasthash(blk->bp, &count);
if (count == 0)
return;
break;
case XFS_DIR2_LEAFN_MAGIC:
lasthash = xfs_dir2_leafn_lasthash(dp, blk->bp, &count);
if (count == 0)
return;
break;
case XFS_DA_NODE_MAGIC:
lasthash = xfs_da3_node_lasthash(dp, blk->bp, &count);
if (count == 0)
return;
break;
}
for (blk--, level--; level >= 0; blk--, level--) {
struct xfs_da3_icnode_hdr nodehdr;
node = blk->bp->b_addr;
dp->d_ops->node_hdr_from_disk(&nodehdr, node);
btree = dp->d_ops->node_tree_p(node);
if (be32_to_cpu(btree->hashval) == lasthash)
break;
blk->hashval = lasthash;
btree[blk->index].hashval = cpu_to_be32(lasthash);
xfs_trans_log_buf(state->args->trans, blk->bp,
XFS_DA_LOGRANGE(node, &btree[blk->index],
sizeof(*btree)));
lasthash = be32_to_cpu(btree[nodehdr.count - 1].hashval);
}
}
Commit Message: xfs: fix directory hash ordering bug
Commit f5ea1100 ("xfs: add CRCs to dir2/da node blocks") introduced
in 3.10 incorrectly converted the btree hash index array pointer in
xfs_da3_fixhashpath(). It resulted in the the current hash always
being compared against the first entry in the btree rather than the
current block index into the btree block's hash entry array. As a
result, it was comparing the wrong hashes, and so could misorder the
entries in the btree.
For most cases, this doesn't cause any problems as it requires hash
collisions to expose the ordering problem. However, when there are
hash collisions within a directory there is a very good probability
that the entries will be ordered incorrectly and that actually
matters when duplicate hashes are placed into or removed from the
btree block hash entry array.
This bug results in an on-disk directory corruption and that results
in directory verifier functions throwing corruption warnings into
the logs. While no data or directory entries are lost, access to
them may be compromised, and attempts to remove entries from a
directory that has suffered from this corruption may result in a
filesystem shutdown. xfs_repair will fix the directory hash
ordering without data loss occuring.
[dchinner: wrote useful a commit message]
cc: <[email protected]>
Reported-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: Mark Tinguely <[email protected]>
Reviewed-by: Ben Myers <[email protected]>
Signed-off-by: Dave Chinner <[email protected]>
CWE ID: CWE-399 | xfs_da3_fixhashpath(
struct xfs_da_state *state,
struct xfs_da_state_path *path)
{
struct xfs_da_state_blk *blk;
struct xfs_da_intnode *node;
struct xfs_da_node_entry *btree;
xfs_dahash_t lasthash=0;
int level;
int count;
struct xfs_inode *dp = state->args->dp;
trace_xfs_da_fixhashpath(state->args);
level = path->active-1;
blk = &path->blk[ level ];
switch (blk->magic) {
case XFS_ATTR_LEAF_MAGIC:
lasthash = xfs_attr_leaf_lasthash(blk->bp, &count);
if (count == 0)
return;
break;
case XFS_DIR2_LEAFN_MAGIC:
lasthash = xfs_dir2_leafn_lasthash(dp, blk->bp, &count);
if (count == 0)
return;
break;
case XFS_DA_NODE_MAGIC:
lasthash = xfs_da3_node_lasthash(dp, blk->bp, &count);
if (count == 0)
return;
break;
}
for (blk--, level--; level >= 0; blk--, level--) {
struct xfs_da3_icnode_hdr nodehdr;
node = blk->bp->b_addr;
dp->d_ops->node_hdr_from_disk(&nodehdr, node);
btree = dp->d_ops->node_tree_p(node);
if (be32_to_cpu(btree[blk->index].hashval) == lasthash)
break;
blk->hashval = lasthash;
btree[blk->index].hashval = cpu_to_be32(lasthash);
xfs_trans_log_buf(state->args->trans, blk->bp,
XFS_DA_LOGRANGE(node, &btree[blk->index],
sizeof(*btree)));
lasthash = be32_to_cpu(btree[nodehdr.count - 1].hashval);
}
}
| 166,260 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ieee80211_tx_h_unicast_ps_buf(struct ieee80211_tx_data *tx)
{
struct sta_info *sta = tx->sta;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb);
struct ieee80211_local *local = tx->local;
if (unlikely(!sta))
return TX_CONTINUE;
if (unlikely((test_sta_flag(sta, WLAN_STA_PS_STA) ||
test_sta_flag(sta, WLAN_STA_PS_DRIVER)) &&
!(info->flags & IEEE80211_TX_CTL_NO_PS_BUFFER))) {
int ac = skb_get_queue_mapping(tx->skb);
ps_dbg(sta->sdata, "STA %pM aid %d: PS buffer for AC %d\n",
sta->sta.addr, sta->sta.aid, ac);
if (tx->local->total_ps_buffered >= TOTAL_MAX_TX_BUFFER)
purge_old_ps_buffers(tx->local);
if (skb_queue_len(&sta->ps_tx_buf[ac]) >= STA_MAX_TX_BUFFER) {
struct sk_buff *old = skb_dequeue(&sta->ps_tx_buf[ac]);
ps_dbg(tx->sdata,
"STA %pM TX buffer for AC %d full - dropping oldest frame\n",
sta->sta.addr, ac);
ieee80211_free_txskb(&local->hw, old);
} else
tx->local->total_ps_buffered++;
info->control.jiffies = jiffies;
info->control.vif = &tx->sdata->vif;
info->flags |= IEEE80211_TX_INTFL_NEED_TXPROCESSING;
info->flags &= ~IEEE80211_TX_TEMPORARY_FLAGS;
skb_queue_tail(&sta->ps_tx_buf[ac], tx->skb);
if (!timer_pending(&local->sta_cleanup))
mod_timer(&local->sta_cleanup,
round_jiffies(jiffies +
STA_INFO_CLEANUP_INTERVAL));
/*
* We queued up some frames, so the TIM bit might
* need to be set, recalculate it.
*/
sta_info_recalc_tim(sta);
return TX_QUEUED;
} else if (unlikely(test_sta_flag(sta, WLAN_STA_PS_STA))) {
ps_dbg(tx->sdata,
"STA %pM in PS mode, but polling/in SP -> send frame\n",
sta->sta.addr);
}
return TX_CONTINUE;
}
Commit Message: mac80211: fix AP powersave TX vs. wakeup race
There is a race between the TX path and the STA wakeup: while
a station is sleeping, mac80211 buffers frames until it wakes
up, then the frames are transmitted. However, the RX and TX
path are concurrent, so the packet indicating wakeup can be
processed while a packet is being transmitted.
This can lead to a situation where the buffered frames list
is emptied on the one side, while a frame is being added on
the other side, as the station is still seen as sleeping in
the TX path.
As a result, the newly added frame will not be send anytime
soon. It might be sent much later (and out of order) when the
station goes to sleep and wakes up the next time.
Additionally, it can lead to the crash below.
Fix all this by synchronising both paths with a new lock.
Both path are not fastpath since they handle PS situations.
In a later patch we'll remove the extra skb queue locks to
reduce locking overhead.
BUG: unable to handle kernel
NULL pointer dereference at 000000b0
IP: [<ff6f1791>] ieee80211_report_used_skb+0x11/0x3e0 [mac80211]
*pde = 00000000
Oops: 0000 [#1] SMP DEBUG_PAGEALLOC
EIP: 0060:[<ff6f1791>] EFLAGS: 00210282 CPU: 1
EIP is at ieee80211_report_used_skb+0x11/0x3e0 [mac80211]
EAX: e5900da0 EBX: 00000000 ECX: 00000001 EDX: 00000000
ESI: e41d00c0 EDI: e5900da0 EBP: ebe458e4 ESP: ebe458b0
DS: 007b ES: 007b FS: 00d8 GS: 00e0 SS: 0068
CR0: 8005003b CR2: 000000b0 CR3: 25a78000 CR4: 000407d0
DR0: 00000000 DR1: 00000000 DR2: 00000000 DR3: 00000000
DR6: ffff0ff0 DR7: 00000400
Process iperf (pid: 3934, ti=ebe44000 task=e757c0b0 task.ti=ebe44000)
iwlwifi 0000:02:00.0: I iwl_pcie_enqueue_hcmd Sending command LQ_CMD (#4e), seq: 0x0903, 92 bytes at 3[3]:9
Stack:
e403b32c ebe458c4 00200002 00200286 e403b338 ebe458cc c10960bb e5900da0
ff76a6ec ebe458d8 00000000 e41d00c0 e5900da0 ebe458f0 ff6f1b75 e403b210
ebe4598c ff723dc1 00000000 ff76a6ec e597c978 e403b758 00000002 00000002
Call Trace:
[<ff6f1b75>] ieee80211_free_txskb+0x15/0x20 [mac80211]
[<ff723dc1>] invoke_tx_handlers+0x1661/0x1780 [mac80211]
[<ff7248a5>] ieee80211_tx+0x75/0x100 [mac80211]
[<ff7249bf>] ieee80211_xmit+0x8f/0xc0 [mac80211]
[<ff72550e>] ieee80211_subif_start_xmit+0x4fe/0xe20 [mac80211]
[<c149ef70>] dev_hard_start_xmit+0x450/0x950
[<c14b9aa9>] sch_direct_xmit+0xa9/0x250
[<c14b9c9b>] __qdisc_run+0x4b/0x150
[<c149f732>] dev_queue_xmit+0x2c2/0xca0
Cc: [email protected]
Reported-by: Yaara Rozenblum <[email protected]>
Signed-off-by: Emmanuel Grumbach <[email protected]>
Reviewed-by: Stanislaw Gruszka <[email protected]>
[reword commit log, use a separate lock]
Signed-off-by: Johannes Berg <[email protected]>
CWE ID: CWE-362 | ieee80211_tx_h_unicast_ps_buf(struct ieee80211_tx_data *tx)
{
struct sta_info *sta = tx->sta;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb);
struct ieee80211_local *local = tx->local;
if (unlikely(!sta))
return TX_CONTINUE;
if (unlikely((test_sta_flag(sta, WLAN_STA_PS_STA) ||
test_sta_flag(sta, WLAN_STA_PS_DRIVER)) &&
!(info->flags & IEEE80211_TX_CTL_NO_PS_BUFFER))) {
int ac = skb_get_queue_mapping(tx->skb);
ps_dbg(sta->sdata, "STA %pM aid %d: PS buffer for AC %d\n",
sta->sta.addr, sta->sta.aid, ac);
if (tx->local->total_ps_buffered >= TOTAL_MAX_TX_BUFFER)
purge_old_ps_buffers(tx->local);
/* sync with ieee80211_sta_ps_deliver_wakeup */
spin_lock(&sta->ps_lock);
/*
* STA woke up the meantime and all the frames on ps_tx_buf have
* been queued to pending queue. No reordering can happen, go
* ahead and Tx the packet.
*/
if (!test_sta_flag(sta, WLAN_STA_PS_STA) &&
!test_sta_flag(sta, WLAN_STA_PS_DRIVER)) {
spin_unlock(&sta->ps_lock);
return TX_CONTINUE;
}
if (skb_queue_len(&sta->ps_tx_buf[ac]) >= STA_MAX_TX_BUFFER) {
struct sk_buff *old = skb_dequeue(&sta->ps_tx_buf[ac]);
ps_dbg(tx->sdata,
"STA %pM TX buffer for AC %d full - dropping oldest frame\n",
sta->sta.addr, ac);
ieee80211_free_txskb(&local->hw, old);
} else
tx->local->total_ps_buffered++;
info->control.jiffies = jiffies;
info->control.vif = &tx->sdata->vif;
info->flags |= IEEE80211_TX_INTFL_NEED_TXPROCESSING;
info->flags &= ~IEEE80211_TX_TEMPORARY_FLAGS;
skb_queue_tail(&sta->ps_tx_buf[ac], tx->skb);
spin_unlock(&sta->ps_lock);
if (!timer_pending(&local->sta_cleanup))
mod_timer(&local->sta_cleanup,
round_jiffies(jiffies +
STA_INFO_CLEANUP_INTERVAL));
/*
* We queued up some frames, so the TIM bit might
* need to be set, recalculate it.
*/
sta_info_recalc_tim(sta);
return TX_QUEUED;
} else if (unlikely(test_sta_flag(sta, WLAN_STA_PS_STA))) {
ps_dbg(tx->sdata,
"STA %pM in PS mode, but polling/in SP -> send frame\n",
sta->sta.addr);
}
return TX_CONTINUE;
}
| 166,393 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderViewTest::SetUp() {
blink::initialize(blink_platform_impl_.Get());
content_client_.reset(CreateContentClient());
content_browser_client_.reset(CreateContentBrowserClient());
content_renderer_client_.reset(CreateContentRendererClient());
SetContentClient(content_client_.get());
SetBrowserClientForTesting(content_browser_client_.get());
SetRendererClientForTesting(content_renderer_client_.get());
if (!render_thread_)
render_thread_.reset(new MockRenderThread());
render_thread_->set_routing_id(kRouteId);
render_thread_->set_surface_id(kSurfaceId);
render_thread_->set_new_window_routing_id(kNewWindowRouteId);
render_thread_->set_new_frame_routing_id(kNewFrameRouteId);
#if defined(OS_MACOSX)
autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
#endif
command_line_.reset(new base::CommandLine(base::CommandLine::NO_PROGRAM));
params_.reset(new MainFunctionParams(*command_line_));
platform_.reset(new RendererMainPlatformDelegate(*params_));
platform_->PlatformInitialize();
std::string flags("--expose-gc");
v8::V8::SetFlagsFromString(flags.c_str(), static_cast<int>(flags.size()));
RenderThreadImpl::RegisterSchemes();
if (!ui::ResourceBundle::HasSharedInstance())
ui::ResourceBundle::InitSharedInstanceWithLocale(
"en-US", NULL, ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES);
compositor_deps_.reset(new FakeCompositorDependencies);
mock_process_.reset(new MockRenderProcess);
ViewMsg_New_Params view_params;
view_params.opener_frame_route_id = MSG_ROUTING_NONE;
view_params.window_was_created_with_opener = false;
view_params.renderer_preferences = RendererPreferences();
view_params.web_preferences = WebPreferences();
view_params.view_id = kRouteId;
view_params.main_frame_routing_id = kMainFrameRouteId;
view_params.surface_id = kSurfaceId;
view_params.session_storage_namespace_id = kInvalidSessionStorageNamespaceId;
view_params.swapped_out = false;
view_params.replicated_frame_state = FrameReplicationState();
view_params.proxy_routing_id = MSG_ROUTING_NONE;
view_params.hidden = false;
view_params.never_visible = false;
view_params.next_page_id = 1;
view_params.initial_size = *InitialSizeParams();
view_params.enable_auto_resize = false;
view_params.min_size = gfx::Size();
view_params.max_size = gfx::Size();
RenderViewImpl* view =
RenderViewImpl::Create(compositor_deps_.get(), view_params, false);
view_ = view;
}
Commit Message: Connect WebUSB client interface to the devices app
This provides a basic WebUSB client interface in
content/renderer. Most of the interface is unimplemented,
but this CL hooks up navigator.usb.getDevices() to the
browser's Mojo devices app to enumerate available USB
devices.
BUG=492204
Review URL: https://codereview.chromium.org/1293253002
Cr-Commit-Position: refs/heads/master@{#344881}
CWE ID: CWE-399 | void RenderViewTest::SetUp() {
blink::initialize(blink_platform_impl_.Get());
content_client_.reset(CreateContentClient());
content_browser_client_.reset(CreateContentBrowserClient());
content_renderer_client_.reset(CreateContentRendererClient());
SetContentClient(content_client_.get());
SetBrowserClientForTesting(content_browser_client_.get());
SetRendererClientForTesting(content_renderer_client_.get());
if (!render_thread_)
render_thread_.reset(new MockRenderThread());
render_thread_->set_routing_id(kRouteId);
render_thread_->set_surface_id(kSurfaceId);
render_thread_->set_new_window_routing_id(kNewWindowRouteId);
render_thread_->set_new_frame_routing_id(kNewFrameRouteId);
#if defined(OS_MACOSX)
autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
#endif
command_line_.reset(new base::CommandLine(base::CommandLine::NO_PROGRAM));
params_.reset(new MainFunctionParams(*command_line_));
platform_.reset(new RendererMainPlatformDelegate(*params_));
platform_->PlatformInitialize();
std::string flags("--expose-gc");
v8::V8::SetFlagsFromString(flags.c_str(), static_cast<int>(flags.size()));
RenderThreadImpl::RegisterSchemes();
if (!ui::ResourceBundle::HasSharedInstance())
ui::ResourceBundle::InitSharedInstanceWithLocale(
"en-US", NULL, ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES);
compositor_deps_.reset(new FakeCompositorDependencies);
mock_process_.reset(new MockRenderProcess);
ViewMsg_New_Params view_params;
view_params.opener_frame_route_id = MSG_ROUTING_NONE;
view_params.window_was_created_with_opener = false;
view_params.renderer_preferences = RendererPreferences();
view_params.web_preferences = WebPreferences();
view_params.view_id = kRouteId;
view_params.main_frame_routing_id = kMainFrameRouteId;
view_params.surface_id = kSurfaceId;
view_params.session_storage_namespace_id = kInvalidSessionStorageNamespaceId;
view_params.swapped_out = false;
view_params.replicated_frame_state = FrameReplicationState();
view_params.proxy_routing_id = MSG_ROUTING_NONE;
view_params.hidden = false;
view_params.never_visible = false;
view_params.next_page_id = 1;
view_params.initial_size = *InitialSizeParams();
view_params.enable_auto_resize = false;
view_params.min_size = gfx::Size();
view_params.max_size = gfx::Size();
#if !defined(OS_IOS)
InitializeMojo();
#endif
RenderViewImpl* view =
RenderViewImpl::Create(compositor_deps_.get(), view_params, false);
view_ = view;
}
| 171,695 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: AccessibilityExpanded AXNodeObject::isExpanded() const {
if (getNode() && isHTMLSummaryElement(*getNode())) {
if (getNode()->parentNode() &&
isHTMLDetailsElement(getNode()->parentNode()))
return toElement(getNode()->parentNode())->hasAttribute(openAttr)
? ExpandedExpanded
: ExpandedCollapsed;
}
const AtomicString& expanded = getAttribute(aria_expandedAttr);
if (equalIgnoringCase(expanded, "true"))
return ExpandedExpanded;
if (equalIgnoringCase(expanded, "false"))
return ExpandedCollapsed;
return ExpandedUndefined;
}
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 | AccessibilityExpanded AXNodeObject::isExpanded() const {
if (getNode() && isHTMLSummaryElement(*getNode())) {
if (getNode()->parentNode() &&
isHTMLDetailsElement(getNode()->parentNode()))
return toElement(getNode()->parentNode())->hasAttribute(openAttr)
? ExpandedExpanded
: ExpandedCollapsed;
}
const AtomicString& expanded = getAttribute(aria_expandedAttr);
if (equalIgnoringASCIICase(expanded, "true"))
return ExpandedExpanded;
if (equalIgnoringASCIICase(expanded, "false"))
return ExpandedCollapsed;
return ExpandedUndefined;
}
| 171,915 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
unsigned char* cp = (unsigned char*) cp0;
assert((cc%stride)==0);
if (cc > stride) {
/*
* Pipeline the most common cases.
*/
if (stride == 3) {
unsigned int cr = cp[0];
unsigned int cg = cp[1];
unsigned int cb = cp[2];
cc -= 3;
cp += 3;
while (cc>0) {
cp[0] = (unsigned char) ((cr += cp[0]) & 0xff);
cp[1] = (unsigned char) ((cg += cp[1]) & 0xff);
cp[2] = (unsigned char) ((cb += cp[2]) & 0xff);
cc -= 3;
cp += 3;
}
} else if (stride == 4) {
unsigned int cr = cp[0];
unsigned int cg = cp[1];
unsigned int cb = cp[2];
unsigned int ca = cp[3];
cc -= 4;
cp += 4;
while (cc>0) {
cp[0] = (unsigned char) ((cr += cp[0]) & 0xff);
cp[1] = (unsigned char) ((cg += cp[1]) & 0xff);
cp[2] = (unsigned char) ((cb += cp[2]) & 0xff);
cp[3] = (unsigned char) ((ca += cp[3]) & 0xff);
cc -= 4;
cp += 4;
}
} else {
cc -= stride;
do {
REPEAT4(stride, cp[stride] =
(unsigned char) ((cp[stride] + *cp) & 0xff); cp++)
cc -= stride;
} while (cc>0);
}
}
}
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 | horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
unsigned char* cp = (unsigned char*) cp0;
if((cc%stride)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horAcc8",
"%s", "(cc%stride)!=0");
return 0;
}
if (cc > stride) {
/*
* Pipeline the most common cases.
*/
if (stride == 3) {
unsigned int cr = cp[0];
unsigned int cg = cp[1];
unsigned int cb = cp[2];
cc -= 3;
cp += 3;
while (cc>0) {
cp[0] = (unsigned char) ((cr += cp[0]) & 0xff);
cp[1] = (unsigned char) ((cg += cp[1]) & 0xff);
cp[2] = (unsigned char) ((cb += cp[2]) & 0xff);
cc -= 3;
cp += 3;
}
} else if (stride == 4) {
unsigned int cr = cp[0];
unsigned int cg = cp[1];
unsigned int cb = cp[2];
unsigned int ca = cp[3];
cc -= 4;
cp += 4;
while (cc>0) {
cp[0] = (unsigned char) ((cr += cp[0]) & 0xff);
cp[1] = (unsigned char) ((cg += cp[1]) & 0xff);
cp[2] = (unsigned char) ((cb += cp[2]) & 0xff);
cp[3] = (unsigned char) ((ca += cp[3]) & 0xff);
cc -= 4;
cp += 4;
}
} else {
cc -= stride;
do {
REPEAT4(stride, cp[stride] =
(unsigned char) ((cp[stride] + *cp) & 0xff); cp++)
cc -= stride;
} while (cc>0);
}
}
return 1;
}
| 166,884 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: userauth_hostbased(struct ssh *ssh)
{
Authctxt *authctxt = ssh->authctxt;
struct sshbuf *b;
struct sshkey *key = NULL;
char *pkalg, *cuser, *chost;
u_char *pkblob, *sig;
size_t alen, blen, slen;
int r, pktype, authenticated = 0;
if (!authctxt->valid) {
debug2("%s: disabled because of invalid user", __func__);
return 0;
}
/* XXX use sshkey_froms() */
if ((r = sshpkt_get_cstring(ssh, &pkalg, &alen)) != 0 ||
(r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 ||
(r = sshpkt_get_cstring(ssh, &chost, NULL)) != 0 ||
(r = sshpkt_get_cstring(ssh, &cuser, NULL)) != 0 ||
(r = sshpkt_get_string(ssh, &sig, &slen)) != 0)
fatal("%s: packet parsing: %s", __func__, ssh_err(r));
debug("%s: cuser %s chost %s pkalg %s slen %zu", __func__,
cuser, chost, pkalg, slen);
#ifdef DEBUG_PK
debug("signature:");
sshbuf_dump_data(sig, siglen, stderr);
#endif
pktype = sshkey_type_from_name(pkalg);
if (pktype == KEY_UNSPEC) {
/* this is perfectly legal */
logit("%s: unsupported public key algorithm: %s",
__func__, pkalg);
goto done;
}
if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
error("%s: key_from_blob: %s", __func__, ssh_err(r));
goto done;
}
if (key == NULL) {
error("%s: cannot decode key: %s", __func__, pkalg);
goto done;
}
if (key->type != pktype) {
error("%s: type mismatch for decoded key "
"(received %d, expected %d)", __func__, key->type, pktype);
goto done;
}
if (sshkey_type_plain(key->type) == KEY_RSA &&
(ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
error("Refusing RSA key because peer uses unsafe "
"signature format");
goto done;
}
if (match_pattern_list(pkalg, options.hostbased_key_types, 0) != 1) {
logit("%s: key type %s not in HostbasedAcceptedKeyTypes",
__func__, sshkey_type(key));
goto done;
}
if ((b = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
/* reconstruct packet */
if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 ||
(r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
(r = sshbuf_put_cstring(b, authctxt->user)) != 0 ||
(r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
(r = sshbuf_put_cstring(b, "hostbased")) != 0 ||
(r = sshbuf_put_string(b, pkalg, alen)) != 0 ||
(r = sshbuf_put_string(b, pkblob, blen)) != 0 ||
(r = sshbuf_put_cstring(b, chost)) != 0 ||
(r = sshbuf_put_cstring(b, cuser)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
#ifdef DEBUG_PK
sshbuf_dump(b, stderr);
#endif
auth2_record_info(authctxt,
"client user \"%.100s\", client host \"%.100s\"", cuser, chost);
/* test for allowed key and correct signature */
authenticated = 0;
if (PRIVSEP(hostbased_key_allowed(authctxt->pw, cuser, chost, key)) &&
PRIVSEP(sshkey_verify(key, sig, slen,
sshbuf_ptr(b), sshbuf_len(b), pkalg, ssh->compat)) == 0)
authenticated = 1;
auth2_record_key(authctxt, authenticated, key);
sshbuf_free(b);
done:
debug2("%s: authenticated %d", __func__, authenticated);
sshkey_free(key);
free(pkalg);
free(pkblob);
free(cuser);
free(chost);
free(sig);
return authenticated;
}
Commit Message: delay bailout for invalid authenticating user until after the packet
containing the request has been fully parsed. Reported by Dariusz Tytko
and Michał Sajdak; ok deraadt
CWE ID: CWE-200 | userauth_hostbased(struct ssh *ssh)
{
Authctxt *authctxt = ssh->authctxt;
struct sshbuf *b;
struct sshkey *key = NULL;
char *pkalg, *cuser, *chost;
u_char *pkblob, *sig;
size_t alen, blen, slen;
int r, pktype, authenticated = 0;
/* XXX use sshkey_froms() */
if ((r = sshpkt_get_cstring(ssh, &pkalg, &alen)) != 0 ||
(r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 ||
(r = sshpkt_get_cstring(ssh, &chost, NULL)) != 0 ||
(r = sshpkt_get_cstring(ssh, &cuser, NULL)) != 0 ||
(r = sshpkt_get_string(ssh, &sig, &slen)) != 0)
fatal("%s: packet parsing: %s", __func__, ssh_err(r));
debug("%s: cuser %s chost %s pkalg %s slen %zu", __func__,
cuser, chost, pkalg, slen);
#ifdef DEBUG_PK
debug("signature:");
sshbuf_dump_data(sig, siglen, stderr);
#endif
pktype = sshkey_type_from_name(pkalg);
if (pktype == KEY_UNSPEC) {
/* this is perfectly legal */
logit("%s: unsupported public key algorithm: %s",
__func__, pkalg);
goto done;
}
if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
error("%s: key_from_blob: %s", __func__, ssh_err(r));
goto done;
}
if (key == NULL) {
error("%s: cannot decode key: %s", __func__, pkalg);
goto done;
}
if (key->type != pktype) {
error("%s: type mismatch for decoded key "
"(received %d, expected %d)", __func__, key->type, pktype);
goto done;
}
if (sshkey_type_plain(key->type) == KEY_RSA &&
(ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
error("Refusing RSA key because peer uses unsafe "
"signature format");
goto done;
}
if (match_pattern_list(pkalg, options.hostbased_key_types, 0) != 1) {
logit("%s: key type %s not in HostbasedAcceptedKeyTypes",
__func__, sshkey_type(key));
goto done;
}
if (!authctxt->valid || authctxt->user == NULL) {
debug2("%s: disabled because of invalid user", __func__);
goto done;
}
if ((b = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
/* reconstruct packet */
if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 ||
(r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
(r = sshbuf_put_cstring(b, authctxt->user)) != 0 ||
(r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
(r = sshbuf_put_cstring(b, "hostbased")) != 0 ||
(r = sshbuf_put_string(b, pkalg, alen)) != 0 ||
(r = sshbuf_put_string(b, pkblob, blen)) != 0 ||
(r = sshbuf_put_cstring(b, chost)) != 0 ||
(r = sshbuf_put_cstring(b, cuser)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
#ifdef DEBUG_PK
sshbuf_dump(b, stderr);
#endif
auth2_record_info(authctxt,
"client user \"%.100s\", client host \"%.100s\"", cuser, chost);
/* test for allowed key and correct signature */
authenticated = 0;
if (PRIVSEP(hostbased_key_allowed(authctxt->pw, cuser, chost, key)) &&
PRIVSEP(sshkey_verify(key, sig, slen,
sshbuf_ptr(b), sshbuf_len(b), pkalg, ssh->compat)) == 0)
authenticated = 1;
auth2_record_key(authctxt, authenticated, key);
sshbuf_free(b);
done:
debug2("%s: authenticated %d", __func__, authenticated);
sshkey_free(key);
free(pkalg);
free(pkblob);
free(cuser);
free(chost);
free(sig);
return authenticated;
}
| 169,105 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH)));
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 | ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH)));
return NULL;
}
| 167,791 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void m_stop(struct seq_file *m, void *v)
{
struct proc_maps_private *priv = m->private;
struct vm_area_struct *vma = v;
vma_stop(priv, vma);
if (priv->task)
put_task_struct(priv->task);
}
Commit Message: proc: fix oops on invalid /proc/<pid>/maps access
When m_start returns an error, the seq_file logic will still call m_stop
with that error entry, so we'd better make sure that we check it before
using it as a vma.
Introduced by commit ec6fd8a4355c ("report errors in /proc/*/*map*
sanely"), which replaced NULL with various ERR_PTR() cases.
(On ia64, you happen to get a unaligned fault instead of a page fault,
since the address used is generally some random error code like -EPERM)
Reported-by: Anca Emanuel <[email protected]>
Reported-by: Tony Luck <[email protected]>
Cc: Al Viro <[email protected]>
Cc: Américo Wang <[email protected]>
Cc: Stephen Wilson <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-20 | static void m_stop(struct seq_file *m, void *v)
{
struct proc_maps_private *priv = m->private;
struct vm_area_struct *vma = v;
if (!IS_ERR(vma))
vma_stop(priv, vma);
if (priv->task)
put_task_struct(priv->task);
}
| 165,744 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int prepare_binprm(struct linux_binprm *bprm)
{
struct inode *inode = file_inode(bprm->file);
umode_t mode = inode->i_mode;
int retval;
/* clear any previous set[ug]id data from a previous binary */
bprm->cred->euid = current_euid();
bprm->cred->egid = current_egid();
if (!(bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID) &&
!task_no_new_privs(current) &&
kuid_has_mapping(bprm->cred->user_ns, inode->i_uid) &&
kgid_has_mapping(bprm->cred->user_ns, inode->i_gid)) {
/* Set-uid? */
if (mode & S_ISUID) {
bprm->per_clear |= PER_CLEAR_ON_SETID;
bprm->cred->euid = inode->i_uid;
}
/* Set-gid? */
/*
* If setgid is set but no group execute bit then this
* is a candidate for mandatory locking, not a setgid
* executable.
*/
if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
bprm->per_clear |= PER_CLEAR_ON_SETID;
bprm->cred->egid = inode->i_gid;
}
}
/* fill in binprm security blob */
retval = security_bprm_set_creds(bprm);
if (retval)
return retval;
bprm->cred_prepared = 1;
memset(bprm->buf, 0, BINPRM_BUF_SIZE);
return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE);
}
Commit Message: fs: take i_mutex during prepare_binprm for set[ug]id executables
This prevents a race between chown() and execve(), where chowning a
setuid-user binary to root would momentarily make the binary setuid
root.
This patch was mostly written by Linus Torvalds.
Signed-off-by: Jann Horn <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362 | int prepare_binprm(struct linux_binprm *bprm)
{
int retval;
bprm_fill_uid(bprm);
/* fill in binprm security blob */
retval = security_bprm_set_creds(bprm);
if (retval)
return retval;
bprm->cred_prepared = 1;
memset(bprm->buf, 0, BINPRM_BUF_SIZE);
return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE);
}
| 166,625 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HostCache::ClearForHosts(
const base::Callback<bool(const std::string&)>& host_filter) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (host_filter.is_null()) {
clear();
return;
}
base::TimeTicks now = base::TimeTicks::Now();
for (EntryMap::iterator it = entries_.begin(); it != entries_.end();) {
EntryMap::iterator next_it = std::next(it);
if (host_filter.Run(it->first.hostname)) {
RecordErase(ERASE_CLEAR, now, it->second);
entries_.erase(it);
}
it = next_it;
}
}
Commit Message: Add PersistenceDelegate to HostCache
PersistenceDelegate is a new interface for persisting the contents of
the HostCache. This commit includes the interface itself, the logic in
HostCache for interacting with it, and a mock implementation of the
interface for testing. It does not include support for immediate data
removal since that won't be needed for the currently planned use case.
BUG=605149
Review-Url: https://codereview.chromium.org/2943143002
Cr-Commit-Position: refs/heads/master@{#481015}
CWE ID: | void HostCache::ClearForHosts(
const base::Callback<bool(const std::string&)>& host_filter) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (host_filter.is_null()) {
clear();
return;
}
bool changed = false;
base::TimeTicks now = base::TimeTicks::Now();
for (EntryMap::iterator it = entries_.begin(); it != entries_.end();) {
EntryMap::iterator next_it = std::next(it);
if (host_filter.Run(it->first.hostname)) {
RecordErase(ERASE_CLEAR, now, it->second);
entries_.erase(it);
changed = true;
}
it = next_it;
}
if (delegate_ && changed)
delegate_->ScheduleWrite();
}
| 172,006 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static scoped_refptr<ScrollPaintPropertyNode> CreateScroll(
scoped_refptr<const ScrollPaintPropertyNode> parent,
const ScrollPaintPropertyNode::State& state_arg,
MainThreadScrollingReasons main_thread_scrolling_reasons =
MainThreadScrollingReason::kNotScrollingOnMain,
CompositorElementId scroll_element_id = CompositorElementId()) {
ScrollPaintPropertyNode::State state = state_arg;
state.main_thread_scrolling_reasons = main_thread_scrolling_reasons;
state.compositor_element_id = scroll_element_id;
return ScrollPaintPropertyNode::Create(parent, std::move(state));
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | static scoped_refptr<ScrollPaintPropertyNode> CreateScroll(
static std::unique_ptr<ScrollPaintPropertyNode> CreateScroll(
const ScrollPaintPropertyNode& parent,
const ScrollPaintPropertyNode::State& state_arg,
MainThreadScrollingReasons main_thread_scrolling_reasons =
MainThreadScrollingReason::kNotScrollingOnMain,
CompositorElementId scroll_element_id = CompositorElementId()) {
ScrollPaintPropertyNode::State state = state_arg;
state.main_thread_scrolling_reasons = main_thread_scrolling_reasons;
state.compositor_element_id = scroll_element_id;
return ScrollPaintPropertyNode::Create(parent, std::move(state));
}
| 171,819 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val)
{
ulonglong tmp;
if (jas_iccgetuint(in, 2, &tmp))
return -1;
*val = tmp;
return 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val)
{
jas_ulonglong tmp;
if (jas_iccgetuint(in, 2, &tmp))
return -1;
*val = tmp;
return 0;
}
| 168,685 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed 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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintWebViewHelper::Print(WebKit::WebFrame* frame, WebKit::WebNode* node) {
if (print_web_view_)
return;
scoped_ptr<PrepareFrameAndViewForPrint> prepare;
if (!InitPrintSettingsAndPrepareFrame(frame, node, &prepare))
return; // Failed to init print page settings.
int expected_page_count = 0;
bool use_browser_overlays = true;
expected_page_count = prepare->GetExpectedPageCount();
if (expected_page_count)
use_browser_overlays = prepare->ShouldUseBrowserOverlays();
prepare.reset();
if (!expected_page_count) {
DidFinishPrinting(OK); // Release resources and fail silently.
return;
}
if (!GetPrintSettingsFromUser(frame, expected_page_count,
use_browser_overlays)) {
DidFinishPrinting(OK); // Release resources and fail silently.
return;
}
if (!RenderPagesForPrint(frame, node, NULL)) {
LOG(ERROR) << "RenderPagesForPrint failed";
DidFinishPrinting(FAIL_PRINT);
}
ResetScriptedPrintCount();
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void PrintWebViewHelper::Print(WebKit::WebFrame* frame, WebKit::WebNode* node) {
if (print_web_view_)
return;
scoped_ptr<PrepareFrameAndViewForPrint> prepare;
if (!InitPrintSettingsAndPrepareFrame(frame, node, &prepare)) {
DidFinishPrinting(FAIL_PRINT);
return; // Failed to init print page settings.
}
int expected_page_count = 0;
bool use_browser_overlays = true;
expected_page_count = prepare->GetExpectedPageCount();
if (expected_page_count)
use_browser_overlays = prepare->ShouldUseBrowserOverlays();
prepare.reset();
if (!expected_page_count) {
DidFinishPrinting(OK); // Release resources and fail silently.
return;
}
if (!GetPrintSettingsFromUser(frame, expected_page_count,
use_browser_overlays)) {
DidFinishPrinting(OK); // Release resources and fail silently.
return;
}
if (!RenderPagesForPrint(frame, node, NULL)) {
LOG(ERROR) << "RenderPagesForPrint failed";
DidFinishPrinting(FAIL_PRINT);
}
ResetScriptedPrintCount();
}
| 170,263 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: pimv2_print(netdissect_options *ndo,
register const u_char *bp, register u_int len, const u_char *bp2)
{
register const u_char *ep;
register const struct pim *pim = (const struct pim *)bp;
int advance;
enum checksum_status cksum_status;
ep = (const u_char *)ndo->ndo_snapend;
if (bp >= ep)
return;
if (ep > bp + len)
ep = bp + len;
ND_TCHECK(pim->pim_rsv);
pimv2_addr_len = pim->pim_rsv;
if (pimv2_addr_len != 0)
ND_PRINT((ndo, ", RFC2117-encoding"));
ND_PRINT((ndo, ", cksum 0x%04x ", EXTRACT_16BITS(&pim->pim_cksum)));
if (EXTRACT_16BITS(&pim->pim_cksum) == 0) {
ND_PRINT((ndo, "(unverified)"));
} else {
if (PIM_TYPE(pim->pim_typever) == PIMV2_TYPE_REGISTER) {
/*
* The checksum only covers the packet header,
* not the encapsulated packet.
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, 8);
if (cksum_status == INCORRECT) {
/*
* To quote RFC 4601, "For interoperability
* reasons, a message carrying a checksum
* calculated over the entire PIM Register
* message should also be accepted."
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, len);
}
} else {
/*
* The checksum covers the entire packet.
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, len);
}
switch (cksum_status) {
case CORRECT:
ND_PRINT((ndo, "(correct)"));
break;
case INCORRECT:
ND_PRINT((ndo, "(incorrect)"));
break;
case UNVERIFIED:
ND_PRINT((ndo, "(unverified)"));
break;
}
}
switch (PIM_TYPE(pim->pim_typever)) {
case PIMV2_TYPE_HELLO:
{
uint16_t otype, olen;
bp += 4;
while (bp < ep) {
ND_TCHECK2(bp[0], 4);
otype = EXTRACT_16BITS(&bp[0]);
olen = EXTRACT_16BITS(&bp[2]);
ND_TCHECK2(bp[0], 4 + olen);
ND_PRINT((ndo, "\n\t %s Option (%u), length %u, Value: ",
tok2str(pimv2_hello_option_values, "Unknown", otype),
otype,
olen));
bp += 4;
switch (otype) {
case PIMV2_HELLO_OPTION_HOLDTIME:
if (olen != 2) {
ND_PRINT((ndo, "ERROR: Option Length != 2 Bytes (%u)", olen));
} else {
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
}
break;
case PIMV2_HELLO_OPTION_LANPRUNEDELAY:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
char t_bit;
uint16_t lan_delay, override_interval;
lan_delay = EXTRACT_16BITS(bp);
override_interval = EXTRACT_16BITS(bp+2);
t_bit = (lan_delay & 0x8000)? 1 : 0;
lan_delay &= ~0x8000;
ND_PRINT((ndo, "\n\t T-bit=%d, LAN delay %dms, Override interval %dms",
t_bit, lan_delay, override_interval));
}
break;
case PIMV2_HELLO_OPTION_DR_PRIORITY_OLD:
case PIMV2_HELLO_OPTION_DR_PRIORITY:
switch (olen) {
case 0:
ND_PRINT((ndo, "Bi-Directional Capability (Old)"));
break;
case 4:
ND_PRINT((ndo, "%u", EXTRACT_32BITS(bp)));
break;
default:
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
break;
}
break;
case PIMV2_HELLO_OPTION_GENID:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
ND_PRINT((ndo, "0x%08x", EXTRACT_32BITS(bp)));
}
break;
case PIMV2_HELLO_OPTION_REFRESH_CAP:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
ND_PRINT((ndo, "v%d", *bp));
if (*(bp+1) != 0) {
ND_PRINT((ndo, ", interval "));
unsigned_relts_print(ndo, *(bp+1));
}
if (EXTRACT_16BITS(bp+2) != 0) {
ND_PRINT((ndo, " ?0x%04x?", EXTRACT_16BITS(bp+2)));
}
}
break;
case PIMV2_HELLO_OPTION_BIDIR_CAP:
break;
case PIMV2_HELLO_OPTION_ADDRESS_LIST_OLD:
case PIMV2_HELLO_OPTION_ADDRESS_LIST:
if (ndo->ndo_vflag > 1) {
const u_char *ptr = bp;
while (ptr < (bp+olen)) {
ND_PRINT((ndo, "\n\t "));
advance = pimv2_addr_print(ndo, ptr, pimv2_unicast, 0);
if (advance < 0) {
ND_PRINT((ndo, "..."));
break;
}
ptr += advance;
}
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, bp, "\n\t ", olen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1)
print_unknown_data(ndo, bp, "\n\t ", olen);
bp += olen;
}
break;
}
case PIMV2_TYPE_REGISTER:
{
const struct ip *ip;
ND_TCHECK2(*(bp + 4), PIMV2_REGISTER_FLAG_LEN);
ND_PRINT((ndo, ", Flags [ %s ]\n\t",
tok2str(pimv2_register_flag_values,
"none",
EXTRACT_32BITS(bp+4))));
bp += 8; len -= 8;
/* encapsulated multicast packet */
ip = (const struct ip *)bp;
switch (IP_V(ip)) {
case 0: /* Null header */
ND_PRINT((ndo, "IP-Null-header %s > %s",
ipaddr_string(ndo, &ip->ip_src),
ipaddr_string(ndo, &ip->ip_dst)));
break;
case 4: /* IPv4 */
ip_print(ndo, bp, len);
break;
case 6: /* IPv6 */
ip6_print(ndo, bp, len);
break;
default:
ND_PRINT((ndo, "IP ver %d", IP_V(ip)));
break;
}
break;
}
case PIMV2_TYPE_REGISTER_STOP:
bp += 4; len -= 4;
if (bp >= ep)
break;
ND_PRINT((ndo, " group="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp >= ep)
break;
ND_PRINT((ndo, " source="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
break;
case PIMV2_TYPE_JOIN_PRUNE:
case PIMV2_TYPE_GRAFT:
case PIMV2_TYPE_GRAFT_ACK:
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |PIM Ver| Type | Addr length | Checksum |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Unicast-Upstream Neighbor Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Reserved | Num groups | Holdtime |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Multicast Group Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Number of Joined Sources | Number of Pruned Sources |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Joined Source Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Joined Source Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Pruned Source Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Pruned Source Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Multicast Group Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
{
uint8_t ngroup;
uint16_t holdtime;
uint16_t njoin;
uint16_t nprune;
int i, j;
bp += 4; len -= 4;
if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/
if (bp >= ep)
break;
ND_PRINT((ndo, ", upstream-neighbor: "));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
}
if (bp + 4 > ep)
break;
ngroup = bp[1];
holdtime = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, "\n\t %u group(s)", ngroup));
if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/
ND_PRINT((ndo, ", holdtime: "));
if (holdtime == 0xffff)
ND_PRINT((ndo, "infinite"));
else
unsigned_relts_print(ndo, holdtime);
}
bp += 4; len -= 4;
for (i = 0; i < ngroup; i++) {
if (bp >= ep)
goto jp_done;
ND_PRINT((ndo, "\n\t group #%u: ", i+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
if (bp + 4 > ep) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
njoin = EXTRACT_16BITS(&bp[0]);
nprune = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, ", joined sources: %u, pruned sources: %u", njoin, nprune));
bp += 4; len -= 4;
for (j = 0; j < njoin; j++) {
ND_PRINT((ndo, "\n\t joined source #%u: ", j+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
}
for (j = 0; j < nprune; j++) {
ND_PRINT((ndo, "\n\t pruned source #%u: ", j+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
}
}
jp_done:
break;
}
case PIMV2_TYPE_BOOTSTRAP:
{
int i, j, frpcnt;
bp += 4;
/* Fragment Tag, Hash Mask len, and BSR-priority */
if (bp + sizeof(uint16_t) >= ep) break;
ND_PRINT((ndo, " tag=%x", EXTRACT_16BITS(bp)));
bp += sizeof(uint16_t);
if (bp >= ep) break;
ND_PRINT((ndo, " hashmlen=%d", bp[0]));
if (bp + 1 >= ep) break;
ND_PRINT((ndo, " BSRprio=%d", bp[1]));
bp += 2;
/* Encoded-Unicast-BSR-Address */
if (bp >= ep) break;
ND_PRINT((ndo, " BSR="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
for (i = 0; bp < ep; i++) {
/* Encoded-Group Address */
ND_PRINT((ndo, " (group%d: ", i));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0))
< 0) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
bp += advance;
/* RP-Count, Frag RP-Cnt, and rsvd */
if (bp >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, " RPcnt=%d", bp[0]));
if (bp + 1 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, " FRPcnt=%d", frpcnt = bp[1]));
bp += 4;
for (j = 0; j < frpcnt && bp < ep; j++) {
/* each RP info */
ND_PRINT((ndo, " RP%d=", j));
if ((advance = pimv2_addr_print(ndo, bp,
pimv2_unicast,
0)) < 0) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
bp += advance;
if (bp + 1 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, ",holdtime="));
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
if (bp + 2 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, ",prio=%d", bp[2]));
bp += 4;
}
ND_PRINT((ndo, ")"));
}
bs_done:
break;
}
case PIMV2_TYPE_ASSERT:
bp += 4; len -= 4;
if (bp >= ep)
break;
ND_PRINT((ndo, " group="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp >= ep)
break;
ND_PRINT((ndo, " src="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp + 8 > ep)
break;
if (bp[0] & 0x80)
ND_PRINT((ndo, " RPT"));
ND_PRINT((ndo, " pref=%u", EXTRACT_32BITS(&bp[0]) & 0x7fffffff));
ND_PRINT((ndo, " metric=%u", EXTRACT_32BITS(&bp[4])));
break;
case PIMV2_TYPE_CANDIDATE_RP:
{
int i, pfxcnt;
bp += 4;
/* Prefix-Cnt, Priority, and Holdtime */
if (bp >= ep) break;
ND_PRINT((ndo, " prefix-cnt=%d", bp[0]));
pfxcnt = bp[0];
if (bp + 1 >= ep) break;
ND_PRINT((ndo, " prio=%d", bp[1]));
if (bp + 3 >= ep) break;
ND_PRINT((ndo, " holdtime="));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));
bp += 4;
/* Encoded-Unicast-RP-Address */
if (bp >= ep) break;
ND_PRINT((ndo, " RP="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
/* Encoded-Group Addresses */
for (i = 0; i < pfxcnt && bp < ep; i++) {
ND_PRINT((ndo, " Group%d=", i));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0))
< 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
}
break;
}
case PIMV2_TYPE_PRUNE_REFRESH:
ND_PRINT((ndo, " src="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_PRINT((ndo, " grp="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_PRINT((ndo, " forwarder="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_TCHECK2(bp[0], 2);
ND_PRINT((ndo, " TUNR "));
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
break;
default:
ND_PRINT((ndo, " [type %d]", PIM_TYPE(pim->pim_typever)));
break;
}
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
}
Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks.
Use ND_TCHECK macros to do bounds checking, and add length checks before
the bounds checks.
Add a bounds check that the review process found was missing.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
Update one test output file to reflect the changes.
CWE ID: CWE-125 | pimv2_print(netdissect_options *ndo,
register const u_char *bp, register u_int len, const u_char *bp2)
{
register const u_char *ep;
register const struct pim *pim = (const struct pim *)bp;
int advance;
enum checksum_status cksum_status;
int pimv2_addr_len;
ep = (const u_char *)ndo->ndo_snapend;
if (bp >= ep)
return;
if (ep > bp + len)
ep = bp + len;
if (len < 2)
goto trunc;
ND_TCHECK(pim->pim_rsv);
pimv2_addr_len = pim->pim_rsv;
if (pimv2_addr_len != 0)
ND_PRINT((ndo, ", RFC2117-encoding"));
if (len < 4)
goto trunc;
ND_TCHECK(pim->pim_cksum);
ND_PRINT((ndo, ", cksum 0x%04x ", EXTRACT_16BITS(&pim->pim_cksum)));
if (EXTRACT_16BITS(&pim->pim_cksum) == 0) {
ND_PRINT((ndo, "(unverified)"));
} else {
if (PIM_TYPE(pim->pim_typever) == PIMV2_TYPE_REGISTER) {
/*
* The checksum only covers the packet header,
* not the encapsulated packet.
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, 8);
if (cksum_status == INCORRECT) {
/*
* To quote RFC 4601, "For interoperability
* reasons, a message carrying a checksum
* calculated over the entire PIM Register
* message should also be accepted."
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, len);
}
} else {
/*
* The checksum covers the entire packet.
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, len);
}
switch (cksum_status) {
case CORRECT:
ND_PRINT((ndo, "(correct)"));
break;
case INCORRECT:
ND_PRINT((ndo, "(incorrect)"));
break;
case UNVERIFIED:
ND_PRINT((ndo, "(unverified)"));
break;
}
}
bp += 4;
len -= 4;
switch (PIM_TYPE(pim->pim_typever)) {
case PIMV2_TYPE_HELLO:
{
uint16_t otype, olen;
while (len > 0) {
if (len < 4)
goto trunc;
ND_TCHECK2(bp[0], 4);
otype = EXTRACT_16BITS(&bp[0]);
olen = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, "\n\t %s Option (%u), length %u, Value: ",
tok2str(pimv2_hello_option_values, "Unknown", otype),
otype,
olen));
bp += 4;
len -= 4;
if (len < olen)
goto trunc;
ND_TCHECK2(bp[0], olen);
switch (otype) {
case PIMV2_HELLO_OPTION_HOLDTIME:
if (olen != 2) {
ND_PRINT((ndo, "ERROR: Option Length != 2 Bytes (%u)", olen));
} else {
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
}
break;
case PIMV2_HELLO_OPTION_LANPRUNEDELAY:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
char t_bit;
uint16_t lan_delay, override_interval;
lan_delay = EXTRACT_16BITS(bp);
override_interval = EXTRACT_16BITS(bp+2);
t_bit = (lan_delay & 0x8000)? 1 : 0;
lan_delay &= ~0x8000;
ND_PRINT((ndo, "\n\t T-bit=%d, LAN delay %dms, Override interval %dms",
t_bit, lan_delay, override_interval));
}
break;
case PIMV2_HELLO_OPTION_DR_PRIORITY_OLD:
case PIMV2_HELLO_OPTION_DR_PRIORITY:
switch (olen) {
case 0:
ND_PRINT((ndo, "Bi-Directional Capability (Old)"));
break;
case 4:
ND_PRINT((ndo, "%u", EXTRACT_32BITS(bp)));
break;
default:
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
break;
}
break;
case PIMV2_HELLO_OPTION_GENID:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
ND_PRINT((ndo, "0x%08x", EXTRACT_32BITS(bp)));
}
break;
case PIMV2_HELLO_OPTION_REFRESH_CAP:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
ND_PRINT((ndo, "v%d", *bp));
if (*(bp+1) != 0) {
ND_PRINT((ndo, ", interval "));
unsigned_relts_print(ndo, *(bp+1));
}
if (EXTRACT_16BITS(bp+2) != 0) {
ND_PRINT((ndo, " ?0x%04x?", EXTRACT_16BITS(bp+2)));
}
}
break;
case PIMV2_HELLO_OPTION_BIDIR_CAP:
break;
case PIMV2_HELLO_OPTION_ADDRESS_LIST_OLD:
case PIMV2_HELLO_OPTION_ADDRESS_LIST:
if (ndo->ndo_vflag > 1) {
const u_char *ptr = bp;
u_int plen = len;
while (ptr < (bp+olen)) {
ND_PRINT((ndo, "\n\t "));
advance = pimv2_addr_print(ndo, ptr, plen, pimv2_unicast, pimv2_addr_len, 0);
if (advance < 0)
goto trunc;
ptr += advance;
plen -= advance;
}
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, bp, "\n\t ", olen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1)
print_unknown_data(ndo, bp, "\n\t ", olen);
bp += olen;
len -= olen;
}
break;
}
case PIMV2_TYPE_REGISTER:
{
const struct ip *ip;
if (len < 4)
goto trunc;
ND_TCHECK2(*bp, PIMV2_REGISTER_FLAG_LEN);
ND_PRINT((ndo, ", Flags [ %s ]\n\t",
tok2str(pimv2_register_flag_values,
"none",
EXTRACT_32BITS(bp))));
bp += 4; len -= 4;
/* encapsulated multicast packet */
if (len == 0)
goto trunc;
ip = (const struct ip *)bp;
ND_TCHECK(ip->ip_vhl);
switch (IP_V(ip)) {
case 0: /* Null header */
ND_TCHECK(ip->ip_dst);
ND_PRINT((ndo, "IP-Null-header %s > %s",
ipaddr_string(ndo, &ip->ip_src),
ipaddr_string(ndo, &ip->ip_dst)));
break;
case 4: /* IPv4 */
ip_print(ndo, bp, len);
break;
case 6: /* IPv6 */
ip6_print(ndo, bp, len);
break;
default:
ND_PRINT((ndo, "IP ver %d", IP_V(ip)));
break;
}
break;
}
case PIMV2_TYPE_REGISTER_STOP:
ND_PRINT((ndo, " group="));
if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0)
goto trunc;
bp += advance; len -= advance;
ND_PRINT((ndo, " source="));
if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0)
goto trunc;
bp += advance; len -= advance;
break;
case PIMV2_TYPE_JOIN_PRUNE:
case PIMV2_TYPE_GRAFT:
case PIMV2_TYPE_GRAFT_ACK:
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |PIM Ver| Type | Addr length | Checksum |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Unicast-Upstream Neighbor Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Reserved | Num groups | Holdtime |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Multicast Group Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Number of Joined Sources | Number of Pruned Sources |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Joined Source Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Joined Source Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Pruned Source Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Pruned Source Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Multicast Group Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
{
uint8_t ngroup;
uint16_t holdtime;
uint16_t njoin;
uint16_t nprune;
int i, j;
if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/
ND_PRINT((ndo, ", upstream-neighbor: "));
if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0)
goto trunc;
bp += advance; len -= advance;
}
if (len < 4)
goto trunc;
ND_TCHECK2(*bp, 4);
ngroup = bp[1];
holdtime = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, "\n\t %u group(s)", ngroup));
if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/
ND_PRINT((ndo, ", holdtime: "));
if (holdtime == 0xffff)
ND_PRINT((ndo, "infinite"));
else
unsigned_relts_print(ndo, holdtime);
}
bp += 4; len -= 4;
for (i = 0; i < ngroup; i++) {
ND_PRINT((ndo, "\n\t group #%u: ", i+1));
if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0)
goto trunc;
bp += advance; len -= advance;
if (len < 4)
goto trunc;
ND_TCHECK2(*bp, 4);
njoin = EXTRACT_16BITS(&bp[0]);
nprune = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, ", joined sources: %u, pruned sources: %u", njoin, nprune));
bp += 4; len -= 4;
for (j = 0; j < njoin; j++) {
ND_PRINT((ndo, "\n\t joined source #%u: ", j+1));
if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_source, pimv2_addr_len, 0)) < 0)
goto trunc;
bp += advance; len -= advance;
}
for (j = 0; j < nprune; j++) {
ND_PRINT((ndo, "\n\t pruned source #%u: ", j+1));
if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_source, pimv2_addr_len, 0)) < 0)
goto trunc;
bp += advance; len -= advance;
}
}
break;
}
case PIMV2_TYPE_BOOTSTRAP:
{
int i, j, frpcnt;
/* Fragment Tag, Hash Mask len, and BSR-priority */
if (len < 2)
goto trunc;
ND_TCHECK_16BITS(bp);
ND_PRINT((ndo, " tag=%x", EXTRACT_16BITS(bp)));
bp += 2;
len -= 2;
if (len < 1)
goto trunc;
ND_TCHECK(bp[0]);
ND_PRINT((ndo, " hashmlen=%d", bp[0]));
if (len < 2)
goto trunc;
ND_TCHECK(bp[2]);
ND_PRINT((ndo, " BSRprio=%d", bp[1]));
bp += 2;
len -= 2;
/* Encoded-Unicast-BSR-Address */
ND_PRINT((ndo, " BSR="));
if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0)
goto trunc;
bp += advance;
len -= advance;
for (i = 0; bp < ep; i++) {
/* Encoded-Group Address */
ND_PRINT((ndo, " (group%d: ", i));
if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0)
goto trunc;
bp += advance;
len -= advance;
/* RP-Count, Frag RP-Cnt, and rsvd */
if (len < 1)
goto trunc;
ND_TCHECK(bp[0]);
ND_PRINT((ndo, " RPcnt=%d", bp[0]));
if (len < 2)
goto trunc;
ND_TCHECK(bp[1]);
ND_PRINT((ndo, " FRPcnt=%d", frpcnt = bp[1]));
if (len < 4)
goto trunc;
bp += 4;
len -= 4;
for (j = 0; j < frpcnt && bp < ep; j++) {
/* each RP info */
ND_PRINT((ndo, " RP%d=", j));
if ((advance = pimv2_addr_print(ndo, bp, len,
pimv2_unicast,
pimv2_addr_len,
0)) < 0)
goto trunc;
bp += advance;
len -= advance;
if (len < 2)
goto trunc;
ND_TCHECK_16BITS(bp);
ND_PRINT((ndo, ",holdtime="));
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
if (len < 3)
goto trunc;
ND_TCHECK(bp[2]);
ND_PRINT((ndo, ",prio=%d", bp[2]));
if (len < 4)
goto trunc;
bp += 4;
len -= 4;
}
ND_PRINT((ndo, ")"));
}
break;
}
case PIMV2_TYPE_ASSERT:
ND_PRINT((ndo, " group="));
if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0)
goto trunc;
bp += advance; len -= advance;
ND_PRINT((ndo, " src="));
if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0)
goto trunc;
bp += advance; len -= advance;
if (len < 8)
goto trunc;
ND_TCHECK2(*bp, 8);
if (bp[0] & 0x80)
ND_PRINT((ndo, " RPT"));
ND_PRINT((ndo, " pref=%u", EXTRACT_32BITS(&bp[0]) & 0x7fffffff));
ND_PRINT((ndo, " metric=%u", EXTRACT_32BITS(&bp[4])));
break;
case PIMV2_TYPE_CANDIDATE_RP:
{
int i, pfxcnt;
/* Prefix-Cnt, Priority, and Holdtime */
if (len < 1)
goto trunc;
ND_TCHECK(bp[0]);
ND_PRINT((ndo, " prefix-cnt=%d", bp[0]));
pfxcnt = bp[0];
if (len < 2)
goto trunc;
ND_TCHECK(bp[1]);
ND_PRINT((ndo, " prio=%d", bp[1]));
if (len < 4)
goto trunc;
ND_TCHECK_16BITS(&bp[2]);
ND_PRINT((ndo, " holdtime="));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));
bp += 4;
len -= 4;
/* Encoded-Unicast-RP-Address */
ND_PRINT((ndo, " RP="));
if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0)
goto trunc;
bp += advance;
len -= advance;
/* Encoded-Group Addresses */
for (i = 0; i < pfxcnt && bp < ep; i++) {
ND_PRINT((ndo, " Group%d=", i));
if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0)
goto trunc;
bp += advance;
len -= advance;
}
break;
}
case PIMV2_TYPE_PRUNE_REFRESH:
ND_PRINT((ndo, " src="));
if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0)
goto trunc;
bp += advance;
len -= advance;
ND_PRINT((ndo, " grp="));
if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0)
goto trunc;
bp += advance;
len -= advance;
ND_PRINT((ndo, " forwarder="));
if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0)
goto trunc;
bp += advance;
len -= advance;
if (len < 2)
goto trunc;
ND_TCHECK_16BITS(bp);
ND_PRINT((ndo, " TUNR "));
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
break;
default:
ND_PRINT((ndo, " [type %d]", PIM_TYPE(pim->pim_typever)));
break;
}
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
}
| 167,858 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: nfs4_open_revalidate(struct inode *dir, struct dentry *dentry, int openflags, struct nameidata *nd)
{
struct path path = {
.mnt = nd->path.mnt,
.dentry = dentry,
};
struct rpc_cred *cred;
struct nfs4_state *state;
cred = rpc_lookup_cred();
if (IS_ERR(cred))
return PTR_ERR(cred);
state = nfs4_do_open(dir, &path, openflags, NULL, cred);
put_rpccred(cred);
if (IS_ERR(state)) {
switch (PTR_ERR(state)) {
case -EPERM:
case -EACCES:
case -EDQUOT:
case -ENOSPC:
case -EROFS:
lookup_instantiate_filp(nd, (struct dentry *)state, NULL);
return 1;
default:
goto out_drop;
}
}
if (state->inode == dentry->d_inode) {
nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
nfs4_intent_set_file(nd, &path, state);
return 1;
}
nfs4_close_sync(&path, state, openflags);
out_drop:
d_drop(dentry);
return 0;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | nfs4_open_revalidate(struct inode *dir, struct dentry *dentry, int openflags, struct nameidata *nd)
{
struct path path = {
.mnt = nd->path.mnt,
.dentry = dentry,
};
struct rpc_cred *cred;
struct nfs4_state *state;
fmode_t fmode = openflags & (FMODE_READ | FMODE_WRITE);
cred = rpc_lookup_cred();
if (IS_ERR(cred))
return PTR_ERR(cred);
state = nfs4_do_open(dir, &path, fmode, openflags, NULL, cred);
put_rpccred(cred);
if (IS_ERR(state)) {
switch (PTR_ERR(state)) {
case -EPERM:
case -EACCES:
case -EDQUOT:
case -ENOSPC:
case -EROFS:
lookup_instantiate_filp(nd, (struct dentry *)state, NULL);
return 1;
default:
goto out_drop;
}
}
if (state->inode == dentry->d_inode) {
nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
nfs4_intent_set_file(nd, &path, state, fmode);
return 1;
}
nfs4_close_sync(&path, state, fmode);
out_drop:
d_drop(dentry);
return 0;
}
| 165,699 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WebRTCSessionDescriptionDescriptor MockWebRTCPeerConnectionHandler::localDescription()
{
return m_localDescription;
}
Commit Message: Unreviewed, rolling out r127612, r127660, and r127664.
http://trac.webkit.org/changeset/127612
http://trac.webkit.org/changeset/127660
http://trac.webkit.org/changeset/127664
https://bugs.webkit.org/show_bug.cgi?id=95920
Source/Platform:
* Platform.gypi:
* chromium/public/WebRTCPeerConnectionHandler.h:
(WebKit):
(WebRTCPeerConnectionHandler):
* chromium/public/WebRTCVoidRequest.h: Removed.
Source/WebCore:
* CMakeLists.txt:
* GNUmakefile.list.am:
* Modules/mediastream/RTCErrorCallback.h:
(WebCore):
(RTCErrorCallback):
* Modules/mediastream/RTCErrorCallback.idl:
* Modules/mediastream/RTCPeerConnection.cpp:
(WebCore::RTCPeerConnection::createOffer):
* Modules/mediastream/RTCPeerConnection.h:
(WebCore):
(RTCPeerConnection):
* Modules/mediastream/RTCPeerConnection.idl:
* Modules/mediastream/RTCSessionDescriptionCallback.h:
(WebCore):
(RTCSessionDescriptionCallback):
* Modules/mediastream/RTCSessionDescriptionCallback.idl:
* Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp:
(WebCore::RTCSessionDescriptionRequestImpl::create):
(WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl):
(WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded):
(WebCore::RTCSessionDescriptionRequestImpl::requestFailed):
(WebCore::RTCSessionDescriptionRequestImpl::clear):
* Modules/mediastream/RTCSessionDescriptionRequestImpl.h:
(RTCSessionDescriptionRequestImpl):
* Modules/mediastream/RTCVoidRequestImpl.cpp: Removed.
* Modules/mediastream/RTCVoidRequestImpl.h: Removed.
* WebCore.gypi:
* platform/chromium/support/WebRTCVoidRequest.cpp: Removed.
* platform/mediastream/RTCPeerConnectionHandler.cpp:
(RTCPeerConnectionHandlerDummy):
(WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy):
* platform/mediastream/RTCPeerConnectionHandler.h:
(WebCore):
(WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler):
(RTCPeerConnectionHandler):
(WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler):
* platform/mediastream/RTCVoidRequest.h: Removed.
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp:
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h:
(RTCPeerConnectionHandlerChromium):
Tools:
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp:
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask):
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::createOffer):
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h:
(MockWebRTCPeerConnectionHandler):
(SuccessCallbackTask):
(FailureCallbackTask):
LayoutTests:
* fast/mediastream/RTCPeerConnection-createOffer.html:
* fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-localDescription.html: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed.
git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | WebRTCSessionDescriptionDescriptor MockWebRTCPeerConnectionHandler::localDescription()
| 170,360 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void show_object(struct object *object, struct strbuf *path,
const char *last, void *data)
{
struct bitmap *base = data;
bitmap_set(base, find_object_pos(object->oid.hash));
mark_as_seen(object);
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[email protected]>
CWE ID: CWE-119 | static void show_object(struct object *object, struct strbuf *path,
static void show_object(struct object *object, const char *name, void *data)
{
struct bitmap *base = data;
bitmap_set(base, find_object_pos(object->oid.hash));
mark_as_seen(object);
}
| 167,421 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WaitForCallback() {
if (!use_audio_thread_) {
base::RunLoop().RunUntilIdle();
return;
}
media::WaitableMessageLoopEvent event;
audio_thread_.task_runner()->PostTaskAndReply(
FROM_HERE, base::Bind(&base::DoNothing), event.GetClosure());
event.RunAndWait();
base::RunLoop().RunUntilIdle();
}
Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one.
BUG=672468
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Review-Url: https://codereview.chromium.org/2692203003
Cr-Commit-Position: refs/heads/master@{#450939}
CWE ID: | void WaitForCallback() {
if (!use_audio_thread_) {
base::RunLoop().RunUntilIdle();
return;
}
WaitableMessageLoopEvent event;
audio_thread_.task_runner()->PostTaskAndReply(
FROM_HERE, base::Bind(&base::DoNothing), event.GetClosure());
event.RunAndWait();
base::RunLoop().RunUntilIdle();
}
| 171,990 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FakePlatformSensorProvider::CreateSensorInternal(
mojom::SensorType type,
mojo::ScopedSharedBufferMapping mapping,
const CreateSensorCallback& callback) {
DCHECK(type >= mojom::SensorType::FIRST && type <= mojom::SensorType::LAST);
auto sensor =
base::MakeRefCounted<FakePlatformSensor>(type, std::move(mapping), this);
DoCreateSensorInternal(type, std::move(sensor), callback);
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732 | void FakePlatformSensorProvider::CreateSensorInternal(
mojom::SensorType type,
SensorReadingSharedBuffer* reading_buffer,
const CreateSensorCallback& callback) {
DCHECK(type >= mojom::SensorType::FIRST && type <= mojom::SensorType::LAST);
auto sensor =
base::MakeRefCounted<FakePlatformSensor>(type, reading_buffer, this);
DoCreateSensorInternal(type, std::move(sensor), callback);
}
| 172,818 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int do_devinfo_ioctl(struct comedi_device *dev,
struct comedi_devinfo __user *arg,
struct file *file)
{
struct comedi_devinfo devinfo;
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_subdevice *read_subdev =
comedi_get_read_subdevice(dev_file_info);
struct comedi_subdevice *write_subdev =
comedi_get_write_subdevice(dev_file_info);
memset(&devinfo, 0, sizeof(devinfo));
/* fill devinfo structure */
devinfo.version_code = COMEDI_VERSION_CODE;
devinfo.n_subdevs = dev->n_subdevices;
memcpy(devinfo.driver_name, dev->driver->driver_name, COMEDI_NAMELEN);
memcpy(devinfo.board_name, dev->board_name, COMEDI_NAMELEN);
if (read_subdev)
devinfo.read_subdevice = read_subdev - dev->subdevices;
else
devinfo.read_subdevice = -1;
if (write_subdev)
devinfo.write_subdevice = write_subdev - dev->subdevices;
else
devinfo.write_subdevice = -1;
if (copy_to_user(arg, &devinfo, sizeof(struct comedi_devinfo)))
return -EFAULT;
return 0;
}
Commit Message: staging: comedi: fix infoleak to userspace
driver_name and board_name are pointers to strings, not buffers of size
COMEDI_NAMELEN. Copying COMEDI_NAMELEN bytes of a string containing
less than COMEDI_NAMELEN-1 bytes would leak some unrelated bytes.
Signed-off-by: Vasiliy Kulikov <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-200 | static int do_devinfo_ioctl(struct comedi_device *dev,
struct comedi_devinfo __user *arg,
struct file *file)
{
struct comedi_devinfo devinfo;
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_subdevice *read_subdev =
comedi_get_read_subdevice(dev_file_info);
struct comedi_subdevice *write_subdev =
comedi_get_write_subdevice(dev_file_info);
memset(&devinfo, 0, sizeof(devinfo));
/* fill devinfo structure */
devinfo.version_code = COMEDI_VERSION_CODE;
devinfo.n_subdevs = dev->n_subdevices;
strlcpy(devinfo.driver_name, dev->driver->driver_name, COMEDI_NAMELEN);
strlcpy(devinfo.board_name, dev->board_name, COMEDI_NAMELEN);
if (read_subdev)
devinfo.read_subdevice = read_subdev - dev->subdevices;
else
devinfo.read_subdevice = -1;
if (write_subdev)
devinfo.write_subdevice = write_subdev - dev->subdevices;
else
devinfo.write_subdevice = -1;
if (copy_to_user(arg, &devinfo, sizeof(struct comedi_devinfo)))
return -EFAULT;
return 0;
}
| 166,557 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ParamTraits<SkBitmap>::Write(base::Pickle* m, const SkBitmap& p) {
size_t fixed_size = sizeof(SkBitmap_Data);
SkBitmap_Data bmp_data;
bmp_data.InitSkBitmapDataForTransfer(p);
m->WriteData(reinterpret_cast<const char*>(&bmp_data),
static_cast<int>(fixed_size));
size_t pixel_size = p.computeByteSize();
m->WriteData(reinterpret_cast<const char*>(p.getPixels()),
static_cast<int>(pixel_size));
}
Commit Message: Update IPC ParamTraits for SkBitmap to follow best practices.
Using memcpy() to serialize a POD struct is highly discouraged. Just use
the standard IPC param traits macros for doing it.
Bug: 779428
Change-Id: I48f52c1f5c245ba274d595829ed92e8b3cb41334
Reviewed-on: https://chromium-review.googlesource.com/899649
Reviewed-by: Tom Sepez <[email protected]>
Commit-Queue: Daniel Cheng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#534562}
CWE ID: CWE-125 | void ParamTraits<SkBitmap>::Write(base::Pickle* m, const SkBitmap& p) {
WriteParam(m, p.info());
size_t pixel_size = p.computeByteSize();
m->WriteData(reinterpret_cast<const char*>(p.getPixels()),
static_cast<int>(pixel_size));
}
| 172,895 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PlatformSensor::UpdateSharedBuffer(const SensorReading& reading) {
ReadingBuffer* buffer =
static_cast<ReadingBuffer*>(shared_buffer_mapping_.get());
auto& seqlock = buffer->seqlock.value();
seqlock.WriteBegin();
buffer->reading = reading;
seqlock.WriteEnd();
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732 | void PlatformSensor::UpdateSharedBuffer(const SensorReading& reading) {
ReadingBuffer* buffer = reading_buffer_;
auto& seqlock = buffer->seqlock.value();
seqlock.WriteBegin();
buffer->reading = reading;
seqlock.WriteEnd();
}
| 172,823 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RunFwdTxfm(int16_t *in, int16_t *out, int stride) {
fwd_txfm_(in, out, stride, tx_type_);
}
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 RunFwdTxfm(int16_t *in, int16_t *out, int stride) {
void RunFwdTxfm(int16_t *in, tran_low_t *out, int stride) {
fwd_txfm_(in, out, stride, tx_type_);
}
| 174,522 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: uint8_t* output() const {
return output_ + BorderTop() * kOuterBlockSize + BorderLeft();
}
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 | uint8_t* output() const {
uint8_t *output() const {
#if CONFIG_VP9_HIGHBITDEPTH
if (UUT_->use_highbd_ == 0) {
return output_ + BorderTop() * kOuterBlockSize + BorderLeft();
} else {
return CONVERT_TO_BYTEPTR(output16_ + BorderTop() * kOuterBlockSize +
BorderLeft());
}
#else
return output_ + BorderTop() * kOuterBlockSize + BorderLeft();
#endif
}
uint8_t *output_ref() const {
#if CONFIG_VP9_HIGHBITDEPTH
if (UUT_->use_highbd_ == 0) {
return output_ref_ + BorderTop() * kOuterBlockSize + BorderLeft();
} else {
return CONVERT_TO_BYTEPTR(output16_ref_ + BorderTop() * kOuterBlockSize +
BorderLeft());
}
#else
return output_ref_ + BorderTop() * kOuterBlockSize + BorderLeft();
#endif
}
uint16_t lookup(uint8_t *list, int index) const {
#if CONFIG_VP9_HIGHBITDEPTH
if (UUT_->use_highbd_ == 0) {
return list[index];
} else {
return CONVERT_TO_SHORTPTR(list)[index];
}
#else
return list[index];
#endif
}
void assign_val(uint8_t *list, int index, uint16_t val) const {
#if CONFIG_VP9_HIGHBITDEPTH
if (UUT_->use_highbd_ == 0) {
list[index] = (uint8_t) val;
} else {
CONVERT_TO_SHORTPTR(list)[index] = val;
}
#else
list[index] = (uint8_t) val;
#endif
}
void wrapper_filter_average_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) {
#if CONFIG_VP9_HIGHBITDEPTH
if (UUT_->use_highbd_ == 0) {
filter_average_block2d_8_c(src_ptr, src_stride, HFilter, VFilter,
dst_ptr, dst_stride, output_width,
output_height);
} else {
highbd_filter_average_block2d_8_c(CONVERT_TO_SHORTPTR(src_ptr),
src_stride, HFilter, VFilter,
CONVERT_TO_SHORTPTR(dst_ptr),
dst_stride, output_width, output_height,
UUT_->use_highbd_);
}
#else
filter_average_block2d_8_c(src_ptr, src_stride, HFilter, VFilter,
dst_ptr, dst_stride, output_width,
output_height);
#endif
}
void wrapper_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) {
#if CONFIG_VP9_HIGHBITDEPTH
if (UUT_->use_highbd_ == 0) {
filter_block2d_8_c(src_ptr, src_stride, HFilter, VFilter,
dst_ptr, dst_stride, output_width, output_height);
} else {
highbd_filter_block2d_8_c(CONVERT_TO_SHORTPTR(src_ptr), src_stride,
HFilter, VFilter,
CONVERT_TO_SHORTPTR(dst_ptr), dst_stride,
output_width, output_height, UUT_->use_highbd_);
}
#else
filter_block2d_8_c(src_ptr, src_stride, HFilter, VFilter,
dst_ptr, dst_stride, output_width, output_height);
#endif
}
| 174,511 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void veth_setup(struct net_device *dev)
{
ether_setup(dev);
dev->netdev_ops = &veth_netdev_ops;
dev->ethtool_ops = &veth_ethtool_ops;
dev->features |= NETIF_F_LLTX;
dev->destructor = veth_dev_free;
dev->hw_features = NETIF_F_NO_CSUM | NETIF_F_SG | NETIF_F_RXCSUM;
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264 | static void veth_setup(struct net_device *dev)
{
ether_setup(dev);
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
dev->netdev_ops = &veth_netdev_ops;
dev->ethtool_ops = &veth_ethtool_ops;
dev->features |= NETIF_F_LLTX;
dev->destructor = veth_dev_free;
dev->hw_features = NETIF_F_NO_CSUM | NETIF_F_SG | NETIF_F_RXCSUM;
}
| 165,731 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) {
xmlParserInputPtr input;
xmlBufferPtr buf;
int l, c;
int count = 0;
if ((ctxt == NULL) || (entity == NULL) ||
((entity->etype != XML_EXTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY)) ||
(entity->content != NULL)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlLoadEntityContent parameter error");
return(-1);
}
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"Reading %s entity content input\n", entity->name);
buf = xmlBufferCreate();
if (buf == NULL) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlLoadEntityContent parameter error");
return(-1);
}
input = xmlNewEntityInputStream(ctxt, entity);
if (input == NULL) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlLoadEntityContent input error");
xmlBufferFree(buf);
return(-1);
}
/*
* Push the entity as the current input, read char by char
* saving to the buffer until the end of the entity or an error
*/
if (xmlPushInput(ctxt, input) < 0) {
xmlBufferFree(buf);
return(-1);
}
GROW;
c = CUR_CHAR(l);
while ((ctxt->input == input) && (ctxt->input->cur < ctxt->input->end) &&
(IS_CHAR(c))) {
xmlBufferAdd(buf, ctxt->input->cur, l);
if (count++ > 100) {
count = 0;
GROW;
}
NEXTL(l);
c = CUR_CHAR(l);
}
if ((ctxt->input == input) && (ctxt->input->cur >= ctxt->input->end)) {
xmlPopInput(ctxt);
} else if (!IS_CHAR(c)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlLoadEntityContent: invalid char value %d\n",
c);
xmlBufferFree(buf);
return(-1);
}
entity->content = buf->content;
buf->content = NULL;
xmlBufferFree(buf);
return(0);
}
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 | xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) {
xmlParserInputPtr input;
xmlBufferPtr buf;
int l, c;
int count = 0;
if ((ctxt == NULL) || (entity == NULL) ||
((entity->etype != XML_EXTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY)) ||
(entity->content != NULL)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlLoadEntityContent parameter error");
return(-1);
}
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"Reading %s entity content input\n", entity->name);
buf = xmlBufferCreate();
if (buf == NULL) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlLoadEntityContent parameter error");
return(-1);
}
input = xmlNewEntityInputStream(ctxt, entity);
if (input == NULL) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlLoadEntityContent input error");
xmlBufferFree(buf);
return(-1);
}
/*
* Push the entity as the current input, read char by char
* saving to the buffer until the end of the entity or an error
*/
if (xmlPushInput(ctxt, input) < 0) {
xmlBufferFree(buf);
return(-1);
}
GROW;
c = CUR_CHAR(l);
while ((ctxt->input == input) && (ctxt->input->cur < ctxt->input->end) &&
(IS_CHAR(c))) {
xmlBufferAdd(buf, ctxt->input->cur, l);
if (count++ > 100) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF) {
xmlBufferFree(buf);
return(-1);
}
}
NEXTL(l);
c = CUR_CHAR(l);
}
if ((ctxt->input == input) && (ctxt->input->cur >= ctxt->input->end)) {
xmlPopInput(ctxt);
} else if (!IS_CHAR(c)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlLoadEntityContent: invalid char value %d\n",
c);
xmlBufferFree(buf);
return(-1);
}
entity->content = buf->content;
buf->content = NULL;
xmlBufferFree(buf);
return(0);
}
| 171,269 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void php_mcrypt_do_crypt(char* cipher, const char *key, int key_len, const char *data, int data_len, char *mode, const char *iv, int iv_len, int argc, int dencrypt, zval* return_value TSRMLS_DC) /* {{{ */
{
char *cipher_dir_string;
char *module_dir_string;
int block_size, max_key_length, use_key_length, i, count, iv_size;
unsigned long int data_size;
int *key_length_sizes;
char *key_s = NULL, *iv_s;
char *data_s;
MCRYPT td;
MCRYPT_GET_INI
td = mcrypt_module_open(cipher, cipher_dir_string, mode, module_dir_string);
if (td == MCRYPT_FAILED) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
RETURN_FALSE;
}
/* Checking for key-length */
max_key_length = mcrypt_enc_get_key_size(td);
if (key_len > max_key_length) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Size of key is too large for this algorithm");
}
key_length_sizes = mcrypt_enc_get_supported_key_sizes(td, &count);
if (count == 0 && key_length_sizes == NULL) { /* all lengths 1 - k_l_s = OK */
use_key_length = key_len;
key_s = emalloc(use_key_length);
memset(key_s, 0, use_key_length);
memcpy(key_s, key, use_key_length);
} else if (count == 1) { /* only m_k_l = OK */
key_s = emalloc(key_length_sizes[0]);
memset(key_s, 0, key_length_sizes[0]);
memcpy(key_s, key, MIN(key_len, key_length_sizes[0]));
use_key_length = key_length_sizes[0];
} else { /* dertermine smallest supported key > length of requested key */
use_key_length = max_key_length; /* start with max key length */
for (i = 0; i < count; i++) {
if (key_length_sizes[i] >= key_len &&
key_length_sizes[i] < use_key_length)
{
use_key_length = key_length_sizes[i];
}
}
key_s = emalloc(use_key_length);
memset(key_s, 0, use_key_length);
memcpy(key_s, key, MIN(key_len, use_key_length));
}
mcrypt_free (key_length_sizes);
/* Check IV */
iv_s = NULL;
iv_size = mcrypt_enc_get_iv_size (td);
/* IV is required */
if (mcrypt_enc_mode_has_iv(td) == 1) {
if (argc == 5) {
if (iv_size != iv_len) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_IV_WRONG_SIZE);
} else {
iv_s = emalloc(iv_size + 1);
memcpy(iv_s, iv, iv_size);
}
} else if (argc == 4) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to use an empty IV, which is NOT recommend");
iv_s = emalloc(iv_size + 1);
memset(iv_s, 0, iv_size + 1);
}
}
/* Check blocksize */
if (mcrypt_enc_is_block_mode(td) == 1) { /* It's a block algorithm */
block_size = mcrypt_enc_get_block_size(td);
data_size = (((data_len - 1) / block_size) + 1) * block_size;
data_s = emalloc(data_size);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
} else { /* It's not a block algorithm */
data_size = data_len;
data_s = emalloc(data_size);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
}
if (mcrypt_generic_init(td, key_s, use_key_length, iv_s) < 0) {
php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Mcrypt initialisation failed");
RETURN_FALSE;
}
if (dencrypt == MCRYPT_ENCRYPT) {
mcrypt_generic(td, data_s, data_size);
} else {
mdecrypt_generic(td, data_s, data_size);
}
RETVAL_STRINGL(data_s, data_size, 1);
/* freeing vars */
mcrypt_generic_end(td);
if (key_s != NULL) {
efree (key_s);
}
if (iv_s != NULL) {
efree (iv_s);
}
efree (data_s);
}
/* }}} */
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190 | static void php_mcrypt_do_crypt(char* cipher, const char *key, int key_len, const char *data, int data_len, char *mode, const char *iv, int iv_len, int argc, int dencrypt, zval* return_value TSRMLS_DC) /* {{{ */
{
char *cipher_dir_string;
char *module_dir_string;
int block_size, max_key_length, use_key_length, i, count, iv_size;
unsigned long int data_size;
int *key_length_sizes;
char *key_s = NULL, *iv_s;
char *data_s;
MCRYPT td;
MCRYPT_GET_INI
td = mcrypt_module_open(cipher, cipher_dir_string, mode, module_dir_string);
if (td == MCRYPT_FAILED) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
RETURN_FALSE;
}
/* Checking for key-length */
max_key_length = mcrypt_enc_get_key_size(td);
if (key_len > max_key_length) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Size of key is too large for this algorithm");
}
key_length_sizes = mcrypt_enc_get_supported_key_sizes(td, &count);
if (count == 0 && key_length_sizes == NULL) { /* all lengths 1 - k_l_s = OK */
use_key_length = key_len;
key_s = emalloc(use_key_length);
memset(key_s, 0, use_key_length);
memcpy(key_s, key, use_key_length);
} else if (count == 1) { /* only m_k_l = OK */
key_s = emalloc(key_length_sizes[0]);
memset(key_s, 0, key_length_sizes[0]);
memcpy(key_s, key, MIN(key_len, key_length_sizes[0]));
use_key_length = key_length_sizes[0];
} else { /* dertermine smallest supported key > length of requested key */
use_key_length = max_key_length; /* start with max key length */
for (i = 0; i < count; i++) {
if (key_length_sizes[i] >= key_len &&
key_length_sizes[i] < use_key_length)
{
use_key_length = key_length_sizes[i];
}
}
key_s = emalloc(use_key_length);
memset(key_s, 0, use_key_length);
memcpy(key_s, key, MIN(key_len, use_key_length));
}
mcrypt_free (key_length_sizes);
/* Check IV */
iv_s = NULL;
iv_size = mcrypt_enc_get_iv_size (td);
/* IV is required */
if (mcrypt_enc_mode_has_iv(td) == 1) {
if (argc == 5) {
if (iv_size != iv_len) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_IV_WRONG_SIZE);
} else {
iv_s = emalloc(iv_size + 1);
memcpy(iv_s, iv, iv_size);
}
} else if (argc == 4) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to use an empty IV, which is NOT recommend");
iv_s = emalloc(iv_size + 1);
memset(iv_s, 0, iv_size + 1);
}
}
/* Check blocksize */
if (mcrypt_enc_is_block_mode(td) == 1) { /* It's a block algorithm */
block_size = mcrypt_enc_get_block_size(td);
data_size = (((data_len - 1) / block_size) + 1) * block_size;
data_s = emalloc(data_size);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
} else { /* It's not a block algorithm */
data_size = data_len;
data_s = emalloc(data_size);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
}
if (mcrypt_generic_init(td, key_s, use_key_length, iv_s) < 0) {
php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Mcrypt initialisation failed");
RETURN_FALSE;
}
if (dencrypt == MCRYPT_ENCRYPT) {
mcrypt_generic(td, data_s, data_size);
} else {
mdecrypt_generic(td, data_s, data_size);
}
RETVAL_STRINGL(data_s, data_size, 1);
/* freeing vars */
mcrypt_generic_end(td);
if (key_s != NULL) {
efree (key_s);
}
if (iv_s != NULL) {
efree (iv_s);
}
efree (data_s);
}
/* }}} */
| 167,113 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ImageCapture::SetMediaTrackConstraints(
ScriptPromiseResolver* resolver,
const HeapVector<MediaTrackConstraintSet>& constraints_vector) {
DCHECK_GT(constraints_vector.size(), 0u);
if (!service_) {
resolver->Reject(DOMException::Create(kNotFoundError, kNoServiceError));
return;
}
auto constraints = constraints_vector[0];
if ((constraints.hasWhiteBalanceMode() &&
!capabilities_.hasWhiteBalanceMode()) ||
(constraints.hasExposureMode() && !capabilities_.hasExposureMode()) ||
(constraints.hasFocusMode() && !capabilities_.hasFocusMode()) ||
(constraints.hasExposureCompensation() &&
!capabilities_.hasExposureCompensation()) ||
(constraints.hasColorTemperature() &&
!capabilities_.hasColorTemperature()) ||
(constraints.hasIso() && !capabilities_.hasIso()) ||
(constraints.hasBrightness() && !capabilities_.hasBrightness()) ||
(constraints.hasContrast() && !capabilities_.hasContrast()) ||
(constraints.hasSaturation() && !capabilities_.hasSaturation()) ||
(constraints.hasSharpness() && !capabilities_.hasSharpness()) ||
(constraints.hasZoom() && !capabilities_.hasZoom()) ||
(constraints.hasTorch() && !capabilities_.hasTorch())) {
resolver->Reject(
DOMException::Create(kNotSupportedError, "Unsupported constraint(s)"));
return;
}
auto settings = media::mojom::blink::PhotoSettings::New();
MediaTrackConstraintSet temp_constraints = current_constraints_;
settings->has_white_balance_mode = constraints.hasWhiteBalanceMode() &&
constraints.whiteBalanceMode().IsString();
if (settings->has_white_balance_mode) {
const auto white_balance_mode =
constraints.whiteBalanceMode().GetAsString();
if (capabilities_.whiteBalanceMode().Find(white_balance_mode) ==
kNotFound) {
resolver->Reject(DOMException::Create(kNotSupportedError,
"Unsupported whiteBalanceMode."));
return;
}
temp_constraints.setWhiteBalanceMode(constraints.whiteBalanceMode());
settings->white_balance_mode = ParseMeteringMode(white_balance_mode);
}
settings->has_exposure_mode =
constraints.hasExposureMode() && constraints.exposureMode().IsString();
if (settings->has_exposure_mode) {
const auto exposure_mode = constraints.exposureMode().GetAsString();
if (capabilities_.exposureMode().Find(exposure_mode) == kNotFound) {
resolver->Reject(DOMException::Create(kNotSupportedError,
"Unsupported exposureMode."));
return;
}
temp_constraints.setExposureMode(constraints.exposureMode());
settings->exposure_mode = ParseMeteringMode(exposure_mode);
}
settings->has_focus_mode =
constraints.hasFocusMode() && constraints.focusMode().IsString();
if (settings->has_focus_mode) {
const auto focus_mode = constraints.focusMode().GetAsString();
if (capabilities_.focusMode().Find(focus_mode) == kNotFound) {
resolver->Reject(
DOMException::Create(kNotSupportedError, "Unsupported focusMode."));
return;
}
temp_constraints.setFocusMode(constraints.focusMode());
settings->focus_mode = ParseMeteringMode(focus_mode);
}
if (constraints.hasPointsOfInterest() &&
constraints.pointsOfInterest().IsPoint2DSequence()) {
for (const auto& point :
constraints.pointsOfInterest().GetAsPoint2DSequence()) {
auto mojo_point = media::mojom::blink::Point2D::New();
mojo_point->x = point.x();
mojo_point->y = point.y();
settings->points_of_interest.push_back(std::move(mojo_point));
}
temp_constraints.setPointsOfInterest(constraints.pointsOfInterest());
}
settings->has_exposure_compensation =
constraints.hasExposureCompensation() &&
constraints.exposureCompensation().IsDouble();
if (settings->has_exposure_compensation) {
const auto exposure_compensation =
constraints.exposureCompensation().GetAsDouble();
if (exposure_compensation < capabilities_.exposureCompensation()->min() ||
exposure_compensation > capabilities_.exposureCompensation()->max()) {
resolver->Reject(DOMException::Create(
kNotSupportedError, "exposureCompensation setting out of range"));
return;
}
temp_constraints.setExposureCompensation(
constraints.exposureCompensation());
settings->exposure_compensation = exposure_compensation;
}
settings->has_color_temperature = constraints.hasColorTemperature() &&
constraints.colorTemperature().IsDouble();
if (settings->has_color_temperature) {
const auto color_temperature = constraints.colorTemperature().GetAsDouble();
if (color_temperature < capabilities_.colorTemperature()->min() ||
color_temperature > capabilities_.colorTemperature()->max()) {
resolver->Reject(DOMException::Create(
kNotSupportedError, "colorTemperature setting out of range"));
return;
}
temp_constraints.setColorTemperature(constraints.colorTemperature());
settings->color_temperature = color_temperature;
}
settings->has_iso = constraints.hasIso() && constraints.iso().IsDouble();
if (settings->has_iso) {
const auto iso = constraints.iso().GetAsDouble();
if (iso < capabilities_.iso()->min() || iso > capabilities_.iso()->max()) {
resolver->Reject(
DOMException::Create(kNotSupportedError, "iso setting out of range"));
return;
}
temp_constraints.setIso(constraints.iso());
settings->iso = iso;
}
settings->has_brightness =
constraints.hasBrightness() && constraints.brightness().IsDouble();
if (settings->has_brightness) {
const auto brightness = constraints.brightness().GetAsDouble();
if (brightness < capabilities_.brightness()->min() ||
brightness > capabilities_.brightness()->max()) {
resolver->Reject(DOMException::Create(kNotSupportedError,
"brightness setting out of range"));
return;
}
temp_constraints.setBrightness(constraints.brightness());
settings->brightness = brightness;
}
settings->has_contrast =
constraints.hasContrast() && constraints.contrast().IsDouble();
if (settings->has_contrast) {
const auto contrast = constraints.contrast().GetAsDouble();
if (contrast < capabilities_.contrast()->min() ||
contrast > capabilities_.contrast()->max()) {
resolver->Reject(DOMException::Create(kNotSupportedError,
"contrast setting out of range"));
return;
}
temp_constraints.setContrast(constraints.contrast());
settings->contrast = contrast;
}
settings->has_saturation =
constraints.hasSaturation() && constraints.saturation().IsDouble();
if (settings->has_saturation) {
const auto saturation = constraints.saturation().GetAsDouble();
if (saturation < capabilities_.saturation()->min() ||
saturation > capabilities_.saturation()->max()) {
resolver->Reject(DOMException::Create(kNotSupportedError,
"saturation setting out of range"));
return;
}
temp_constraints.setSaturation(constraints.saturation());
settings->saturation = saturation;
}
settings->has_sharpness =
constraints.hasSharpness() && constraints.sharpness().IsDouble();
if (settings->has_sharpness) {
const auto sharpness = constraints.sharpness().GetAsDouble();
if (sharpness < capabilities_.sharpness()->min() ||
sharpness > capabilities_.sharpness()->max()) {
resolver->Reject(DOMException::Create(kNotSupportedError,
"sharpness setting out of range"));
return;
}
temp_constraints.setSharpness(constraints.sharpness());
settings->sharpness = sharpness;
}
settings->has_zoom = constraints.hasZoom() && constraints.zoom().IsDouble();
if (settings->has_zoom) {
const auto zoom = constraints.zoom().GetAsDouble();
if (zoom < capabilities_.zoom()->min() ||
zoom > capabilities_.zoom()->max()) {
resolver->Reject(DOMException::Create(kNotSupportedError,
"zoom setting out of range"));
return;
}
temp_constraints.setZoom(constraints.zoom());
settings->zoom = zoom;
}
settings->has_torch =
constraints.hasTorch() && constraints.torch().IsBoolean();
if (settings->has_torch) {
const auto torch = constraints.torch().GetAsBoolean();
if (torch && !capabilities_.torch()) {
resolver->Reject(
DOMException::Create(kNotSupportedError, "torch not supported"));
return;
}
temp_constraints.setTorch(constraints.torch());
settings->torch = torch;
}
current_constraints_ = temp_constraints;
service_requests_.insert(resolver);
MediaTrackConstraints resolver_constraints;
resolver_constraints.setAdvanced(constraints_vector);
auto resolver_cb = WTF::Bind(&ImageCapture::ResolveWithMediaTrackConstraints,
WrapPersistent(this), resolver_constraints);
service_->SetOptions(
stream_track_->Component()->Source()->Id(), std::move(settings),
ConvertToBaseCallback(WTF::Bind(
&ImageCapture::OnMojoSetOptions, WrapPersistent(this),
WrapPersistent(resolver), WTF::Passed(std::move(resolver_cb)),
false /* trigger_take_photo */)));
}
Commit Message: Convert MediaTrackConstraints to a ScriptValue
IDLDictionaries such as MediaTrackConstraints should not be stored on
the heap which would happen when binding one as a parameter to a
callback. This change converts the object to a ScriptValue ahead of
time. This is fine because the value will be passed to a
ScriptPromiseResolver that will converted it to a V8 value if it
isn't already.
Bug: 759457
Change-Id: I3009a0f7711cc264aeaae07a36c18a6db8c915c8
Reviewed-on: https://chromium-review.googlesource.com/701358
Reviewed-by: Kentaro Hara <[email protected]>
Commit-Queue: Reilly Grant <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507177}
CWE ID: CWE-416 | void ImageCapture::SetMediaTrackConstraints(
ScriptPromiseResolver* resolver,
const HeapVector<MediaTrackConstraintSet>& constraints_vector) {
DCHECK_GT(constraints_vector.size(), 0u);
if (!service_) {
resolver->Reject(DOMException::Create(kNotFoundError, kNoServiceError));
return;
}
auto constraints = constraints_vector[0];
if ((constraints.hasWhiteBalanceMode() &&
!capabilities_.hasWhiteBalanceMode()) ||
(constraints.hasExposureMode() && !capabilities_.hasExposureMode()) ||
(constraints.hasFocusMode() && !capabilities_.hasFocusMode()) ||
(constraints.hasExposureCompensation() &&
!capabilities_.hasExposureCompensation()) ||
(constraints.hasColorTemperature() &&
!capabilities_.hasColorTemperature()) ||
(constraints.hasIso() && !capabilities_.hasIso()) ||
(constraints.hasBrightness() && !capabilities_.hasBrightness()) ||
(constraints.hasContrast() && !capabilities_.hasContrast()) ||
(constraints.hasSaturation() && !capabilities_.hasSaturation()) ||
(constraints.hasSharpness() && !capabilities_.hasSharpness()) ||
(constraints.hasZoom() && !capabilities_.hasZoom()) ||
(constraints.hasTorch() && !capabilities_.hasTorch())) {
resolver->Reject(
DOMException::Create(kNotSupportedError, "Unsupported constraint(s)"));
return;
}
auto settings = media::mojom::blink::PhotoSettings::New();
MediaTrackConstraintSet temp_constraints = current_constraints_;
settings->has_white_balance_mode = constraints.hasWhiteBalanceMode() &&
constraints.whiteBalanceMode().IsString();
if (settings->has_white_balance_mode) {
const auto white_balance_mode =
constraints.whiteBalanceMode().GetAsString();
if (capabilities_.whiteBalanceMode().Find(white_balance_mode) ==
kNotFound) {
resolver->Reject(DOMException::Create(kNotSupportedError,
"Unsupported whiteBalanceMode."));
return;
}
temp_constraints.setWhiteBalanceMode(constraints.whiteBalanceMode());
settings->white_balance_mode = ParseMeteringMode(white_balance_mode);
}
settings->has_exposure_mode =
constraints.hasExposureMode() && constraints.exposureMode().IsString();
if (settings->has_exposure_mode) {
const auto exposure_mode = constraints.exposureMode().GetAsString();
if (capabilities_.exposureMode().Find(exposure_mode) == kNotFound) {
resolver->Reject(DOMException::Create(kNotSupportedError,
"Unsupported exposureMode."));
return;
}
temp_constraints.setExposureMode(constraints.exposureMode());
settings->exposure_mode = ParseMeteringMode(exposure_mode);
}
settings->has_focus_mode =
constraints.hasFocusMode() && constraints.focusMode().IsString();
if (settings->has_focus_mode) {
const auto focus_mode = constraints.focusMode().GetAsString();
if (capabilities_.focusMode().Find(focus_mode) == kNotFound) {
resolver->Reject(
DOMException::Create(kNotSupportedError, "Unsupported focusMode."));
return;
}
temp_constraints.setFocusMode(constraints.focusMode());
settings->focus_mode = ParseMeteringMode(focus_mode);
}
if (constraints.hasPointsOfInterest() &&
constraints.pointsOfInterest().IsPoint2DSequence()) {
for (const auto& point :
constraints.pointsOfInterest().GetAsPoint2DSequence()) {
auto mojo_point = media::mojom::blink::Point2D::New();
mojo_point->x = point.x();
mojo_point->y = point.y();
settings->points_of_interest.push_back(std::move(mojo_point));
}
temp_constraints.setPointsOfInterest(constraints.pointsOfInterest());
}
settings->has_exposure_compensation =
constraints.hasExposureCompensation() &&
constraints.exposureCompensation().IsDouble();
if (settings->has_exposure_compensation) {
const auto exposure_compensation =
constraints.exposureCompensation().GetAsDouble();
if (exposure_compensation < capabilities_.exposureCompensation()->min() ||
exposure_compensation > capabilities_.exposureCompensation()->max()) {
resolver->Reject(DOMException::Create(
kNotSupportedError, "exposureCompensation setting out of range"));
return;
}
temp_constraints.setExposureCompensation(
constraints.exposureCompensation());
settings->exposure_compensation = exposure_compensation;
}
settings->has_color_temperature = constraints.hasColorTemperature() &&
constraints.colorTemperature().IsDouble();
if (settings->has_color_temperature) {
const auto color_temperature = constraints.colorTemperature().GetAsDouble();
if (color_temperature < capabilities_.colorTemperature()->min() ||
color_temperature > capabilities_.colorTemperature()->max()) {
resolver->Reject(DOMException::Create(
kNotSupportedError, "colorTemperature setting out of range"));
return;
}
temp_constraints.setColorTemperature(constraints.colorTemperature());
settings->color_temperature = color_temperature;
}
settings->has_iso = constraints.hasIso() && constraints.iso().IsDouble();
if (settings->has_iso) {
const auto iso = constraints.iso().GetAsDouble();
if (iso < capabilities_.iso()->min() || iso > capabilities_.iso()->max()) {
resolver->Reject(
DOMException::Create(kNotSupportedError, "iso setting out of range"));
return;
}
temp_constraints.setIso(constraints.iso());
settings->iso = iso;
}
settings->has_brightness =
constraints.hasBrightness() && constraints.brightness().IsDouble();
if (settings->has_brightness) {
const auto brightness = constraints.brightness().GetAsDouble();
if (brightness < capabilities_.brightness()->min() ||
brightness > capabilities_.brightness()->max()) {
resolver->Reject(DOMException::Create(kNotSupportedError,
"brightness setting out of range"));
return;
}
temp_constraints.setBrightness(constraints.brightness());
settings->brightness = brightness;
}
settings->has_contrast =
constraints.hasContrast() && constraints.contrast().IsDouble();
if (settings->has_contrast) {
const auto contrast = constraints.contrast().GetAsDouble();
if (contrast < capabilities_.contrast()->min() ||
contrast > capabilities_.contrast()->max()) {
resolver->Reject(DOMException::Create(kNotSupportedError,
"contrast setting out of range"));
return;
}
temp_constraints.setContrast(constraints.contrast());
settings->contrast = contrast;
}
settings->has_saturation =
constraints.hasSaturation() && constraints.saturation().IsDouble();
if (settings->has_saturation) {
const auto saturation = constraints.saturation().GetAsDouble();
if (saturation < capabilities_.saturation()->min() ||
saturation > capabilities_.saturation()->max()) {
resolver->Reject(DOMException::Create(kNotSupportedError,
"saturation setting out of range"));
return;
}
temp_constraints.setSaturation(constraints.saturation());
settings->saturation = saturation;
}
settings->has_sharpness =
constraints.hasSharpness() && constraints.sharpness().IsDouble();
if (settings->has_sharpness) {
const auto sharpness = constraints.sharpness().GetAsDouble();
if (sharpness < capabilities_.sharpness()->min() ||
sharpness > capabilities_.sharpness()->max()) {
resolver->Reject(DOMException::Create(kNotSupportedError,
"sharpness setting out of range"));
return;
}
temp_constraints.setSharpness(constraints.sharpness());
settings->sharpness = sharpness;
}
settings->has_zoom = constraints.hasZoom() && constraints.zoom().IsDouble();
if (settings->has_zoom) {
const auto zoom = constraints.zoom().GetAsDouble();
if (zoom < capabilities_.zoom()->min() ||
zoom > capabilities_.zoom()->max()) {
resolver->Reject(DOMException::Create(kNotSupportedError,
"zoom setting out of range"));
return;
}
temp_constraints.setZoom(constraints.zoom());
settings->zoom = zoom;
}
settings->has_torch =
constraints.hasTorch() && constraints.torch().IsBoolean();
if (settings->has_torch) {
const auto torch = constraints.torch().GetAsBoolean();
if (torch && !capabilities_.torch()) {
resolver->Reject(
DOMException::Create(kNotSupportedError, "torch not supported"));
return;
}
temp_constraints.setTorch(constraints.torch());
settings->torch = torch;
}
current_constraints_ = temp_constraints;
service_requests_.insert(resolver);
MediaTrackConstraints resolver_constraints;
resolver_constraints.setAdvanced(constraints_vector);
// An IDLDictionaryBase cannot safely be bound into a callback so the
// ScriptValue is created ahead of time. See https://crbug.com/759457.
auto resolver_cb = WTF::Bind(
&ImageCapture::ResolveWithMediaTrackConstraints, WrapPersistent(this),
ScriptValue::From(resolver->GetScriptState(), resolver_constraints));
service_->SetOptions(
stream_track_->Component()->Source()->Id(), std::move(settings),
ConvertToBaseCallback(WTF::Bind(
&ImageCapture::OnMojoSetOptions, WrapPersistent(this),
WrapPersistent(resolver), WTF::Passed(std::move(resolver_cb)),
false /* trigger_take_photo */)));
}
| 172,963 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuVideoDecodeAccelerator::OnDecode(
base::SharedMemoryHandle handle, int32 id, int32 size) {
DCHECK(video_decode_accelerator_.get());
video_decode_accelerator_->Decode(media::BitstreamBuffer(id, handle, size));
}
Commit Message: Sizes going across an IPC should be uint32.
BUG=164946
Review URL: https://chromiumcodereview.appspot.com/11472038
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171944 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuVideoDecodeAccelerator::OnDecode(
base::SharedMemoryHandle handle, int32 id, uint32 size) {
DCHECK(video_decode_accelerator_.get());
video_decode_accelerator_->Decode(media::BitstreamBuffer(id, handle, size));
}
| 171,407 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.