prompt
stringlengths 1.19k
236k
| output
int64 0
1
|
---|---|
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: status_t ESDS::parseESDescriptor(size_t offset, size_t size) {
if (size < 3) {
return ERROR_MALFORMED;
}
offset += 2; // skip ES_ID
size -= 2;
unsigned streamDependenceFlag = mData[offset] & 0x80;
unsigned URL_Flag = mData[offset] & 0x40;
unsigned OCRstreamFlag = mData[offset] & 0x20;
++offset;
--size;
if (streamDependenceFlag) {
offset += 2;
size -= 2;
}
if (URL_Flag) {
if (offset >= size) {
return ERROR_MALFORMED;
}
unsigned URLlength = mData[offset];
offset += URLlength + 1;
size -= URLlength + 1;
}
if (OCRstreamFlag) {
offset += 2;
size -= 2;
if ((offset >= size || mData[offset] != kTag_DecoderConfigDescriptor)
&& offset - 2 < size
&& mData[offset - 2] == kTag_DecoderConfigDescriptor) {
offset -= 2;
size += 2;
ALOGW("Found malformed 'esds' atom, ignoring missing OCR_ES_Id.");
}
}
if (offset >= size) {
return ERROR_MALFORMED;
}
uint8_t tag;
size_t sub_offset, sub_size;
status_t err = skipDescriptorHeader(
offset, size, &tag, &sub_offset, &sub_size);
if (err != OK) {
return err;
}
if (tag != kTag_DecoderConfigDescriptor) {
return ERROR_MALFORMED;
}
err = parseDecoderConfigDescriptor(sub_offset, sub_size);
return err;
}
Commit Message: Fix integer underflow in ESDS processing
Several arithmetic operations within parseESDescriptor could underflow, leading
to an out-of-bounds read operation. Ensure that subtractions from 'size' do not
cause it to wrap around.
Bug: 20139950
(cherry picked from commit 07c0f59d6c48874982d2b5c713487612e5af465a)
Change-Id: I377d21051e07ca654ea1f7037120429d3f71924a
CWE ID: CWE-189
Target: 1
Example 2:
Code: static void JNI_SendTabToSelfAndroidBridge_DeleteAllEntries(
JNIEnv* env,
const JavaParamRef<jobject>& j_profile) {
SendTabToSelfModel* model = GetModel(j_profile);
if (model->IsReady()) {
model->DeleteAllEntries();
}
}
Commit Message: [SendTabToSelf] Added logic to display an infobar for the feature.
This CL is one of many to come. It covers:
* Creation of the infobar from the SendTabToSelfInfoBarController
* Plumbed the call to create the infobar to the native code.
* Open the link when user taps on the link
In follow-up CLs, the following will be done:
* Instantiate the InfobarController in the ChromeActivity
* Listen for Model changes in the Controller
Bug: 949233,963193
Change-Id: I5df1359debb5f0f35c32c2df3b691bf9129cdeb8
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1604406
Reviewed-by: Tommy Nyquist <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Mikel Astiz <[email protected]>
Reviewed-by: sebsg <[email protected]>
Reviewed-by: Jeffrey Cohen <[email protected]>
Reviewed-by: Matthew Jones <[email protected]>
Commit-Queue: Tanya Gupta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660854}
CWE ID: CWE-190
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ExtensionViewGuest::ExtensionViewGuest(WebContents* owner_web_contents)
: GuestView<ExtensionViewGuest>(owner_web_contents) {}
Commit Message: Make extensions use a correct same-origin check.
GURL::GetOrigin does not do the right thing for all types of URLs.
BUG=573317
Review URL: https://codereview.chromium.org/1658913002
Cr-Commit-Position: refs/heads/master@{#373381}
CWE ID: CWE-284
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WT_Interpolate (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 phaseFrac;
EAS_I32 acc0;
const EAS_SAMPLE *pSamples;
const EAS_SAMPLE *loopEnd;
EAS_I32 samp1;
EAS_I32 samp2;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
pOutputBuffer = pWTIntFrame->pAudioBuffer;
loopEnd = (const EAS_SAMPLE*) pWTVoice->loopEnd + 1;
pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum;
/*lint -e{713} truncation is OK */
phaseFrac = pWTVoice->phaseFrac;
phaseInc = pWTIntFrame->frame.phaseIncrement;
/* fetch adjacent samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
while (numSamples--) {
/* linear interpolation */
acc0 = samp2 - samp1;
acc0 = acc0 * phaseFrac;
/*lint -e{704} <avoid divide>*/
acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS);
/* save new output sample in buffer */
/*lint -e{704} <avoid divide>*/
*pOutputBuffer++ = (EAS_I16)(acc0 >> 2);
/* increment phase */
phaseFrac += phaseInc;
/*lint -e{704} <avoid divide>*/
acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS;
/* next sample */
if (acc0 > 0) {
/* advance sample pointer */
pSamples += acc0;
phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK);
/* check for loop end */
acc0 = (EAS_I32) (pSamples - loopEnd);
if (acc0 >= 0)
pSamples = (const EAS_SAMPLE*) pWTVoice->loopStart + acc0;
/* fetch new samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
}
}
/* save pointer and phase */
pWTVoice->phaseAccum = (EAS_U32) pSamples;
pWTVoice->phaseFrac = (EAS_U32) phaseFrac;
}
Commit Message: Sonivox: sanity check numSamples.
Bug: 26366256
Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void parse_output_words(struct output_struct *words, short *levels,
const char *str, uchar priority)
{
const char *s;
int j, len, lev;
for ( ; str; str = s) {
if ((s = strchr(str, ',')) != NULL)
len = s++ - str;
else
len = strlen(str);
if (!len)
continue;
if (!isDigit(str)) {
while (len && isDigit(str+len-1))
len--;
}
lev = isDigit(str+len) ? atoi(str+len) : 1;
if (lev > MAX_OUT_LEVEL)
lev = MAX_OUT_LEVEL;
if (len == 4 && strncasecmp(str, "help", 4) == 0) {
output_item_help(words);
exit_cleanup(0);
}
if (len == 4 && strncasecmp(str, "none", 4) == 0)
len = lev = 0;
else if (len == 3 && strncasecmp(str, "all", 3) == 0)
len = 0;
for (j = 0; words[j].name; j++) {
if (!len
|| (len == words[j].namelen && strncasecmp(str, words[j].name, len) == 0)) {
if (priority >= words[j].priority) {
words[j].priority = priority;
levels[j] = lev;
}
if (len)
break;
}
}
if (len && !words[j].name) {
rprintf(FERROR, "Unknown %s item: \"%.*s\"\n",
words[j].help, len, str);
exit_cleanup(RERR_SYNTAX);
}
}
}
Commit Message:
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int jas_icctxt_getsize(jas_iccattrval_t *attrval)
{
jas_icctxt_t *txt = &attrval->data.txt;
return JAS_CAST(int, strlen(txt->string) + 1);
}
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
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int hidp_setup_hid(struct hidp_session *session,
struct hidp_connadd_req *req)
{
struct hid_device *hid;
int err;
session->rd_data = kzalloc(req->rd_size, GFP_KERNEL);
if (!session->rd_data)
return -ENOMEM;
if (copy_from_user(session->rd_data, req->rd_data, req->rd_size)) {
err = -EFAULT;
goto fault;
}
session->rd_size = req->rd_size;
hid = hid_allocate_device();
if (IS_ERR(hid)) {
err = PTR_ERR(hid);
goto fault;
}
session->hid = hid;
hid->driver_data = session;
hid->bus = BUS_BLUETOOTH;
hid->vendor = req->vendor;
hid->product = req->product;
hid->version = req->version;
hid->country = req->country;
strncpy(hid->name, req->name, 128);
snprintf(hid->phys, sizeof(hid->phys), "%pMR",
&bt_sk(session->ctrl_sock->sk)->src);
snprintf(hid->uniq, sizeof(hid->uniq), "%pMR",
&bt_sk(session->ctrl_sock->sk)->dst);
hid->dev.parent = &session->conn->dev;
hid->ll_driver = &hidp_hid_driver;
hid->hid_get_raw_report = hidp_get_raw_report;
hid->hid_output_raw_report = hidp_output_raw_report;
/* True if device is blacklisted in drivers/hid/hid-core.c */
if (hid_ignore(hid)) {
hid_destroy_device(session->hid);
session->hid = NULL;
return -ENODEV;
}
return 0;
fault:
kfree(session->rd_data);
session->rd_data = NULL;
return err;
}
Commit Message: Bluetooth: Fix incorrect strncpy() in hidp_setup_hid()
The length parameter should be sizeof(req->name) - 1 because there is no
guarantee that string provided by userspace will contain the trailing
'\0'.
Can be easily reproduced by manually setting req->name to 128 non-zero
bytes prior to ioctl(HIDPCONNADD) and checking the device name setup on
input subsystem:
$ cat /sys/devices/pnp0/00\:04/tty/ttyS0/hci0/hci0\:1/input8/name
AAAAAA[...]AAAAAAAAf0:af:f0:af:f0:af
("f0:af:f0:af:f0:af" is the device bluetooth address, taken from "phys"
field in struct hid_device due to overflow.)
Cc: [email protected]
Signed-off-by: Anderson Lizardo <[email protected]>
Acked-by: Marcel Holtmann <[email protected]>
Signed-off-by: Gustavo Padovan <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: std::string DownloadItemImpl::DebugString(bool verbose) const {
std::string description =
base::StringPrintf("{ id = %d"
" state = %s",
download_id_,
DebugDownloadStateString(state_));
std::string url_list("<none>");
if (!request_info_.url_chain.empty()) {
std::vector<GURL>::const_iterator iter = request_info_.url_chain.begin();
std::vector<GURL>::const_iterator last = request_info_.url_chain.end();
url_list = (*iter).is_valid() ? (*iter).spec() : "<invalid>";
++iter;
for ( ; verbose && (iter != last); ++iter) {
url_list += " ->\n\t";
const GURL& next_url = *iter;
url_list += next_url.is_valid() ? next_url.spec() : "<invalid>";
}
}
if (verbose) {
description += base::StringPrintf(
" total = %" PRId64 " received = %" PRId64
" reason = %s"
" paused = %c"
" resume_mode = %s"
" auto_resume_count = %d"
" danger = %d"
" all_data_saved = %c"
" last_modified = '%s'"
" etag = '%s'"
" has_download_file = %s"
" url_chain = \n\t\"%s\"\n\t"
" current_path = \"%" PRFilePath
"\"\n\t"
" target_path = \"%" PRFilePath
"\""
" referrer = \"%s\""
" site_url = \"%s\"",
GetTotalBytes(), GetReceivedBytes(),
DownloadInterruptReasonToString(last_reason_).c_str(),
IsPaused() ? 'T' : 'F', DebugResumeModeString(GetResumeMode()),
auto_resume_count_, GetDangerType(), AllDataSaved() ? 'T' : 'F',
GetLastModifiedTime().c_str(), GetETag().c_str(),
download_file_.get() ? "true" : "false", url_list.c_str(),
GetFullPath().value().c_str(), GetTargetFilePath().value().c_str(),
GetReferrerUrl().spec().c_str(), GetSiteUrl().spec().c_str());
} else {
description += base::StringPrintf(" url = \"%s\"", url_list.c_str());
}
description += " }";
return description;
}
Commit Message: Downloads : Fixed an issue of opening incorrect download file
When one download overwrites another completed download, calling download.open in the old download causes the new download to open, which could be dangerous and undesirable. In this CL, we are trying to avoid this by blocking the opening of the old download.
Bug: 793620
Change-Id: Ic948175756700ad7c08489c3cc347330daedb6f8
Reviewed-on: https://chromium-review.googlesource.com/826477
Reviewed-by: David Trainor <[email protected]>
Reviewed-by: Xing Liu <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Commit-Queue: Shakti Sahu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#525810}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: long long AudioTrack::GetBitDepth() const { return m_bitDepth; }
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
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static const ut8 *r_bin_dwarf_parse_comp_unit(Sdb *s, const ut8 *obuf,
RBinDwarfCompUnit *cu, const RBinDwarfDebugAbbrev *da,
size_t offset, const ut8 *debug_str, size_t debug_str_len) {
const ut8 *buf = obuf, *buf_end = obuf + (cu->hdr.length - 7);
ut64 abbr_code;
size_t i;
if (cu->hdr.length > debug_str_len) {
return NULL;
}
while (buf && buf < buf_end && buf >= obuf) {
if (cu->length && cu->capacity == cu->length) {
r_bin_dwarf_expand_cu (cu);
}
buf = r_uleb128 (buf, buf_end - buf, &abbr_code);
if (abbr_code > da->length || !buf) {
return NULL;
}
r_bin_dwarf_init_die (&cu->dies[cu->length]);
if (!abbr_code) {
cu->dies[cu->length].abbrev_code = 0;
cu->length++;
buf++;
continue;
}
cu->dies[cu->length].abbrev_code = abbr_code;
cu->dies[cu->length].tag = da->decls[abbr_code - 1].tag;
abbr_code += offset;
if (da->capacity < abbr_code) {
return NULL;
}
for (i = 0; i < da->decls[abbr_code - 1].length; i++) {
if (cu->dies[cu->length].length == cu->dies[cu->length].capacity) {
r_bin_dwarf_expand_die (&cu->dies[cu->length]);
}
if (i >= cu->dies[cu->length].capacity || i >= da->decls[abbr_code - 1].capacity) {
eprintf ("Warning: malformed dwarf attribute capacity doesn't match length\n");
break;
}
memset (&cu->dies[cu->length].attr_values[i], 0, sizeof
(cu->dies[cu->length].attr_values[i]));
buf = r_bin_dwarf_parse_attr_value (buf, buf_end - buf,
&da->decls[abbr_code - 1].specs[i],
&cu->dies[cu->length].attr_values[i],
&cu->hdr, debug_str, debug_str_len);
if (cu->dies[cu->length].attr_values[i].name == DW_AT_comp_dir) {
const char *name = cu->dies[cu->length].attr_values[i].encoding.str_struct.string;
sdb_set (s, "DW_AT_comp_dir", name, 0);
}
cu->dies[cu->length].length++;
}
cu->length++;
}
return buf;
}
Commit Message: Fix #8813 - segfault in dwarf parser
CWE ID: CWE-125
Target: 1
Example 2:
Code: CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)
{
cJSON *to_detach = cJSON_GetObjectItem(object, string);
return cJSON_DetachItemViaPointer(object, to_detach);
}
Commit Message: Fix crash of cJSON_GetObjectItemCaseSensitive when calling it on arrays
CWE ID: CWE-754
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void LocalFileSystem::requestFileSystem(ExecutionContext* context, FileSystemType type, long long size, PassOwnPtr<AsyncFileSystemCallbacks> callbacks)
{
RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context);
RefPtr<CallbackWrapper> wrapper = adoptRef(new CallbackWrapper(callbacks));
requestFileSystemAccessInternal(context,
bind(&LocalFileSystem::fileSystemAllowedInternal, this, contextPtr, type, wrapper),
bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper));
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SpdyWriteQueue::RemovePendingWritesForStreamsAfter(
SpdyStreamId last_good_stream_id) {
CHECK(!removing_writes_);
removing_writes_ = true;
for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) {
std::deque<PendingWrite>* queue = &queue_[i];
std::deque<PendingWrite>::iterator out_it = queue->begin();
for (std::deque<PendingWrite>::const_iterator it = queue->begin();
it != queue->end(); ++it) {
if (it->stream.get() && (it->stream->stream_id() > last_good_stream_id ||
it->stream->stream_id() == 0)) {
delete it->frame_producer;
} else {
*out_it = *it;
++out_it;
}
}
queue->erase(out_it, queue->end());
}
removing_writes_ = false;
}
Commit Message: These can post callbacks which re-enter into SpdyWriteQueue.
BUG=369539
Review URL: https://codereview.chromium.org/265933007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268730 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: int32_t Parcel::readExceptionCode() const
{
binder::Status status;
status.readFromParcel(*this);
return status.exceptionCode();
}
Commit Message: Add bound checks to utf16_to_utf8
Bug: 29250543
Change-Id: I518e7b2fe10aaa3f1c1987586a09b1110aff7e1a
(cherry picked from commit 7e93b2ddcb49b5365fbe1dab134ffb38e6f1c719)
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int aesni_cbc_hmac_sha256_init_key(EVP_CIPHER_CTX *ctx,
const unsigned char *inkey,
const unsigned char *iv, int enc)
{
EVP_AES_HMAC_SHA256 *key = data(ctx);
int ret;
if (enc)
memset(&key->ks, 0, sizeof(key->ks.rd_key)),
ret = aesni_set_encrypt_key(inkey, ctx->key_len * 8, &key->ks);
else
ret = aesni_set_decrypt_key(inkey, ctx->key_len * 8, &key->ks);
SHA256_Init(&key->head); /* handy when benchmarking */
key->tail = key->head;
key->md = key->head;
key->payload_length = NO_PAYLOAD_LENGTH;
return ret < 0 ? 0 : 1;
}
Commit Message:
CWE ID: CWE-310
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PasswordAutofillAgent::PasswordAutofillAgent(content::RenderFrame* render_frame)
: content::RenderFrameObserver(render_frame),
logging_state_active_(false),
was_username_autofilled_(false),
was_password_autofilled_(false),
weak_ptr_factory_(this) {
Send(new AutofillHostMsg_PasswordAutofillAgentConstructed(routing_id()));
}
Commit Message: Remove WeakPtrFactory from PasswordAutofillAgent
Unlike in AutofillAgent, the factory is no longer used in PAA.
[email protected]
BUG=609010,609007,608100,608101,433486
Review-Url: https://codereview.chromium.org/1945723003
Cr-Commit-Position: refs/heads/master@{#391475}
CWE ID:
Target: 1
Example 2:
Code: WORD32 ih264d_cavlc_parse4x4coeff_n8(WORD16 *pi2_coeff_block,
UWORD32 u4_isdc, /* is it a DC block */
WORD32 u4_n,
dec_struct_t *ps_dec,
UWORD32 *pu4_total_coeff)
{
dec_bit_stream_t *ps_bitstrm = ps_dec->ps_bitstrm;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 u4_bitstream_offset = ps_bitstrm->u4_ofst;
UWORD32 u4_code;
UNUSED(u4_n);
UNUSED(pi2_coeff_block);
GETBITS(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 6);
ps_bitstrm->u4_ofst = u4_bitstream_offset;
*pu4_total_coeff = 0;
if(u4_code != 3)
{
UWORD8 *pu1_offset = (UWORD8 *)gau1_ih264d_total_coeff_fn_ptr_offset;
UWORD32 u4_trailing_ones, u4_offset, u4_total_coeff_tone;
*pu4_total_coeff = (u4_code >> 2) + 1;
u4_trailing_ones = u4_code & 0x03;
u4_offset = pu1_offset[*pu4_total_coeff - 1];
u4_total_coeff_tone = (*pu4_total_coeff << 16) | u4_trailing_ones;
ps_dec->pf_cavlc_4x4res_block[u4_offset](u4_isdc,
u4_total_coeff_tone,
ps_bitstrm);
}
return OK;
}
Commit Message: Decoder: Fix stack underflow in CAVLC 4x4 parse functions
Bug: 26399350
Change-Id: Id768751672a7b093ab6e53d4fc0b3188d470920e
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: unsigned char *base64decode(const char *buf, size_t *size)
{
if (!buf || !size) return NULL;
size_t len = (*size > 0) ? *size : strlen(buf);
if (len <= 0) return NULL;
unsigned char *outbuf = (unsigned char*)malloc((len/4)*3+3);
const char *ptr = buf;
int p = 0;
size_t l = 0;
do {
ptr += strspn(ptr, "\r\n\t ");
if (*ptr == '\0' || ptr >= buf+len) {
break;
}
l = strcspn(ptr, "\r\n\t ");
if (l > 3 && ptr+l <= buf+len) {
p+=base64decode_block(outbuf+p, ptr, l);
ptr += l;
} else {
break;
}
} while (1);
outbuf[p] = 0;
*size = p;
return outbuf;
}
Commit Message: base64: Rework base64decode to handle split encoded data correctly
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn,
struct nlattr *rp)
{
struct xfrm_replay_state_esn *up;
if (!replay_esn || !rp)
return 0;
up = nla_data(rp);
if (xfrm_replay_state_esn_len(replay_esn) !=
xfrm_replay_state_esn_len(up))
return -EINVAL;
return 0;
}
Commit Message: xfrm_user: ensure user supplied esn replay window is valid
The current code fails to ensure that the netlink message actually
contains as many bytes as the header indicates. If a user creates a new
state or updates an existing one but does not supply the bytes for the
whole ESN replay window, the kernel copies random heap bytes into the
replay bitmap, the ones happen to follow the XFRMA_REPLAY_ESN_VAL
netlink attribute. This leads to following issues:
1. The replay window has random bits set confusing the replay handling
code later on.
2. A malicious user could use this flaw to leak up to ~3.5kB of heap
memory when she has access to the XFRM netlink interface (requires
CAP_NET_ADMIN).
Known users of the ESN replay window are strongSwan and Steffen's
iproute2 patch (<http://patchwork.ozlabs.org/patch/85962/>). The latter
uses the interface with a bitmap supplied while the former does not.
strongSwan is therefore prone to run into issue 1.
To fix both issues without breaking existing userland allow using the
XFRMA_REPLAY_ESN_VAL netlink attribute with either an empty bitmap or a
fully specified one. For the former case we initialize the in-kernel
bitmap with zero, for the latter we copy the user supplied bitmap. For
state updates the full bitmap must be supplied.
To prevent overflows in the bitmap length calculation the maximum size
of bmp_len is limited to 128 by this patch -- resulting in a maximum
replay window of 4096 packets. This should be sufficient for all real
life scenarios (RFC 4303 recommends a default replay window size of 64).
Cc: Steffen Klassert <[email protected]>
Cc: Martin Willi <[email protected]>
Cc: Ben Hutchings <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: void CoordinatorImpl::RequestGlobalMemoryDumpAndAppendToTrace(
MemoryDumpType dump_type,
MemoryDumpLevelOfDetail level_of_detail,
RequestGlobalMemoryDumpAndAppendToTraceCallback callback) {
auto adapter = [](RequestGlobalMemoryDumpAndAppendToTraceCallback callback,
bool success, uint64_t dump_guid,
mojom::GlobalMemoryDumpPtr) {
std::move(callback).Run(success, dump_guid);
};
QueuedRequest::Args args(dump_type, level_of_detail, {},
true /* add_to_trace */, base::kNullProcessId,
/*memory_footprint_only=*/false);
RequestGlobalMemoryDumpInternal(args,
base::BindOnce(adapter, std::move(callback)));
}
Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained
Bug: 856578
Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9
Reviewed-on: https://chromium-review.googlesource.com/1114617
Reviewed-by: Hector Dearman <[email protected]>
Commit-Queue: Hector Dearman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#571528}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
colorspace[MaxTextExtent],
text[MaxTextExtent];
Image
*image;
IndexPacket
*indexes;
long
x_offset,
y_offset;
MagickBooleanType
status;
MagickPixelPacket
pixel;
QuantumAny
range;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
count,
type,
y;
unsigned long
depth,
height,
max_value,
width;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
width=0;
height=0;
max_value=0;
*colorspace='\0';
count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value,
colorspace);
if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=width;
image->rows=height;
for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
LocaleLower(colorspace);
i=(ssize_t) strlen(colorspace)-1;
image->matte=MagickFalse;
if ((i > 0) && (colorspace[i] == 'a'))
{
colorspace[i]='\0';
image->matte=MagickTrue;
}
type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace);
if (type < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->colorspace=(ColorspaceType) type;
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
(void) SetImageBackgroundColor(image);
range=GetQuantumRange(image->depth);
for (y=0; y < (ssize_t) image->rows; y++)
{
double
blue,
green,
index,
opacity,
red;
red=0.0;
green=0.0;
blue=0.0;
index=0.0;
opacity=0.0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ReadBlobString(image,text) == (char *) NULL)
break;
switch (image->colorspace)
{
case GRAYColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&opacity);
green=red;
blue=red;
break;
}
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset,&y_offset,&red);
green=red;
blue=red;
break;
}
case CMYKColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&index,&opacity);
break;
}
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue,&index);
break;
}
default:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&opacity);
break;
}
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue);
break;
}
}
if (strchr(text,'%') != (char *) NULL)
{
red*=0.01*range;
green*=0.01*range;
blue*=0.01*range;
index*=0.01*range;
opacity*=0.01*range;
}
if (image->colorspace == LabColorspace)
{
green+=(range+1)/2.0;
blue+=(range+1)/2.0;
}
pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5),
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5),
range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5),
range);
pixel.index=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (index+0.5),
range);
pixel.opacity=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (opacity+
0.5),range);
q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1,
exception);
if (q == (PixelPacket *) NULL)
continue;
SetPixelRed(q,pixel.red);
SetPixelGreen(q,pixel.green);
SetPixelBlue(q,pixel.blue);
if (image->colorspace == CMYKColorspace)
{
indexes=GetAuthenticIndexQueue(image);
SetPixelIndex(indexes,pixel.index);
}
if (image->matte != MagickFalse)
SetPixelAlpha(q,pixel.opacity);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/591
CWE ID: CWE-835
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int dccp_packet(struct nf_conn *ct, const struct sk_buff *skb,
unsigned int dataoff, enum ip_conntrack_info ctinfo,
u_int8_t pf, unsigned int hooknum,
unsigned int *timeouts)
{
struct net *net = nf_ct_net(ct);
enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
struct dccp_hdr _dh, *dh;
u_int8_t type, old_state, new_state;
enum ct_dccp_roles role;
dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &dh);
BUG_ON(dh == NULL);
type = dh->dccph_type;
if (type == DCCP_PKT_RESET &&
!test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
/* Tear down connection immediately if only reply is a RESET */
nf_ct_kill_acct(ct, ctinfo, skb);
return NF_ACCEPT;
}
spin_lock_bh(&ct->lock);
role = ct->proto.dccp.role[dir];
old_state = ct->proto.dccp.state;
new_state = dccp_state_table[role][type][old_state];
switch (new_state) {
case CT_DCCP_REQUEST:
if (old_state == CT_DCCP_TIMEWAIT &&
role == CT_DCCP_ROLE_SERVER) {
/* Reincarnation in the reverse direction: reopen and
* reverse client/server roles. */
ct->proto.dccp.role[dir] = CT_DCCP_ROLE_CLIENT;
ct->proto.dccp.role[!dir] = CT_DCCP_ROLE_SERVER;
}
break;
case CT_DCCP_RESPOND:
if (old_state == CT_DCCP_REQUEST)
ct->proto.dccp.handshake_seq = dccp_hdr_seq(dh);
break;
case CT_DCCP_PARTOPEN:
if (old_state == CT_DCCP_RESPOND &&
type == DCCP_PKT_ACK &&
dccp_ack_seq(dh) == ct->proto.dccp.handshake_seq)
set_bit(IPS_ASSURED_BIT, &ct->status);
break;
case CT_DCCP_IGNORE:
/*
* Connection tracking might be out of sync, so we ignore
* packets that might establish a new connection and resync
* if the server responds with a valid Response.
*/
if (ct->proto.dccp.last_dir == !dir &&
ct->proto.dccp.last_pkt == DCCP_PKT_REQUEST &&
type == DCCP_PKT_RESPONSE) {
ct->proto.dccp.role[!dir] = CT_DCCP_ROLE_CLIENT;
ct->proto.dccp.role[dir] = CT_DCCP_ROLE_SERVER;
ct->proto.dccp.handshake_seq = dccp_hdr_seq(dh);
new_state = CT_DCCP_RESPOND;
break;
}
ct->proto.dccp.last_dir = dir;
ct->proto.dccp.last_pkt = type;
spin_unlock_bh(&ct->lock);
if (LOG_INVALID(net, IPPROTO_DCCP))
nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL,
"nf_ct_dccp: invalid packet ignored ");
return NF_ACCEPT;
case CT_DCCP_INVALID:
spin_unlock_bh(&ct->lock);
if (LOG_INVALID(net, IPPROTO_DCCP))
nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL,
"nf_ct_dccp: invalid state transition ");
return -NF_ACCEPT;
}
ct->proto.dccp.last_dir = dir;
ct->proto.dccp.last_pkt = type;
ct->proto.dccp.state = new_state;
spin_unlock_bh(&ct->lock);
if (new_state != old_state)
nf_conntrack_event_cache(IPCT_PROTOINFO, ct);
nf_ct_refresh_acct(ct, ctinfo, skb, timeouts[new_state]);
return NF_ACCEPT;
}
Commit Message: netfilter: nf_conntrack_dccp: fix skb_header_pointer API usages
Some occurences in the netfilter tree use skb_header_pointer() in
the following way ...
struct dccp_hdr _dh, *dh;
...
skb_header_pointer(skb, dataoff, sizeof(_dh), &dh);
... where dh itself is a pointer that is being passed as the copy
buffer. Instead, we need to use &_dh as the forth argument so that
we're copying the data into an actual buffer that sits on the stack.
Currently, we probably could overwrite memory on the stack (e.g.
with a possibly mal-formed DCCP packet), but unintentionally, as
we only want the buffer to be placed into _dh variable.
Fixes: 2bc780499aa3 ("[NETFILTER]: nf_conntrack: add DCCP protocol support")
Signed-off-by: Daniel Borkmann <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: static bool isCaretAtStartOfWrappedLine(const FrameSelection& selection) {
if (!selection.computeVisibleSelectionInDOMTreeDeprecated().isCaret())
return false;
if (selection.selectionInDOMTree().affinity() != TextAffinity::Downstream)
return false;
const Position& position =
selection.computeVisibleSelectionInDOMTreeDeprecated().start();
return !inSameLine(PositionWithAffinity(position, TextAffinity::Upstream),
PositionWithAffinity(position, TextAffinity::Downstream));
}
Commit Message: Make TypingCommand::insertText() to take SelectionInDOMTree instead of VisibleSelection
This patch makes |TypingCommand::insertText()| to take |SelectionInDOMTree|
instead of |VisibleSelection| to reduce usage of |VisibleSelection| for
improving code health.
BUG=657237
TEST=n/a
Review-Url: https://codereview.chromium.org/2733183002
Cr-Commit-Position: refs/heads/master@{#455368}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with 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:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void InspectorTraceEvents::WillSendRequest(
ExecutionContext*,
unsigned long identifier,
DocumentLoader* loader,
ResourceRequest& request,
const ResourceResponse& redirect_response,
const FetchInitiatorInfo&) {
LocalFrame* frame = loader ? loader->GetFrame() : nullptr;
TRACE_EVENT_INSTANT1(
"devtools.timeline", "ResourceSendRequest", TRACE_EVENT_SCOPE_THREAD,
"data", InspectorSendRequestEvent::Data(identifier, frame, request));
probe::AsyncTaskScheduled(frame ? frame->GetDocument() : nullptr,
"SendRequest", AsyncId(identifier));
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Andrey Lushnikov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool GLES2DecoderImpl::PrepareTexturesForRender() {
DCHECK(state_.current_program.get());
bool textures_set = false;
const Program::SamplerIndices& sampler_indices =
state_.current_program->sampler_indices();
for (size_t ii = 0; ii < sampler_indices.size(); ++ii) {
const Program::UniformInfo* uniform_info =
state_.current_program->GetUniformInfo(sampler_indices[ii]);
DCHECK(uniform_info);
for (size_t jj = 0; jj < uniform_info->texture_units.size(); ++jj) {
GLuint texture_unit_index = uniform_info->texture_units[jj];
if (texture_unit_index < state_.texture_units.size()) {
TextureUnit& texture_unit = state_.texture_units[texture_unit_index];
TextureRef* texture_ref =
texture_unit.GetInfoForSamplerType(uniform_info->type);
GLenum textarget = GetBindTargetForSamplerType(uniform_info->type);
const SamplerState& sampler_state = GetSamplerStateForTextureUnit(
uniform_info->type, texture_unit_index);
if (!texture_ref ||
!texture_manager()->CanRenderWithSampler(
texture_ref, sampler_state)) {
textures_set = true;
api()->glActiveTextureFn(GL_TEXTURE0 + texture_unit_index);
api()->glBindTextureFn(textarget, texture_manager()->black_texture_id(
uniform_info->type));
if (!texture_ref) {
LOCAL_RENDER_WARNING(
std::string("there is no texture bound to the unit ") +
base::UintToString(texture_unit_index));
} else {
LOCAL_RENDER_WARNING(
std::string("texture bound to texture unit ") +
base::UintToString(texture_unit_index) +
" is not renderable. It maybe non-power-of-2 and have"
" incompatible texture filtering.");
}
continue;
}
if (textarget != GL_TEXTURE_CUBE_MAP) {
Texture* texture = texture_ref->texture();
if (DoBindOrCopyTexImageIfNeeded(texture, textarget,
GL_TEXTURE0 + texture_unit_index)) {
textures_set = true;
continue;
}
}
}
}
}
return !textures_set;
}
Commit Message: Implement immutable texture base/max level clamping
It seems some drivers fail to handle that gracefully, so let's always clamp
to be on the safe side.
BUG=877874
TEST=test case in the bug, gpu_unittests
[email protected]
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: I6d93cb9389ea70525df4604112223604577582a2
Reviewed-on: https://chromium-review.googlesource.com/1194994
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#587264}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void FrameFetchContext::DispatchDidBlockRequest(
const ResourceRequest& resource_request,
const FetchInitiatorInfo& fetch_initiator_info,
ResourceRequestBlockedReason blocked_reason) const {
if (IsDetached())
return;
probe::didBlockRequest(GetFrame()->GetDocument(), resource_request,
MasterDocumentLoader(), 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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) {
RASN1Object *object;
RCMS *container;
if (!buffer || !length) {
return NULL;
}
container = R_NEW0 (RCMS);
if (!container) {
return NULL;
}
object = r_asn1_create_object (buffer, length);
if (!object || object->list.length != 2 || !object->list.objects[0] || object->list.objects[1]->list.length != 1) {
r_asn1_free_object (object);
free (container);
return NULL;
}
container->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length);
r_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]);
r_asn1_free_object (object);
return container;
}
Commit Message: Fix #7152 - Null deref in cms
CWE ID: CWE-476
Target: 1
Example 2:
Code: void __stop_tty(struct tty_struct *tty)
{
if (tty->stopped)
return;
tty->stopped = 1;
if (tty->ops->stop)
tty->ops->stop(tty);
}
Commit Message: tty: Fix unsafe ldisc reference via ioctl(TIOCGETD)
ioctl(TIOCGETD) retrieves the line discipline id directly from the
ldisc because the line discipline id (c_line) in termios is untrustworthy;
userspace may have set termios via ioctl(TCSETS*) without actually
changing the line discipline via ioctl(TIOCSETD).
However, directly accessing the current ldisc via tty->ldisc is
unsafe; the ldisc ptr dereferenced may be stale if the line discipline
is changing via ioctl(TIOCSETD) or hangup.
Wait for the line discipline reference (just like read() or write())
to retrieve the "current" line discipline id.
Cc: <[email protected]>
Signed-off-by: Peter Hurley <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void AddIncompatibleApplicationsStrings(content::WebUIDataSource* html_source) {
LocalizedString localized_strings[] = {
{"incompatibleApplicationsResetCardTitle",
IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_RESET_CARD_TITLE},
{"incompatibleApplicationsSubpageSubtitle",
IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_SUBPAGE_SUBTITLE},
{"incompatibleApplicationsSubpageSubtitleNoAdminRights",
IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_SUBPAGE_SUBTITLE_NO_ADMIN_RIGHTS},
{"incompatibleApplicationsListTitle",
IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_LIST_TITLE},
{"incompatibleApplicationsRemoveButton",
IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_REMOVE_BUTTON},
{"incompatibleApplicationsUpdateButton",
IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_UPDATE_BUTTON},
{"incompatibleApplicationsDone",
IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_DONE},
};
AddLocalizedStringsBulk(html_source, localized_strings,
arraysize(localized_strings));
base::string16 learn_how_text = l10n_util::GetStringFUTF16(
IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_SUBPAGE_LEARN_HOW,
base::ASCIIToUTF16("chrome://placeholder"));
html_source->AddString("incompatibleApplicationsSubpageLearnHow",
learn_how_text);
}
Commit Message: [md-settings] Clarify Password Saving and Autofill Toggles
This change clarifies the wording around the password saving and
autofill toggles.
Bug: 822465
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I91b31fe61cd0754239f7908e8c04c7e69b72f670
Reviewed-on: https://chromium-review.googlesource.com/970541
Commit-Queue: Jan Wilken Dörrie <[email protected]>
Reviewed-by: Vaclav Brozek <[email protected]>
Reviewed-by: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#544661}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void MakeGroupObsolete() {
PushNextTask(
base::BindOnce(&AppCacheStorageImplTest::Verify_MakeGroupObsolete,
base::Unretained(this)));
MakeCacheAndGroup(kManifestUrl, 1, 1, true);
EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin]);
AppCacheDatabase::EntryRecord entry_record;
entry_record.cache_id = 1;
entry_record.flags = AppCacheEntry::FALLBACK;
entry_record.response_id = 1;
entry_record.url = kEntryUrl;
EXPECT_TRUE(database()->InsertEntry(&entry_record));
AppCacheDatabase::NamespaceRecord fallback_namespace_record;
fallback_namespace_record.cache_id = 1;
fallback_namespace_record.namespace_.target_url = kEntryUrl;
fallback_namespace_record.namespace_.namespace_url = kFallbackNamespace;
fallback_namespace_record.origin = url::Origin::Create(kManifestUrl);
EXPECT_TRUE(database()->InsertNamespace(&fallback_namespace_record));
AppCacheDatabase::OnlineWhiteListRecord online_whitelist_record;
online_whitelist_record.cache_id = 1;
online_whitelist_record.namespace_url = kOnlineNamespace;
EXPECT_TRUE(database()->InsertOnlineWhiteList(&online_whitelist_record));
storage()->MakeGroupObsolete(group_.get(), delegate(), 0);
EXPECT_FALSE(group_->is_obsolete());
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200
Target: 1
Example 2:
Code: user_key_allowed(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
int auth_attempt, struct sshauthopt **authoptsp)
{
u_int success, i;
char *file;
struct sshauthopt *opts = NULL;
if (authoptsp != NULL)
*authoptsp = NULL;
if (auth_key_is_revoked(key))
return 0;
if (sshkey_is_cert(key) &&
auth_key_is_revoked(key->cert->signature_key))
return 0;
if ((success = user_cert_trusted_ca(ssh, pw, key, &opts)) != 0)
goto out;
sshauthopt_free(opts);
opts = NULL;
if ((success = user_key_command_allowed2(ssh, pw, key, &opts)) != 0)
goto out;
sshauthopt_free(opts);
opts = NULL;
for (i = 0; !success && i < options.num_authkeys_files; i++) {
if (strcasecmp(options.authorized_keys_files[i], "none") == 0)
continue;
file = expand_authorized_keys(
options.authorized_keys_files[i], pw);
success = user_key_allowed2(ssh, pw, key, file, &opts);
free(file);
}
out:
if (success && authoptsp != NULL) {
*authoptsp = opts;
opts = NULL;
}
sshauthopt_free(opts);
return success;
}
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
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: const Track* Tracks::GetTrackByIndex(unsigned long idx) const
{
const ptrdiff_t count = m_trackEntriesEnd - m_trackEntries;
if (idx >= static_cast<unsigned long>(count))
return NULL;
return m_trackEntries[idx];
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int acm_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_cdc_union_desc *union_header = NULL;
struct usb_cdc_country_functional_desc *cfd = NULL;
unsigned char *buffer = intf->altsetting->extra;
int buflen = intf->altsetting->extralen;
struct usb_interface *control_interface;
struct usb_interface *data_interface;
struct usb_endpoint_descriptor *epctrl = NULL;
struct usb_endpoint_descriptor *epread = NULL;
struct usb_endpoint_descriptor *epwrite = NULL;
struct usb_device *usb_dev = interface_to_usbdev(intf);
struct acm *acm;
int minor;
int ctrlsize, readsize;
u8 *buf;
u8 ac_management_function = 0;
u8 call_management_function = 0;
int call_interface_num = -1;
int data_interface_num = -1;
unsigned long quirks;
int num_rx_buf;
int i;
unsigned int elength = 0;
int combined_interfaces = 0;
struct device *tty_dev;
int rv = -ENOMEM;
/* normal quirks */
quirks = (unsigned long)id->driver_info;
if (quirks == IGNORE_DEVICE)
return -ENODEV;
num_rx_buf = (quirks == SINGLE_RX_URB) ? 1 : ACM_NR;
/* handle quirks deadly to normal probing*/
if (quirks == NO_UNION_NORMAL) {
data_interface = usb_ifnum_to_if(usb_dev, 1);
control_interface = usb_ifnum_to_if(usb_dev, 0);
goto skip_normal_probe;
}
/* normal probing*/
if (!buffer) {
dev_err(&intf->dev, "Weird descriptor references\n");
return -EINVAL;
}
if (!buflen) {
if (intf->cur_altsetting->endpoint &&
intf->cur_altsetting->endpoint->extralen &&
intf->cur_altsetting->endpoint->extra) {
dev_dbg(&intf->dev,
"Seeking extra descriptors on endpoint\n");
buflen = intf->cur_altsetting->endpoint->extralen;
buffer = intf->cur_altsetting->endpoint->extra;
} else {
dev_err(&intf->dev,
"Zero length descriptor references\n");
return -EINVAL;
}
}
while (buflen > 0) {
elength = buffer[0];
if (!elength) {
dev_err(&intf->dev, "skipping garbage byte\n");
elength = 1;
goto next_desc;
}
if (buffer[1] != USB_DT_CS_INTERFACE) {
dev_err(&intf->dev, "skipping garbage\n");
goto next_desc;
}
switch (buffer[2]) {
case USB_CDC_UNION_TYPE: /* we've found it */
if (elength < sizeof(struct usb_cdc_union_desc))
goto next_desc;
if (union_header) {
dev_err(&intf->dev, "More than one "
"union descriptor, skipping ...\n");
goto next_desc;
}
union_header = (struct usb_cdc_union_desc *)buffer;
break;
case USB_CDC_COUNTRY_TYPE: /* export through sysfs*/
if (elength < sizeof(struct usb_cdc_country_functional_desc))
goto next_desc;
cfd = (struct usb_cdc_country_functional_desc *)buffer;
break;
case USB_CDC_HEADER_TYPE: /* maybe check version */
break; /* for now we ignore it */
case USB_CDC_ACM_TYPE:
if (elength < 4)
goto next_desc;
ac_management_function = buffer[3];
break;
case USB_CDC_CALL_MANAGEMENT_TYPE:
if (elength < 5)
goto next_desc;
call_management_function = buffer[3];
call_interface_num = buffer[4];
break;
default:
/*
* there are LOTS more CDC descriptors that
* could legitimately be found here.
*/
dev_dbg(&intf->dev, "Ignoring descriptor: "
"type %02x, length %ud\n",
buffer[2], elength);
break;
}
next_desc:
buflen -= elength;
buffer += elength;
}
if (!union_header) {
if (call_interface_num > 0) {
dev_dbg(&intf->dev, "No union descriptor, using call management descriptor\n");
/* quirks for Droids MuIn LCD */
if (quirks & NO_DATA_INTERFACE)
data_interface = usb_ifnum_to_if(usb_dev, 0);
else
data_interface = usb_ifnum_to_if(usb_dev, (data_interface_num = call_interface_num));
control_interface = intf;
} else {
if (intf->cur_altsetting->desc.bNumEndpoints != 3) {
dev_dbg(&intf->dev,"No union descriptor, giving up\n");
return -ENODEV;
} else {
dev_warn(&intf->dev,"No union descriptor, testing for castrated device\n");
combined_interfaces = 1;
control_interface = data_interface = intf;
goto look_for_collapsed_interface;
}
}
} else {
control_interface = usb_ifnum_to_if(usb_dev, union_header->bMasterInterface0);
data_interface = usb_ifnum_to_if(usb_dev, (data_interface_num = union_header->bSlaveInterface0));
}
if (!control_interface || !data_interface) {
dev_dbg(&intf->dev, "no interfaces\n");
return -ENODEV;
}
if (data_interface_num != call_interface_num)
dev_dbg(&intf->dev, "Separate call control interface. That is not fully supported.\n");
if (control_interface == data_interface) {
/* some broken devices designed for windows work this way */
dev_warn(&intf->dev,"Control and data interfaces are not separated!\n");
combined_interfaces = 1;
/* a popular other OS doesn't use it */
quirks |= NO_CAP_LINE;
if (data_interface->cur_altsetting->desc.bNumEndpoints != 3) {
dev_err(&intf->dev, "This needs exactly 3 endpoints\n");
return -EINVAL;
}
look_for_collapsed_interface:
for (i = 0; i < 3; i++) {
struct usb_endpoint_descriptor *ep;
ep = &data_interface->cur_altsetting->endpoint[i].desc;
if (usb_endpoint_is_int_in(ep))
epctrl = ep;
else if (usb_endpoint_is_bulk_out(ep))
epwrite = ep;
else if (usb_endpoint_is_bulk_in(ep))
epread = ep;
else
return -EINVAL;
}
if (!epctrl || !epread || !epwrite)
return -ENODEV;
else
goto made_compressed_probe;
}
skip_normal_probe:
/*workaround for switched interfaces */
if (data_interface->cur_altsetting->desc.bInterfaceClass
!= CDC_DATA_INTERFACE_TYPE) {
if (control_interface->cur_altsetting->desc.bInterfaceClass
== CDC_DATA_INTERFACE_TYPE) {
dev_dbg(&intf->dev,
"Your device has switched interfaces.\n");
swap(control_interface, data_interface);
} else {
return -EINVAL;
}
}
/* Accept probe requests only for the control interface */
if (!combined_interfaces && intf != control_interface)
return -ENODEV;
if (!combined_interfaces && usb_interface_claimed(data_interface)) {
/* valid in this context */
dev_dbg(&intf->dev, "The data interface isn't available\n");
return -EBUSY;
}
if (data_interface->cur_altsetting->desc.bNumEndpoints < 2 ||
control_interface->cur_altsetting->desc.bNumEndpoints == 0)
return -EINVAL;
epctrl = &control_interface->cur_altsetting->endpoint[0].desc;
epread = &data_interface->cur_altsetting->endpoint[0].desc;
epwrite = &data_interface->cur_altsetting->endpoint[1].desc;
/* workaround for switched endpoints */
if (!usb_endpoint_dir_in(epread)) {
/* descriptors are swapped */
dev_dbg(&intf->dev,
"The data interface has switched endpoints\n");
swap(epread, epwrite);
}
made_compressed_probe:
dev_dbg(&intf->dev, "interfaces are valid\n");
acm = kzalloc(sizeof(struct acm), GFP_KERNEL);
if (acm == NULL)
goto alloc_fail;
minor = acm_alloc_minor(acm);
if (minor < 0) {
dev_err(&intf->dev, "no more free acm devices\n");
kfree(acm);
return -ENODEV;
}
ctrlsize = usb_endpoint_maxp(epctrl);
readsize = usb_endpoint_maxp(epread) *
(quirks == SINGLE_RX_URB ? 1 : 2);
acm->combined_interfaces = combined_interfaces;
acm->writesize = usb_endpoint_maxp(epwrite) * 20;
acm->control = control_interface;
acm->data = data_interface;
acm->minor = minor;
acm->dev = usb_dev;
acm->ctrl_caps = ac_management_function;
if (quirks & NO_CAP_LINE)
acm->ctrl_caps &= ~USB_CDC_CAP_LINE;
acm->ctrlsize = ctrlsize;
acm->readsize = readsize;
acm->rx_buflimit = num_rx_buf;
INIT_WORK(&acm->work, acm_softint);
init_waitqueue_head(&acm->wioctl);
spin_lock_init(&acm->write_lock);
spin_lock_init(&acm->read_lock);
mutex_init(&acm->mutex);
acm->rx_endpoint = usb_rcvbulkpipe(usb_dev, epread->bEndpointAddress);
acm->is_int_ep = usb_endpoint_xfer_int(epread);
if (acm->is_int_ep)
acm->bInterval = epread->bInterval;
tty_port_init(&acm->port);
acm->port.ops = &acm_port_ops;
init_usb_anchor(&acm->delayed);
acm->quirks = quirks;
buf = usb_alloc_coherent(usb_dev, ctrlsize, GFP_KERNEL, &acm->ctrl_dma);
if (!buf)
goto alloc_fail2;
acm->ctrl_buffer = buf;
if (acm_write_buffers_alloc(acm) < 0)
goto alloc_fail4;
acm->ctrlurb = usb_alloc_urb(0, GFP_KERNEL);
if (!acm->ctrlurb)
goto alloc_fail5;
for (i = 0; i < num_rx_buf; i++) {
struct acm_rb *rb = &(acm->read_buffers[i]);
struct urb *urb;
rb->base = usb_alloc_coherent(acm->dev, readsize, GFP_KERNEL,
&rb->dma);
if (!rb->base)
goto alloc_fail6;
rb->index = i;
rb->instance = acm;
urb = usb_alloc_urb(0, GFP_KERNEL);
if (!urb)
goto alloc_fail6;
urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
urb->transfer_dma = rb->dma;
if (acm->is_int_ep) {
usb_fill_int_urb(urb, acm->dev,
acm->rx_endpoint,
rb->base,
acm->readsize,
acm_read_bulk_callback, rb,
acm->bInterval);
} else {
usb_fill_bulk_urb(urb, acm->dev,
acm->rx_endpoint,
rb->base,
acm->readsize,
acm_read_bulk_callback, rb);
}
acm->read_urbs[i] = urb;
__set_bit(i, &acm->read_urbs_free);
}
for (i = 0; i < ACM_NW; i++) {
struct acm_wb *snd = &(acm->wb[i]);
snd->urb = usb_alloc_urb(0, GFP_KERNEL);
if (snd->urb == NULL)
goto alloc_fail7;
if (usb_endpoint_xfer_int(epwrite))
usb_fill_int_urb(snd->urb, usb_dev,
usb_sndintpipe(usb_dev, epwrite->bEndpointAddress),
NULL, acm->writesize, acm_write_bulk, snd, epwrite->bInterval);
else
usb_fill_bulk_urb(snd->urb, usb_dev,
usb_sndbulkpipe(usb_dev, epwrite->bEndpointAddress),
NULL, acm->writesize, acm_write_bulk, snd);
snd->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
if (quirks & SEND_ZERO_PACKET)
snd->urb->transfer_flags |= URB_ZERO_PACKET;
snd->instance = acm;
}
usb_set_intfdata(intf, acm);
i = device_create_file(&intf->dev, &dev_attr_bmCapabilities);
if (i < 0)
goto alloc_fail7;
if (cfd) { /* export the country data */
acm->country_codes = kmalloc(cfd->bLength - 4, GFP_KERNEL);
if (!acm->country_codes)
goto skip_countries;
acm->country_code_size = cfd->bLength - 4;
memcpy(acm->country_codes, (u8 *)&cfd->wCountyCode0,
cfd->bLength - 4);
acm->country_rel_date = cfd->iCountryCodeRelDate;
i = device_create_file(&intf->dev, &dev_attr_wCountryCodes);
if (i < 0) {
kfree(acm->country_codes);
acm->country_codes = NULL;
acm->country_code_size = 0;
goto skip_countries;
}
i = device_create_file(&intf->dev,
&dev_attr_iCountryCodeRelDate);
if (i < 0) {
device_remove_file(&intf->dev, &dev_attr_wCountryCodes);
kfree(acm->country_codes);
acm->country_codes = NULL;
acm->country_code_size = 0;
goto skip_countries;
}
}
skip_countries:
usb_fill_int_urb(acm->ctrlurb, usb_dev,
usb_rcvintpipe(usb_dev, epctrl->bEndpointAddress),
acm->ctrl_buffer, ctrlsize, acm_ctrl_irq, acm,
/* works around buggy devices */
epctrl->bInterval ? epctrl->bInterval : 16);
acm->ctrlurb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
acm->ctrlurb->transfer_dma = acm->ctrl_dma;
dev_info(&intf->dev, "ttyACM%d: USB ACM device\n", minor);
acm->line.dwDTERate = cpu_to_le32(9600);
acm->line.bDataBits = 8;
acm_set_line(acm, &acm->line);
usb_driver_claim_interface(&acm_driver, data_interface, acm);
usb_set_intfdata(data_interface, acm);
usb_get_intf(control_interface);
tty_dev = tty_port_register_device(&acm->port, acm_tty_driver, minor,
&control_interface->dev);
if (IS_ERR(tty_dev)) {
rv = PTR_ERR(tty_dev);
goto alloc_fail8;
}
if (quirks & CLEAR_HALT_CONDITIONS) {
usb_clear_halt(usb_dev, usb_rcvbulkpipe(usb_dev, epread->bEndpointAddress));
usb_clear_halt(usb_dev, usb_sndbulkpipe(usb_dev, epwrite->bEndpointAddress));
}
return 0;
alloc_fail8:
if (acm->country_codes) {
device_remove_file(&acm->control->dev,
&dev_attr_wCountryCodes);
device_remove_file(&acm->control->dev,
&dev_attr_iCountryCodeRelDate);
kfree(acm->country_codes);
}
device_remove_file(&acm->control->dev, &dev_attr_bmCapabilities);
alloc_fail7:
usb_set_intfdata(intf, NULL);
for (i = 0; i < ACM_NW; i++)
usb_free_urb(acm->wb[i].urb);
alloc_fail6:
for (i = 0; i < num_rx_buf; i++)
usb_free_urb(acm->read_urbs[i]);
acm_read_buffers_free(acm);
usb_free_urb(acm->ctrlurb);
alloc_fail5:
acm_write_buffers_free(acm);
alloc_fail4:
usb_free_coherent(usb_dev, ctrlsize, acm->ctrl_buffer, acm->ctrl_dma);
alloc_fail2:
acm_release_minor(acm);
kfree(acm);
alloc_fail:
return rv;
}
Commit Message: USB: cdc-acm: more sanity checking
An attack has become available which pretends to be a quirky
device circumventing normal sanity checks and crashes the kernel
by an insufficient number of interfaces. This patch adds a check
to the code path for quirky devices.
Signed-off-by: Oliver Neukum <[email protected]>
CC: [email protected]
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: void dump_backtrace_entry(unsigned long where, unsigned long from, unsigned long frame)
{
#ifdef CONFIG_KALLSYMS
printk("[<%08lx>] (%pS) from [<%08lx>] (%pS)\n", where, (void *)where, from, (void *)from);
#else
printk("Function entered at [<%08lx>] from [<%08lx>]\n", where, from);
#endif
if (in_exception_text(where))
dump_mem("", "Exception stack", frame + 4, frame + 4 + sizeof(struct pt_regs));
}
Commit Message: ARM: 7735/2: Preserve the user r/w register TPIDRURW on context switch and fork
Since commit 6a1c53124aa1 the user writeable TLS register was zeroed to
prevent it from being used as a covert channel between two tasks.
There are more and more applications coming to Windows RT,
Wine could support them, but mostly they expect to have
the thread environment block (TEB) in TPIDRURW.
This patch preserves that register per thread instead of clearing it.
Unlike the TPIDRURO, which is already switched, the TPIDRURW
can be updated from userspace so needs careful treatment in the case that we
modify TPIDRURW and call fork(). To avoid this we must always read
TPIDRURW in copy_thread.
Signed-off-by: André Hentschel <[email protected]>
Signed-off-by: Will Deacon <[email protected]>
Signed-off-by: Jonathan Austin <[email protected]>
Signed-off-by: Russell King <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: explicit FastPackedObjectElementsAccessor(const char* name)
: FastSmiOrObjectElementsAccessor<
FastPackedObjectElementsAccessor,
ElementsKindTraits<FAST_ELEMENTS> >(name) {}
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
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: TIFFNumberOfStrips(TIFF* tif)
{
TIFFDirectory *td = &tif->tif_dir;
uint32 nstrips;
/* If the value was already computed and store in td_nstrips, then return it,
since ChopUpSingleUncompressedStrip might have altered and resized the
since the td_stripbytecount and td_stripoffset arrays to the new value
after the initial affectation of td_nstrips = TIFFNumberOfStrips() in
tif_dirread.c ~line 3612.
See http://bugzilla.maptools.org/show_bug.cgi?id=2587 */
if( td->td_nstrips )
return td->td_nstrips;
nstrips = (td->td_rowsperstrip == (uint32) -1 ? 1 :
TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip));
if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
nstrips = _TIFFMultiply32(tif, nstrips, (uint32)td->td_samplesperpixel,
"TIFFNumberOfStrips");
return (nstrips);
}
Commit Message: * libtiff/tif_dirread.c: modify ChopUpSingleUncompressedStrip() to
instanciate compute ntrips as TIFFhowmany_32(td->td_imagelength, rowsperstrip),
instead of a logic based on the total size of data. Which is faulty is
the total size of data is not sufficient to fill the whole image, and thus
results in reading outside of the StripByCounts/StripOffsets arrays when
using TIFFReadScanline().
Reported by Agostino Sarubbo.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2608.
* libtiff/tif_strip.c: revert the change in TIFFNumberOfStrips() done
for http://bugzilla.maptools.org/show_bug.cgi?id=2587 / CVE-2016-9273 since
the above change is a better fix that makes it unnecessary.
CWE ID: CWE-125
Target: 1
Example 2:
Code: isofile_hd_cmp_key(const struct archive_rb_node *n, const void *key)
{
const struct hardlink *h = (const struct hardlink *)n;
return (strcmp(archive_entry_pathname(h->file_list.first->entry),
(const char *)key));
}
Commit Message: Issue 711: Be more careful about verifying filename lengths when writing ISO9660 archives
* Don't cast size_t to int, since this can lead to overflow
on machines where sizeof(int) < sizeof(size_t)
* Check a + b > limit by writing it as
a > limit || b > limit || a + b > limit
to avoid problems when a + b wraps around.
CWE ID: CWE-190
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: prefix_components (char *filename, bool checkdirs)
{
int count = 0;
struct stat stat_buf;
int stat_result;
char *f = filename + FILE_SYSTEM_PREFIX_LEN (filename);
if (*f)
while (*++f)
if (ISSLASH (f[0]) && ! ISSLASH (f[-1]))
{
if (checkdirs)
{
*f = '\0';
stat_result = safe_stat (filename, &stat_buf);
*f = '/';
if (! (stat_result == 0 && S_ISDIR (stat_buf.st_mode)))
break;
}
count++;
}
return count;
}
Commit Message:
CWE ID: CWE-78
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SProcXFixesQueryVersion(ClientPtr client)
{
REQUEST(xXFixesQueryVersionReq);
swaps(&stuff->length);
swapl(&stuff->majorVersion);
return (*ProcXFixesVector[stuff->xfixesReqType]) (client);
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: SkBitmap Clipboard::ReadImage(Buffer buffer) const {
ScopedGObject<GdkPixbuf>::Type pixbuf(
gtk_clipboard_wait_for_image(clipboard_));
if (!pixbuf.get())
return SkBitmap();
gfx::CanvasSkia canvas(gdk_pixbuf_get_width(pixbuf.get()),
gdk_pixbuf_get_height(pixbuf.get()),
false);
{
skia::ScopedPlatformPaint scoped_platform_paint(canvas.sk_canvas());
cairo_t* context = scoped_platform_paint.GetPlatformSurface();
gdk_cairo_set_source_pixbuf(context, pixbuf.get(), 0.0, 0.0);
cairo_paint(context);
}
return canvas.ExtractBitmap();
}
Commit Message: Use XFixes to update the clipboard sequence number.
BUG=73478
TEST=manual testing
Review URL: http://codereview.chromium.org/8501002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109528 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: menu_add(WebKitWebView *page, GArray *argv, GString *result) {
(void) page;
(void) result;
add_to_menu(argv, WEBKIT_HIT_TEST_RESULT_CONTEXT_DOCUMENT);
}
Commit Message: disable Uzbl javascript object because of security problem.
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int handle_exception(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct kvm_run *kvm_run = vcpu->run;
u32 intr_info, ex_no, error_code;
unsigned long cr2, rip, dr6;
u32 vect_info;
enum emulation_result er;
vect_info = vmx->idt_vectoring_info;
intr_info = vmx->exit_intr_info;
if (is_machine_check(intr_info))
return handle_machine_check(vcpu);
if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR)
return 1; /* already handled by vmx_vcpu_run() */
if (is_no_device(intr_info)) {
vmx_fpu_activate(vcpu);
return 1;
}
if (is_invalid_opcode(intr_info)) {
if (is_guest_mode(vcpu)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
if (er != EMULATE_DONE)
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
error_code = 0;
if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
/*
* The #PF with PFEC.RSVD = 1 indicates the guest is accessing
* MMIO, it is better to report an internal error.
* See the comments in vmx_handle_exit.
*/
if ((vect_info & VECTORING_INFO_VALID_MASK) &&
!(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
vcpu->run->internal.ndata = 3;
vcpu->run->internal.data[0] = vect_info;
vcpu->run->internal.data[1] = intr_info;
vcpu->run->internal.data[2] = error_code;
return 0;
}
if (is_page_fault(intr_info)) {
/* EPT won't cause page fault directly */
BUG_ON(enable_ept);
cr2 = vmcs_readl(EXIT_QUALIFICATION);
trace_kvm_page_fault(cr2, error_code);
if (kvm_event_needs_reinjection(vcpu))
kvm_mmu_unprotect_page_virt(vcpu, cr2);
return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
}
ex_no = intr_info & INTR_INFO_VECTOR_MASK;
if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
return handle_rmode_exception(vcpu, ex_no, error_code);
switch (ex_no) {
case AC_VECTOR:
kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
return 1;
case DB_VECTOR:
dr6 = vmcs_readl(EXIT_QUALIFICATION);
if (!(vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
vcpu->arch.dr6 &= ~15;
vcpu->arch.dr6 |= dr6 | DR6_RTM;
if (!(dr6 & ~DR6_RESERVED)) /* icebp */
skip_emulated_instruction(vcpu);
kvm_queue_exception(vcpu, DB_VECTOR);
return 1;
}
kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
/* fall through */
case BP_VECTOR:
/*
* Update instruction length as we may reinject #BP from
* user space while in guest debugging mode. Reading it for
* #DB as well causes no harm, it is not used in that case.
*/
vmx->vcpu.arch.event_exit_inst_len =
vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
kvm_run->exit_reason = KVM_EXIT_DEBUG;
rip = kvm_rip_read(vcpu);
kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
kvm_run->debug.arch.exception = ex_no;
break;
default:
kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
kvm_run->ex.exception = ex_no;
kvm_run->ex.error_code = error_code;
break;
}
return 0;
}
Commit Message: kvm: nVMX: Allow L1 to intercept software exceptions (#BP and #OF)
When L2 exits to L0 due to "exception or NMI", software exceptions
(#BP and #OF) for which L1 has requested an intercept should be
handled by L1 rather than L0. Previously, only hardware exceptions
were forwarded to L1.
Signed-off-by: Jim Mattson <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-388
Target: 1
Example 2:
Code: xmlParse3986URIReference(xmlURIPtr uri, const char *str) {
int ret;
if (str == NULL)
return(-1);
xmlCleanURI(uri);
/*
* Try first to parse absolute refs, then fallback to relative if
* it fails.
*/
ret = xmlParse3986URI(uri, str);
if (ret != 0) {
xmlCleanURI(uri);
ret = xmlParse3986RelativeRef(uri, str);
if (ret != 0) {
xmlCleanURI(uri);
return(ret);
}
}
return(0);
}
Commit Message: DO NOT MERGE: Use correct limit for port values
no upstream report yet, add it here when we have it
issue found & patch by nmehta@
Bug: 36555370
Change-Id: Ibf1efea554b95f514e23e939363d608021de4614
(cherry picked from commit b62884fb49fe92081e414966d9b5fe58250ae53c)
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: _eXosip_is_public_address (const char *c_address)
{
return (0 != strncmp (c_address, "192.168", 7)
&& 0 != strncmp (c_address, "10.", 3)
&& 0 != strncmp (c_address, "172.16.", 7)
&& 0 != strncmp (c_address, "172.17.", 7)
&& 0 != strncmp (c_address, "172.18.", 7)
&& 0 != strncmp (c_address, "172.19.", 7)
&& 0 != strncmp (c_address, "172.20.", 7)
&& 0 != strncmp (c_address, "172.21.", 7)
&& 0 != strncmp (c_address, "172.22.", 7)
&& 0 != strncmp (c_address, "172.23.", 7)
&& 0 != strncmp (c_address, "172.24.", 7)
&& 0 != strncmp (c_address, "172.25.", 7)
&& 0 != strncmp (c_address, "172.26.", 7)
&& 0 != strncmp (c_address, "172.27.", 7)
&& 0 != strncmp (c_address, "172.28.", 7)
&& 0 != strncmp (c_address, "172.29.", 7)
&& 0 != strncmp (c_address, "172.30.", 7)
&& 0 != strncmp (c_address, "172.31.", 7)
&& 0 != strncmp (c_address, "169.254", 7));
}
Commit Message:
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: download::DownloadInterruptReason DownloadManagerImpl::BeginDownloadRequest(
std::unique_ptr<net::URLRequest> url_request,
ResourceContext* resource_context,
download::DownloadUrlParameters* params) {
if (ResourceDispatcherHostImpl::Get()->is_shutdown())
return download::DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN;
ResourceDispatcherHostImpl::Get()->InitializeURLRequest(
url_request.get(),
Referrer(params->referrer(),
Referrer::NetReferrerPolicyToBlinkReferrerPolicy(
params->referrer_policy())),
true, // download.
params->render_process_host_id(), params->render_view_host_routing_id(),
params->render_frame_host_routing_id(), PREVIEWS_OFF, resource_context);
url_request->set_first_party_url_policy(
net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
const GURL& url = url_request->original_url();
const net::URLRequestContext* request_context = url_request->context();
if (!request_context->job_factory()->IsHandledProtocol(url.scheme())) {
DVLOG(1) << "Download request for unsupported protocol: "
<< url.possibly_invalid_spec();
return download::DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST;
}
std::unique_ptr<ResourceHandler> handler(
DownloadResourceHandler::CreateForNewRequest(
url_request.get(), params->request_origin(),
params->download_source(), params->follow_cross_origin_redirects()));
ResourceDispatcherHostImpl::Get()->BeginURLRequest(
std::move(url_request), std::move(handler), true, // download
params->content_initiated(), params->do_not_prompt_for_login(),
resource_context);
return download::DOWNLOAD_INTERRUPT_REASON_NONE;
}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <[email protected]>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629547}
CWE ID: CWE-284
Target: 1
Example 2:
Code: static void djvu_close_lc(LoadContext* lc)
{
if (lc->document)
ddjvu_document_release(lc->document);
if (lc->context)
ddjvu_context_release(lc->context);
if (lc->page)
ddjvu_page_release(lc->page);
RelinquishMagickMemory(lc);
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ImageInputType::handleDOMActivateEvent(Event* event)
{
RefPtrWillBeRawPtr<HTMLInputElement> element(this->element());
if (element->isDisabledFormControl() || !element->form())
return;
element->setActivatedSubmit(true);
m_clickLocation = extractClickLocation(event);
element->form()->prepareForSubmission(event); // Event handlers can run.
element->setActivatedSubmit(false);
event->setDefaultHandled();
}
Commit Message: ImageInputType::ensurePrimaryContent should recreate UA shadow tree.
Once the fallback shadow tree was created, it was never recreated even if
ensurePrimaryContent was called. Such situation happens by updating |src|
attribute.
BUG=589838
Review URL: https://codereview.chromium.org/1732753004
Cr-Commit-Position: refs/heads/master@{#377804}
CWE ID: CWE-361
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: cpStripToTile(uint8* out, uint8* in,
uint32 rows, uint32 cols, int outskew, int inskew)
{
while (rows-- > 0) {
uint32 j = cols;
while (j-- > 0)
*out++ = *in++;
out += outskew;
in += inskew;
}
}
Commit Message: * tools/tiffcp.c: fix uint32 underflow/overflow that can cause heap-based
buffer overflow.
Reported by Agostino Sarubbo.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2610
CWE ID: CWE-190
Target: 1
Example 2:
Code: void FileAPIMessageFilter::OnSyncGetPlatformPath(
const GURL& path, FilePath* platform_path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DCHECK(platform_path);
*platform_path = FilePath();
FileSystemURL url(path);
if (!url.is_valid())
return;
base::PlatformFileError error;
if (!HasPermissionsForFile(url, kReadFilePermissions, &error))
return;
LocalFileSystemOperation* operation =
context_->CreateFileSystemOperation(
url, NULL)->AsLocalFileSystemOperation();
DCHECK(operation);
if (!operation)
return;
operation->SyncGetPlatformPath(url, platform_path);
if (!ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
process_id_, *platform_path)) {
ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
process_id_, *platform_path);
}
}
Commit Message: File permission fix: now we selectively grant read permission for Sandboxed files
We also need to check the read permission and call GrantReadFile() for
sandboxed files for CreateSnapshotFile().
BUG=162114
TEST=manual
Review URL: https://codereview.chromium.org/11280231
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@170181 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int asf_read_packet(AVFormatContext *s, AVPacket *pkt)
{
ASFContext *asf = s->priv_data;
for (;;) {
int ret;
/* parse cached packets, if any */
if ((ret = asf_parse_packet(s, s->pb, pkt)) <= 0)
return ret;
if ((ret = asf_get_packet(s, s->pb)) < 0)
assert(asf->packet_size_left < FRAME_HEADER_SIZE ||
asf->packet_segments < 1);
asf->packet_time_start = 0;
}
}
Commit Message: avformat/asfdec: Fix DoS in asf_build_simple_index()
Fixes: Missing EOF check in loop
No testcase
Found-by: Xiaohei and Wangchu from Alibaba Security Team
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void FocusInCallback(IBusPanelService* panel,
const gchar* path,
gpointer user_data) {
g_return_if_fail(user_data);
InputMethodStatusConnection* self
= static_cast<InputMethodStatusConnection*>(user_data);
self->FocusIn(path);
}
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
Target: 1
Example 2:
Code: void nntp_hash_destructor(int type, void *obj, intptr_t data)
{
nntp_data_free(obj);
}
Commit Message: sanitise cache paths
Co-authored-by: JerikoOne <[email protected]>
CWE ID: CWE-22
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: LayerTreeHostTestDeferCommits()
: num_will_begin_impl_frame_(0), num_send_begin_main_frame_(0) {}
Commit Message: (Reland) Discard compositor frames from unloaded web content
This is a reland of https://codereview.chromium.org/2707243005/ with a
small change to fix an uninitialized memory error that fails on MSAN
bots.
BUG=672847
[email protected], [email protected]
CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2731283003
Cr-Commit-Position: refs/heads/master@{#454954}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int cipso_v4_validate(const struct sk_buff *skb, unsigned char **option)
{
unsigned char *opt = *option;
unsigned char *tag;
unsigned char opt_iter;
unsigned char err_offset = 0;
u8 opt_len;
u8 tag_len;
struct cipso_v4_doi *doi_def = NULL;
u32 tag_iter;
/* caller already checks for length values that are too large */
opt_len = opt[1];
if (opt_len < 8) {
err_offset = 1;
goto validate_return;
}
rcu_read_lock();
doi_def = cipso_v4_doi_search(get_unaligned_be32(&opt[2]));
if (doi_def == NULL) {
err_offset = 2;
goto validate_return_locked;
}
opt_iter = CIPSO_V4_HDR_LEN;
tag = opt + opt_iter;
while (opt_iter < opt_len) {
for (tag_iter = 0; doi_def->tags[tag_iter] != tag[0];)
if (doi_def->tags[tag_iter] == CIPSO_V4_TAG_INVALID ||
++tag_iter == CIPSO_V4_TAG_MAXCNT) {
err_offset = opt_iter;
goto validate_return_locked;
}
tag_len = tag[1];
if (tag_len > (opt_len - opt_iter)) {
err_offset = opt_iter + 1;
goto validate_return_locked;
}
switch (tag[0]) {
case CIPSO_V4_TAG_RBITMAP:
if (tag_len < CIPSO_V4_TAG_RBM_BLEN) {
err_offset = opt_iter + 1;
goto validate_return_locked;
}
/* We are already going to do all the verification
* necessary at the socket layer so from our point of
* view it is safe to turn these checks off (and less
* work), however, the CIPSO draft says we should do
* all the CIPSO validations here but it doesn't
* really specify _exactly_ what we need to validate
* ... so, just make it a sysctl tunable. */
if (cipso_v4_rbm_strictvalid) {
if (cipso_v4_map_lvl_valid(doi_def,
tag[3]) < 0) {
err_offset = opt_iter + 3;
goto validate_return_locked;
}
if (tag_len > CIPSO_V4_TAG_RBM_BLEN &&
cipso_v4_map_cat_rbm_valid(doi_def,
&tag[4],
tag_len - 4) < 0) {
err_offset = opt_iter + 4;
goto validate_return_locked;
}
}
break;
case CIPSO_V4_TAG_ENUM:
if (tag_len < CIPSO_V4_TAG_ENUM_BLEN) {
err_offset = opt_iter + 1;
goto validate_return_locked;
}
if (cipso_v4_map_lvl_valid(doi_def,
tag[3]) < 0) {
err_offset = opt_iter + 3;
goto validate_return_locked;
}
if (tag_len > CIPSO_V4_TAG_ENUM_BLEN &&
cipso_v4_map_cat_enum_valid(doi_def,
&tag[4],
tag_len - 4) < 0) {
err_offset = opt_iter + 4;
goto validate_return_locked;
}
break;
case CIPSO_V4_TAG_RANGE:
if (tag_len < CIPSO_V4_TAG_RNG_BLEN) {
err_offset = opt_iter + 1;
goto validate_return_locked;
}
if (cipso_v4_map_lvl_valid(doi_def,
tag[3]) < 0) {
err_offset = opt_iter + 3;
goto validate_return_locked;
}
if (tag_len > CIPSO_V4_TAG_RNG_BLEN &&
cipso_v4_map_cat_rng_valid(doi_def,
&tag[4],
tag_len - 4) < 0) {
err_offset = opt_iter + 4;
goto validate_return_locked;
}
break;
case CIPSO_V4_TAG_LOCAL:
/* This is a non-standard tag that we only allow for
* local connections, so if the incoming interface is
* not the loopback device drop the packet. */
if (!(skb->dev->flags & IFF_LOOPBACK)) {
err_offset = opt_iter;
goto validate_return_locked;
}
if (tag_len != CIPSO_V4_TAG_LOC_BLEN) {
err_offset = opt_iter + 1;
goto validate_return_locked;
}
break;
default:
err_offset = opt_iter;
goto validate_return_locked;
}
tag += tag_len;
opt_iter += tag_len;
}
validate_return_locked:
rcu_read_unlock();
validate_return:
*option = opt + err_offset;
return err_offset;
}
Commit Message: cipso: don't follow a NULL pointer when setsockopt() is called
As reported by Alan Cox, and verified by Lin Ming, when a user
attempts to add a CIPSO option to a socket using the CIPSO_V4_TAG_LOCAL
tag the kernel dies a terrible death when it attempts to follow a NULL
pointer (the skb argument to cipso_v4_validate() is NULL when called via
the setsockopt() syscall).
This patch fixes this by first checking to ensure that the skb is
non-NULL before using it to find the incoming network interface. In
the unlikely case where the skb is NULL and the user attempts to add
a CIPSO option with the _TAG_LOCAL tag we return an error as this is
not something we want to allow.
A simple reproducer, kindly supplied by Lin Ming, although you must
have the CIPSO DOI #3 configure on the system first or you will be
caught early in cipso_v4_validate():
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <string.h>
struct local_tag {
char type;
char length;
char info[4];
};
struct cipso {
char type;
char length;
char doi[4];
struct local_tag local;
};
int main(int argc, char **argv)
{
int sockfd;
struct cipso cipso = {
.type = IPOPT_CIPSO,
.length = sizeof(struct cipso),
.local = {
.type = 128,
.length = sizeof(struct local_tag),
},
};
memset(cipso.doi, 0, 4);
cipso.doi[3] = 3;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
#define SOL_IP 0
setsockopt(sockfd, SOL_IP, IP_OPTIONS,
&cipso, sizeof(struct cipso));
return 0;
}
CC: Lin Ming <[email protected]>
Reported-by: Alan Cox <[email protected]>
Signed-off-by: Paul Moore <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: void VerifyRemoveFromCache(base::PlatformFileError error,
const std::string& resource_id,
const std::string& md5) {
++num_callback_invocations_;
EXPECT_EQ(expected_error_, error);
GDataRootDirectory::CacheEntry* entry =
file_system_->root_->GetCacheEntry(resource_id, md5);
if (entry)
EXPECT_TRUE(entry->IsDirty());
std::vector<PathToVerify> paths_to_verify;
paths_to_verify.push_back( // Index 0: CACHE_TYPE_TMP.
PathToVerify(file_system_->GetCacheFilePath(resource_id, "*",
GDataRootDirectory::CACHE_TYPE_TMP,
GDataFileSystem::CACHED_FILE_FROM_SERVER), FilePath()));
paths_to_verify.push_back( // Index 1: CACHE_TYPE_PERSISTENT.
PathToVerify(file_system_->GetCacheFilePath(resource_id, "*",
GDataRootDirectory::CACHE_TYPE_PERSISTENT,
GDataFileSystem::CACHED_FILE_FROM_SERVER), FilePath()));
paths_to_verify.push_back( // Index 2: CACHE_TYPE_PINNED.
PathToVerify(file_system_->GetCacheFilePath(resource_id, "",
GDataRootDirectory::CACHE_TYPE_PINNED,
GDataFileSystem::CACHED_FILE_FROM_SERVER), FilePath()));
paths_to_verify.push_back( // Index 3: CACHE_TYPE_OUTGOING.
PathToVerify(file_system_->GetCacheFilePath(resource_id, "",
GDataRootDirectory::CACHE_TYPE_OUTGOING,
GDataFileSystem::CACHED_FILE_FROM_SERVER), FilePath()));
if (!entry) {
for (size_t i = 0; i < paths_to_verify.size(); ++i) {
file_util::FileEnumerator enumerator(
paths_to_verify[i].path_to_scan.DirName(), false /* not recursive*/,
static_cast<file_util::FileEnumerator::FileType>(
file_util::FileEnumerator::FILES |
file_util::FileEnumerator::SHOW_SYM_LINKS),
paths_to_verify[i].path_to_scan.BaseName().value());
EXPECT_TRUE(enumerator.Next().empty());
}
} else {
paths_to_verify[1].expected_existing_path =
GetCacheFilePath(resource_id,
std::string(),
GDataRootDirectory::CACHE_TYPE_PERSISTENT,
GDataFileSystem::CACHED_FILE_LOCALLY_MODIFIED);
paths_to_verify[3].expected_existing_path =
GetCacheFilePath(resource_id,
std::string(),
GDataRootDirectory::CACHE_TYPE_OUTGOING,
GDataFileSystem::CACHED_FILE_FROM_SERVER);
if (entry->IsPinned()) {
paths_to_verify[2].expected_existing_path =
GetCacheFilePath(resource_id,
std::string(),
GDataRootDirectory::CACHE_TYPE_PINNED,
GDataFileSystem::CACHED_FILE_FROM_SERVER);
}
for (size_t i = 0; i < paths_to_verify.size(); ++i) {
const struct PathToVerify& verify = paths_to_verify[i];
file_util::FileEnumerator enumerator(
verify.path_to_scan.DirName(), false /* not recursive*/,
static_cast<file_util::FileEnumerator::FileType>(
file_util::FileEnumerator::FILES |
file_util::FileEnumerator::SHOW_SYM_LINKS),
verify.path_to_scan.BaseName().value());
size_t num_files_found = 0;
for (FilePath current = enumerator.Next(); !current.empty();
current = enumerator.Next()) {
++num_files_found;
EXPECT_EQ(verify.expected_existing_path, current);
}
if (verify.expected_existing_path.empty())
EXPECT_EQ(0U, num_files_found);
else
EXPECT_EQ(1U, num_files_found);
}
}
}
Commit Message: gdata: Define the resource ID for the root directory
Per the spec, the resource ID for the root directory is defined
as "folder:root". Add the resource ID to the root directory in our
file system representation so we can look up the root directory by
the resource ID.
BUG=127697
TEST=add unit tests
Review URL: https://chromiumcodereview.appspot.com/10332253
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137928 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool DataReductionProxySettings::IsDataSaverEnabledByUser() const {
//// static
if (params::ShouldForceEnableDataReductionProxy())
return true;
if (spdy_proxy_auth_enabled_.GetPrefName().empty())
return false;
return spdy_proxy_auth_enabled_.GetValue();
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Commit-Queue: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SoftAVC::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
Target: 1
Example 2:
Code: cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
{
struct task_group *parent = css_tg(parent_css);
struct task_group *tg;
if (!parent) {
/* This is early initialization for the top cgroup */
return &root_task_group.css;
}
tg = sched_create_group(parent);
if (IS_ERR(tg))
return ERR_PTR(-ENOMEM);
return &tg->css;
}
Commit Message: sched: Fix information leak in sys_sched_getattr()
We're copying the on-stack structure to userspace, but forgot to give
the right number of bytes to copy. This allows the calling process to
obtain up to PAGE_SIZE bytes from the stack (and possibly adjacent
kernel memory).
This fix copies only as much as we actually have on the stack
(attr->size defaults to the size of the struct) and leaves the rest of
the userspace-provided buffer untouched.
Found using kmemcheck + trinity.
Fixes: d50dde5a10f30 ("sched: Add new scheduler syscalls to support an extended scheduling parameters ABI")
Cc: Dario Faggioli <[email protected]>
Cc: Juri Lelli <[email protected]>
Cc: Ingo Molnar <[email protected]>
Signed-off-by: Vegard Nossum <[email protected]>
Signed-off-by: Peter Zijlstra <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Thomas Gleixner <[email protected]>
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int ipmi_get_smi_info(int if_num, struct ipmi_smi_info *data)
{
int rv, index;
struct ipmi_smi *intf;
index = srcu_read_lock(&ipmi_interfaces_srcu);
list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
if (intf->intf_num == if_num)
goto found;
}
srcu_read_unlock(&ipmi_interfaces_srcu, index);
/* Not found, return an error */
return -EINVAL;
found:
if (!intf->handlers->get_smi_info)
rv = -ENOTTY;
else
rv = intf->handlers->get_smi_info(intf->send_info, data);
srcu_read_unlock(&ipmi_interfaces_srcu, index);
return rv;
}
Commit Message: ipmi: fix use-after-free of user->release_barrier.rda
When we do the following test, we got oops in ipmi_msghandler driver
while((1))
do
service ipmievd restart & service ipmievd restart
done
---------------------------------------------------------------
[ 294.230186] Unable to handle kernel paging request at virtual address 0000803fea6ea008
[ 294.230188] Mem abort info:
[ 294.230190] ESR = 0x96000004
[ 294.230191] Exception class = DABT (current EL), IL = 32 bits
[ 294.230193] SET = 0, FnV = 0
[ 294.230194] EA = 0, S1PTW = 0
[ 294.230195] Data abort info:
[ 294.230196] ISV = 0, ISS = 0x00000004
[ 294.230197] CM = 0, WnR = 0
[ 294.230199] user pgtable: 4k pages, 48-bit VAs, pgdp = 00000000a1c1b75a
[ 294.230201] [0000803fea6ea008] pgd=0000000000000000
[ 294.230204] Internal error: Oops: 96000004 [#1] SMP
[ 294.235211] Modules linked in: nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm iw_cm dm_mirror dm_region_hash dm_log dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ghash_ce sha2_ce ses sha256_arm64 sha1_ce hibmc_drm hisi_sas_v2_hw enclosure sg hisi_sas_main sbsa_gwdt ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe ipmi_si mdio hns_dsaf ipmi_devintf ipmi_msghandler hns_enet_drv hns_mdio
[ 294.277745] CPU: 3 PID: 0 Comm: swapper/3 Kdump: loaded Not tainted 5.0.0-rc2+ #113
[ 294.285511] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017
[ 294.292835] pstate: 80000005 (Nzcv daif -PAN -UAO)
[ 294.297695] pc : __srcu_read_lock+0x38/0x58
[ 294.301940] lr : acquire_ipmi_user+0x2c/0x70 [ipmi_msghandler]
[ 294.307853] sp : ffff00001001bc80
[ 294.311208] x29: ffff00001001bc80 x28: ffff0000117e5000
[ 294.316594] x27: 0000000000000000 x26: dead000000000100
[ 294.321980] x25: dead000000000200 x24: ffff803f6bd06800
[ 294.327366] x23: 0000000000000000 x22: 0000000000000000
[ 294.332752] x21: ffff00001001bd04 x20: ffff80df33d19018
[ 294.338137] x19: ffff80df33d19018 x18: 0000000000000000
[ 294.343523] x17: 0000000000000000 x16: 0000000000000000
[ 294.348908] x15: 0000000000000000 x14: 0000000000000002
[ 294.354293] x13: 0000000000000000 x12: 0000000000000000
[ 294.359679] x11: 0000000000000000 x10: 0000000000100000
[ 294.365065] x9 : 0000000000000000 x8 : 0000000000000004
[ 294.370451] x7 : 0000000000000000 x6 : ffff80df34558678
[ 294.375836] x5 : 000000000000000c x4 : 0000000000000000
[ 294.381221] x3 : 0000000000000001 x2 : 0000803fea6ea000
[ 294.386607] x1 : 0000803fea6ea008 x0 : 0000000000000001
[ 294.391994] Process swapper/3 (pid: 0, stack limit = 0x0000000083087293)
[ 294.398791] Call trace:
[ 294.401266] __srcu_read_lock+0x38/0x58
[ 294.405154] acquire_ipmi_user+0x2c/0x70 [ipmi_msghandler]
[ 294.410716] deliver_response+0x80/0xf8 [ipmi_msghandler]
[ 294.416189] deliver_local_response+0x28/0x68 [ipmi_msghandler]
[ 294.422193] handle_one_recv_msg+0x158/0xcf8 [ipmi_msghandler]
[ 294.432050] handle_new_recv_msgs+0xc0/0x210 [ipmi_msghandler]
[ 294.441984] smi_recv_tasklet+0x8c/0x158 [ipmi_msghandler]
[ 294.451618] tasklet_action_common.isra.5+0x88/0x138
[ 294.460661] tasklet_action+0x2c/0x38
[ 294.468191] __do_softirq+0x120/0x2f8
[ 294.475561] irq_exit+0x134/0x140
[ 294.482445] __handle_domain_irq+0x6c/0xc0
[ 294.489954] gic_handle_irq+0xb8/0x178
[ 294.497037] el1_irq+0xb0/0x140
[ 294.503381] arch_cpu_idle+0x34/0x1a8
[ 294.510096] do_idle+0x1d4/0x290
[ 294.516322] cpu_startup_entry+0x28/0x30
[ 294.523230] secondary_start_kernel+0x184/0x1d0
[ 294.530657] Code: d538d082 d2800023 8b010c81 8b020021 (c85f7c25)
[ 294.539746] ---[ end trace 8a7a880dee570b29 ]---
[ 294.547341] Kernel panic - not syncing: Fatal exception in interrupt
[ 294.556837] SMP: stopping secondary CPUs
[ 294.563996] Kernel Offset: disabled
[ 294.570515] CPU features: 0x002,21006008
[ 294.577638] Memory Limit: none
[ 294.587178] Starting crashdump kernel...
[ 294.594314] Bye!
Because the user->release_barrier.rda is freed in ipmi_destroy_user(), but
the refcount is not zero, when acquire_ipmi_user() uses user->release_barrier.rda
in __srcu_read_lock(), it causes oops.
Fix this by calling cleanup_srcu_struct() when the refcount is zero.
Fixes: e86ee2d44b44 ("ipmi: Rework locking and shutdown for hot remove")
Cc: [email protected] # 4.18
Signed-off-by: Yang Yingliang <[email protected]>
Signed-off-by: Corey Minyard <[email protected]>
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void OneClickSigninHelper::DidStopLoading(
content::RenderViewHost* render_view_host) {
content::WebContents* contents = web_contents();
const GURL url = contents->GetURL();
Profile* profile =
Profile::FromBrowserContext(contents->GetBrowserContext());
VLOG(1) << "OneClickSigninHelper::DidStopLoading: url=" << url.spec();
if (!error_message_.empty() && auto_accept_ == AUTO_ACCEPT_EXPLICIT) {
VLOG(1) << "OneClickSigninHelper::DidStopLoading: error=" << error_message_;
RemoveCurrentHistoryItem(contents);
Browser* browser = chrome::FindBrowserWithWebContents(contents);
RedirectToNtpOrAppsPage(web_contents(), source_);
ShowSigninErrorBubble(browser, error_message_);
CleanTransientState();
return;
}
if (AreWeShowingSignin(url, source_, email_)) {
if (!showing_signin_) {
if (source_ == SyncPromoUI::SOURCE_UNKNOWN)
LogOneClickHistogramValue(one_click_signin::HISTOGRAM_SHOWN);
else
LogHistogramValue(source_, one_click_signin::HISTOGRAM_SHOWN);
}
showing_signin_ = true;
}
GURL::Replacements replacements;
replacements.ClearQuery();
const bool continue_url_match = (
continue_url_.is_valid() &&
url.ReplaceComponents(replacements) ==
continue_url_.ReplaceComponents(replacements));
if (continue_url_match)
RemoveCurrentHistoryItem(contents);
if (email_.empty()) {
VLOG(1) << "OneClickSigninHelper::DidStopLoading: nothing to do";
if (continue_url_match && auto_accept_ == AUTO_ACCEPT_EXPLICIT)
RedirectToSignin();
std::string unused_value;
if (net::GetValueForKeyInQuery(url, "ntp", &unused_value)) {
SyncPromoUI::SetUserSkippedSyncPromo(profile);
RedirectToNtpOrAppsPage(web_contents(), source_);
}
if (!continue_url_match && !IsValidGaiaSigninRedirectOrResponseURL(url) &&
++untrusted_navigations_since_signin_visit_ > kMaxNavigationsSince) {
CleanTransientState();
}
return;
}
bool force_same_tab_navigation = false;
if (!continue_url_match && IsValidGaiaSigninRedirectOrResponseURL(url))
return;
if (auto_accept_ == AUTO_ACCEPT_EXPLICIT) {
DCHECK(source_ != SyncPromoUI::SOURCE_UNKNOWN);
if (!continue_url_match) {
VLOG(1) << "OneClickSigninHelper::DidStopLoading: invalid url='"
<< url.spec()
<< "' expected continue url=" << continue_url_;
CleanTransientState();
return;
}
SyncPromoUI::Source source =
SyncPromoUI::GetSourceForSyncPromoURL(url);
if (source != source_) {
original_source_ = source_;
source_ = source;
force_same_tab_navigation = source == SyncPromoUI::SOURCE_SETTINGS;
switched_to_advanced_ = source == SyncPromoUI::SOURCE_SETTINGS;
}
}
Browser* browser = chrome::FindBrowserWithWebContents(contents);
VLOG(1) << "OneClickSigninHelper::DidStopLoading: signin is go."
<< " auto_accept=" << auto_accept_
<< " source=" << source_;
switch (auto_accept_) {
case AUTO_ACCEPT_NONE:
if (showing_signin_)
LogOneClickHistogramValue(one_click_signin::HISTOGRAM_DISMISSED);
break;
case AUTO_ACCEPT_ACCEPTED:
LogOneClickHistogramValue(one_click_signin::HISTOGRAM_ACCEPTED);
LogOneClickHistogramValue(one_click_signin::HISTOGRAM_WITH_DEFAULTS);
SigninManager::DisableOneClickSignIn(profile);
StartSync(StartSyncArgs(profile, browser, auto_accept_,
session_index_, email_, password_,
false /* force_same_tab_navigation */,
true /* confirmation_required */, source_),
OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS);
break;
case AUTO_ACCEPT_CONFIGURE:
LogOneClickHistogramValue(one_click_signin::HISTOGRAM_ACCEPTED);
LogOneClickHistogramValue(one_click_signin::HISTOGRAM_WITH_ADVANCED);
SigninManager::DisableOneClickSignIn(profile);
StartSync(
StartSyncArgs(profile, browser, auto_accept_, session_index_, email_,
password_, false /* force_same_tab_navigation */,
false /* confirmation_required */, source_),
OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST);
break;
case AUTO_ACCEPT_EXPLICIT: {
if (switched_to_advanced_) {
LogHistogramValue(original_source_,
one_click_signin::HISTOGRAM_WITH_ADVANCED);
LogHistogramValue(original_source_,
one_click_signin::HISTOGRAM_ACCEPTED);
} else {
LogHistogramValue(source_, one_click_signin::HISTOGRAM_ACCEPTED);
LogHistogramValue(source_, one_click_signin::HISTOGRAM_WITH_DEFAULTS);
}
OneClickSigninSyncStarter::StartSyncMode start_mode =
source_ == SyncPromoUI::SOURCE_SETTINGS ?
OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST :
OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS;
std::string last_email =
profile->GetPrefs()->GetString(prefs::kGoogleServicesLastUsername);
if (!last_email.empty() && !gaia::AreEmailsSame(last_email, email_)) {
ConfirmEmailDialogDelegate::AskForConfirmation(
contents,
last_email,
email_,
base::Bind(
&StartExplicitSync,
StartSyncArgs(profile, browser, auto_accept_,
session_index_, email_, password_,
force_same_tab_navigation,
false /* confirmation_required */, source_),
contents,
start_mode));
} else {
StartSync(
StartSyncArgs(profile, browser, auto_accept_, session_index_,
email_, password_, force_same_tab_navigation,
untrusted_confirmation_required_, source_),
start_mode);
RedirectToNtpOrAppsPageIfNecessary(web_contents(), source_);
}
if (source_ == SyncPromoUI::SOURCE_SETTINGS &&
SyncPromoUI::GetSourceForSyncPromoURL(continue_url_) ==
SyncPromoUI::SOURCE_WEBSTORE_INSTALL) {
redirect_url_ = continue_url_;
ProfileSyncService* sync_service =
ProfileSyncServiceFactory::GetForProfile(profile);
if (sync_service)
sync_service->AddObserver(this);
}
break;
}
case AUTO_ACCEPT_REJECTED_FOR_PROFILE:
AddEmailToOneClickRejectedList(profile, email_);
LogOneClickHistogramValue(one_click_signin::HISTOGRAM_REJECTED);
break;
default:
NOTREACHED() << "Invalid auto_accept=" << auto_accept_;
break;
}
CleanTransientState();
}
Commit Message: Display confirmation dialog for untrusted signins
BUG=252062
Review URL: https://chromiumcodereview.appspot.com/17482002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int r_bin_dwarf_expand_cu(RBinDwarfCompUnit *cu) {
RBinDwarfDIE *tmp;
if (!cu || cu->capacity == 0 || cu->capacity != cu->length) {
return -EINVAL;
}
tmp = (RBinDwarfDIE*)realloc(cu->dies,
cu->capacity * 2 * sizeof(RBinDwarfDIE));
if (!tmp) {
return -ENOMEM;
}
memset ((ut8*)tmp + cu->capacity, 0, cu->capacity);
cu->dies = tmp;
cu->capacity *= 2;
return 0;
}
Commit Message: Fix #8813 - segfault in dwarf parser
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void free_user(struct kref *ref)
{
struct ipmi_user *user = container_of(ref, struct ipmi_user, refcount);
kfree(user);
}
Commit Message: ipmi: fix use-after-free of user->release_barrier.rda
When we do the following test, we got oops in ipmi_msghandler driver
while((1))
do
service ipmievd restart & service ipmievd restart
done
---------------------------------------------------------------
[ 294.230186] Unable to handle kernel paging request at virtual address 0000803fea6ea008
[ 294.230188] Mem abort info:
[ 294.230190] ESR = 0x96000004
[ 294.230191] Exception class = DABT (current EL), IL = 32 bits
[ 294.230193] SET = 0, FnV = 0
[ 294.230194] EA = 0, S1PTW = 0
[ 294.230195] Data abort info:
[ 294.230196] ISV = 0, ISS = 0x00000004
[ 294.230197] CM = 0, WnR = 0
[ 294.230199] user pgtable: 4k pages, 48-bit VAs, pgdp = 00000000a1c1b75a
[ 294.230201] [0000803fea6ea008] pgd=0000000000000000
[ 294.230204] Internal error: Oops: 96000004 [#1] SMP
[ 294.235211] Modules linked in: nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm iw_cm dm_mirror dm_region_hash dm_log dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ghash_ce sha2_ce ses sha256_arm64 sha1_ce hibmc_drm hisi_sas_v2_hw enclosure sg hisi_sas_main sbsa_gwdt ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe ipmi_si mdio hns_dsaf ipmi_devintf ipmi_msghandler hns_enet_drv hns_mdio
[ 294.277745] CPU: 3 PID: 0 Comm: swapper/3 Kdump: loaded Not tainted 5.0.0-rc2+ #113
[ 294.285511] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017
[ 294.292835] pstate: 80000005 (Nzcv daif -PAN -UAO)
[ 294.297695] pc : __srcu_read_lock+0x38/0x58
[ 294.301940] lr : acquire_ipmi_user+0x2c/0x70 [ipmi_msghandler]
[ 294.307853] sp : ffff00001001bc80
[ 294.311208] x29: ffff00001001bc80 x28: ffff0000117e5000
[ 294.316594] x27: 0000000000000000 x26: dead000000000100
[ 294.321980] x25: dead000000000200 x24: ffff803f6bd06800
[ 294.327366] x23: 0000000000000000 x22: 0000000000000000
[ 294.332752] x21: ffff00001001bd04 x20: ffff80df33d19018
[ 294.338137] x19: ffff80df33d19018 x18: 0000000000000000
[ 294.343523] x17: 0000000000000000 x16: 0000000000000000
[ 294.348908] x15: 0000000000000000 x14: 0000000000000002
[ 294.354293] x13: 0000000000000000 x12: 0000000000000000
[ 294.359679] x11: 0000000000000000 x10: 0000000000100000
[ 294.365065] x9 : 0000000000000000 x8 : 0000000000000004
[ 294.370451] x7 : 0000000000000000 x6 : ffff80df34558678
[ 294.375836] x5 : 000000000000000c x4 : 0000000000000000
[ 294.381221] x3 : 0000000000000001 x2 : 0000803fea6ea000
[ 294.386607] x1 : 0000803fea6ea008 x0 : 0000000000000001
[ 294.391994] Process swapper/3 (pid: 0, stack limit = 0x0000000083087293)
[ 294.398791] Call trace:
[ 294.401266] __srcu_read_lock+0x38/0x58
[ 294.405154] acquire_ipmi_user+0x2c/0x70 [ipmi_msghandler]
[ 294.410716] deliver_response+0x80/0xf8 [ipmi_msghandler]
[ 294.416189] deliver_local_response+0x28/0x68 [ipmi_msghandler]
[ 294.422193] handle_one_recv_msg+0x158/0xcf8 [ipmi_msghandler]
[ 294.432050] handle_new_recv_msgs+0xc0/0x210 [ipmi_msghandler]
[ 294.441984] smi_recv_tasklet+0x8c/0x158 [ipmi_msghandler]
[ 294.451618] tasklet_action_common.isra.5+0x88/0x138
[ 294.460661] tasklet_action+0x2c/0x38
[ 294.468191] __do_softirq+0x120/0x2f8
[ 294.475561] irq_exit+0x134/0x140
[ 294.482445] __handle_domain_irq+0x6c/0xc0
[ 294.489954] gic_handle_irq+0xb8/0x178
[ 294.497037] el1_irq+0xb0/0x140
[ 294.503381] arch_cpu_idle+0x34/0x1a8
[ 294.510096] do_idle+0x1d4/0x290
[ 294.516322] cpu_startup_entry+0x28/0x30
[ 294.523230] secondary_start_kernel+0x184/0x1d0
[ 294.530657] Code: d538d082 d2800023 8b010c81 8b020021 (c85f7c25)
[ 294.539746] ---[ end trace 8a7a880dee570b29 ]---
[ 294.547341] Kernel panic - not syncing: Fatal exception in interrupt
[ 294.556837] SMP: stopping secondary CPUs
[ 294.563996] Kernel Offset: disabled
[ 294.570515] CPU features: 0x002,21006008
[ 294.577638] Memory Limit: none
[ 294.587178] Starting crashdump kernel...
[ 294.594314] Bye!
Because the user->release_barrier.rda is freed in ipmi_destroy_user(), but
the refcount is not zero, when acquire_ipmi_user() uses user->release_barrier.rda
in __srcu_read_lock(), it causes oops.
Fix this by calling cleanup_srcu_struct() when the refcount is zero.
Fixes: e86ee2d44b44 ("ipmi: Rework locking and shutdown for hot remove")
Cc: [email protected] # 4.18
Signed-off-by: Yang Yingliang <[email protected]>
Signed-off-by: Corey Minyard <[email protected]>
CWE ID: CWE-416
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: virtual void TearDown() {
content::GetContentClient()->set_browser(old_browser_client_);
RenderViewHostTestHarness::TearDown();
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Target: 1
Example 2:
Code: void PaintLayerScrollableArea::SetScrollCornerAndResizerVisualRect(
const LayoutRect& rect) {
scroll_corner_and_resizer_visual_rect_ = rect;
if (LayoutScrollbarPart* scroll_corner = ScrollCorner())
scroll_corner->GetMutableForPainting().FirstFragment().SetVisualRect(rect);
if (LayoutScrollbarPart* resizer = Resizer())
resizer->GetMutableForPainting().FirstFragment().SetVisualRect(rect);
}
Commit Message: Always call UpdateCompositedScrollOffset, not just for the root layer
Bug: 927560
Change-Id: I1d5522aae4f11dd3f5b8947bb089bac1bf19bdb4
Reviewed-on: https://chromium-review.googlesource.com/c/1452701
Reviewed-by: Chris Harrelson <[email protected]>
Commit-Queue: Mason Freed <[email protected]>
Cr-Commit-Position: refs/heads/master@{#628942}
CWE ID: CWE-79
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: find_file (const char *currpath, grub_fshelp_node_t currroot,
grub_fshelp_node_t *currfound,
struct grub_fshelp_find_file_closure *c)
{
#ifndef _MSC_VER
char fpath[grub_strlen (currpath) + 1];
#else
char *fpath = grub_malloc (grub_strlen (currpath) + 1);
#endif
char *name = fpath;
char *next;
enum grub_fshelp_filetype type = GRUB_FSHELP_DIR;
grub_fshelp_node_t currnode = currroot;
grub_fshelp_node_t oldnode = currroot;
c->currroot = currroot;
grub_strncpy (fpath, currpath, grub_strlen (currpath) + 1);
/* Remove all leading slashes. */
while (*name == '/')
name++;
if (! *name)
{
*currfound = currnode;
return 0;
}
for (;;)
{
int found;
struct find_file_closure cc;
/* Extract the actual part from the pathname. */
next = grub_strchr (name, '/');
if (next)
{
/* Remove all leading slashes. */
while (*next == '/')
*(next++) = '\0';
}
/* At this point it is expected that the current node is a
directory, check if this is true. */
if (type != GRUB_FSHELP_DIR)
{
free_node (currnode, c);
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a directory");
}
cc.name = name;
cc.type = &type;
cc.oldnode = &oldnode;
cc.currnode = &currnode;
/* Iterate over the directory. */
found = c->iterate_dir (currnode, iterate, &cc);
if (! found)
{
if (grub_errno)
return grub_errno;
break;
}
/* Read in the symlink and follow it. */
if (type == GRUB_FSHELP_SYMLINK)
{
char *symlink;
/* Test if the symlink does not loop. */
if (++(c->symlinknest) == 8)
{
free_node (currnode, c);
free_node (oldnode, c);
return grub_error (GRUB_ERR_SYMLINK_LOOP,
"too deep nesting of symlinks");
}
symlink = c->read_symlink (currnode);
free_node (currnode, c);
if (!symlink)
{
free_node (oldnode, c);
return grub_errno;
}
/* The symlink is an absolute path, go back to the root inode. */
if (symlink[0] == '/')
{
free_node (oldnode, c);
oldnode = c->rootnode;
}
/* Lookup the node the symlink points to. */
find_file (symlink, oldnode, &currnode, c);
type = c->foundtype;
grub_free (symlink);
if (grub_errno)
{
free_node (oldnode, c);
return grub_errno;
}
}
free_node (oldnode, c);
/* Found the node! */
if (! next || *next == '\0')
{
*currfound = currnode;
c->foundtype = type;
return 0;
}
name = next;
}
return grub_error (GRUB_ERR_FILE_NOT_FOUND, "file not found");
}
Commit Message: Fix #7723 - crash in ext2 GRUB code because of variable size array in stack
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int irssi_ssl_handshake(GIOChannel *handle)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
int ret, err;
X509 *cert;
const char *errstr;
ret = SSL_connect(chan->ssl);
if (ret <= 0) {
err = SSL_get_error(chan->ssl, ret);
switch (err) {
case SSL_ERROR_WANT_READ:
return 1;
case SSL_ERROR_WANT_WRITE:
return 3;
case SSL_ERROR_ZERO_RETURN:
g_warning("SSL handshake failed: %s", "server closed connection");
return -1;
case SSL_ERROR_SYSCALL:
errstr = ERR_reason_error_string(ERR_get_error());
if (errstr == NULL && ret == -1)
errstr = strerror(errno);
g_warning("SSL handshake failed: %s", errstr != NULL ? errstr : "server closed connection unexpectedly");
return -1;
default:
errstr = ERR_reason_error_string(ERR_get_error());
g_warning("SSL handshake failed: %s", errstr != NULL ? errstr : "unknown SSL error");
return -1;
}
}
cert = SSL_get_peer_certificate(chan->ssl);
if (cert == NULL) {
g_warning("SSL server supplied no certificate");
return -1;
}
ret = !chan->verify || irssi_ssl_verify(chan->ssl, chan->ctx, cert);
X509_free(cert);
return ret ? 0 : -1;
}
Commit Message: Check if an SSL certificate matches the hostname of the server we are connecting to
git-svn-id: http://svn.irssi.org/repos/irssi/trunk@5104 dbcabf3a-b0e7-0310-adc4-f8d773084564
CWE ID: CWE-20
Target: 1
Example 2:
Code: ListAttributeTargetObserver::ListAttributeTargetObserver(const AtomicString& id, HTMLInputElement* element)
: IdTargetObserver(element->treeScope()->idTargetObserverRegistry(), id)
, m_element(element)
{
}
Commit Message: Setting input.x-webkit-speech should not cause focus change
In r150866, we introduced element()->focus() in destroyShadowSubtree()
to retain focus on <input> when its type attribute gets changed.
But when x-webkit-speech attribute is changed, the element is detached
before calling destroyShadowSubtree() and element()->focus() failed
This patch moves detach() after destroyShadowSubtree() to fix the
problem.
BUG=243818
TEST=fast/forms/input-type-change-focusout.html
NOTRY=true
Review URL: https://chromiumcodereview.appspot.com/16084005
git-svn-id: svn://svn.chromium.org/blink/trunk@151444 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
{
int start = 0;
u32 prev_legacy, cur_legacy;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
if (!prev_legacy && cur_legacy)
start = 1;
memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
sizeof(kvm->arch.vpit->pit_state.channels));
kvm->arch.vpit->pit_state.flags = ps->flags;
kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return 0;
}
Commit Message: KVM: x86: Reload pit counters for all channels when restoring state
Currently if userspace restores the pit counters with a count of 0
on channels 1 or 2 and the guest attempts to read the count on those
channels, then KVM will perform a mod of 0 and crash. This will ensure
that 0 values are converted to 65536 as per the spec.
This is CVE-2015-7513.
Signed-off-by: Andy Honig <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void WriteDDSInfo(Image *image, const size_t pixelFormat,
const size_t compression, const size_t mipmaps)
{
char
software[MaxTextExtent];
register ssize_t
i;
unsigned int
format,
caps,
flags;
flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT |
DDSD_PIXELFORMAT | DDSD_LINEARSIZE);
caps=(unsigned int) DDSCAPS_TEXTURE;
format=(unsigned int) pixelFormat;
if (mipmaps > 0)
{
flags=flags | (unsigned int) DDSD_MIPMAPCOUNT;
caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX);
}
if (format != DDPF_FOURCC && image->matte)
format=format | DDPF_ALPHAPIXELS;
(void) WriteBlob(image,4,(unsigned char *) "DDS ");
(void) WriteBlobLSBLong(image,124);
(void) WriteBlobLSBLong(image,flags);
(void) WriteBlobLSBLong(image,(unsigned int) image->rows);
(void) WriteBlobLSBLong(image,(unsigned int) image->columns);
if (compression == FOURCC_DXT1)
(void) WriteBlobLSBLong(image,
(unsigned int) (Max(1,(image->columns+3)/4) * 8));
else
(void) WriteBlobLSBLong(image,
(unsigned int) (Max(1,(image->columns+3)/4) * 16));
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1);
(void) ResetMagickMemory(software,0,sizeof(software));
(void) strcpy(software,"IMAGEMAGICK");
(void) WriteBlob(image,44,(unsigned char *) software);
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,format);
if (pixelFormat == DDPF_FOURCC)
{
(void) WriteBlobLSBLong(image,(unsigned int) compression);
for(i=0;i < 5;i++) // bitcount / masks
(void) WriteBlobLSBLong(image,0x00);
}
else
{
(void) WriteBlobLSBLong(image,0x00);
if (image->matte)
{
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,0xff0000);
(void) WriteBlobLSBLong(image,0xff00);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0xff000000);
}
else
{
(void) WriteBlobLSBLong(image,24);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,0x00);
}
}
(void) WriteBlobLSBLong(image,caps);
for(i=0;i < 4;i++) // ddscaps2 + reserved region
(void) WriteBlobLSBLong(image,0x00);
}
Commit Message: Added extra EOF check and some minor refactoring.
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int em_bsf_c(struct x86_emulate_ctxt *ctxt)
{
/* If src is zero, do not writeback, but update flags */
if (ctxt->src.val == 0)
ctxt->dst.type = OP_NONE;
return fastop(ctxt, em_bsf);
}
Commit Message: KVM: x86: drop error recovery in em_jmp_far and em_ret_far
em_jmp_far and em_ret_far assumed that setting IP can only fail in 64
bit mode, but syzkaller proved otherwise (and SDM agrees).
Code segment was restored upon failure, but it was left uninitialized
outside of long mode, which could lead to a leak of host kernel stack.
We could have fixed that by always saving and restoring the CS, but we
take a simpler approach and just break any guest that manages to fail
as the error recovery is error-prone and modern CPUs don't need emulator
for this.
Found by syzkaller:
WARNING: CPU: 2 PID: 3668 at arch/x86/kvm/emulate.c:2217 em_ret_far+0x428/0x480
Kernel panic - not syncing: panic_on_warn set ...
CPU: 2 PID: 3668 Comm: syz-executor Not tainted 4.9.0-rc4+ #49
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
[...]
Call Trace:
[...] __dump_stack lib/dump_stack.c:15
[...] dump_stack+0xb3/0x118 lib/dump_stack.c:51
[...] panic+0x1b7/0x3a3 kernel/panic.c:179
[...] __warn+0x1c4/0x1e0 kernel/panic.c:542
[...] warn_slowpath_null+0x2c/0x40 kernel/panic.c:585
[...] em_ret_far+0x428/0x480 arch/x86/kvm/emulate.c:2217
[...] em_ret_far_imm+0x17/0x70 arch/x86/kvm/emulate.c:2227
[...] x86_emulate_insn+0x87a/0x3730 arch/x86/kvm/emulate.c:5294
[...] x86_emulate_instruction+0x520/0x1ba0 arch/x86/kvm/x86.c:5545
[...] emulate_instruction arch/x86/include/asm/kvm_host.h:1116
[...] complete_emulated_io arch/x86/kvm/x86.c:6870
[...] complete_emulated_mmio+0x4e9/0x710 arch/x86/kvm/x86.c:6934
[...] kvm_arch_vcpu_ioctl_run+0x3b7a/0x5a90 arch/x86/kvm/x86.c:6978
[...] kvm_vcpu_ioctl+0x61e/0xdd0 arch/x86/kvm/../../../virt/kvm/kvm_main.c:2557
[...] vfs_ioctl fs/ioctl.c:43
[...] do_vfs_ioctl+0x18c/0x1040 fs/ioctl.c:679
[...] SYSC_ioctl fs/ioctl.c:694
[...] SyS_ioctl+0x8f/0xc0 fs/ioctl.c:685
[...] entry_SYSCALL_64_fastpath+0x1f/0xc2
Reported-by: Dmitry Vyukov <[email protected]>
Cc: [email protected]
Fixes: d1442d85cc30 ("KVM: x86: Handle errors when RIP is set during far jumps")
Signed-off-by: Radim Krčmář <[email protected]>
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: BaseSessionService::~BaseSessionService() {
}
Commit Message: Metrics for measuring how much overhead reading compressed content states adds.
BUG=104293
TEST=NONE
Review URL: https://chromiumcodereview.appspot.com/9426039
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@123733 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void WritePixels(struct ngiflib_img * i, struct ngiflib_decode_context * context, const u8 * pixels, u16 n) {
u16 tocopy;
struct ngiflib_gif * p = i->parent;
while(n > 0) {
tocopy = (context->Xtogo < n) ? context->Xtogo : n;
if(!i->gce.transparent_flag) {
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
ngiflib_memcpy(context->frbuff_p.p8, pixels, tocopy);
pixels += tocopy;
context->frbuff_p.p8 += tocopy;
#ifndef NGIFLIB_INDEXED_ONLY
} else {
int j;
for(j = (int)tocopy; j > 0; j--) {
*(context->frbuff_p.p32++) =
GifIndexToTrueColor(i->palette, *pixels++);
}
}
#endif /* NGIFLIB_INDEXED_ONLY */
} else {
int j;
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
for(j = (int)tocopy; j > 0; j--) {
if(*pixels != i->gce.transparent_color) *context->frbuff_p.p8 = *pixels;
pixels++;
context->frbuff_p.p8++;
}
#ifndef NGIFLIB_INDEXED_ONLY
} else {
for(j = (int)tocopy; j > 0; j--) {
if(*pixels != i->gce.transparent_color) {
*context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, *pixels);
}
pixels++;
context->frbuff_p.p32++;
}
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
context->Xtogo -= tocopy;
if(context->Xtogo == 0) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(p->line_cb) p->line_cb(p, context->line_p, context->curY);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
context->Xtogo = i->width;
switch(context->pass) {
case 0:
context->curY++;
break;
case 1: /* 1st pass : every eighth row starting from 0 */
context->curY += 8;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 4;
}
break;
case 2: /* 2nd pass : every eighth row starting from 4 */
context->curY += 8;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 2;
}
break;
case 3: /* 3rd pass : every fourth row starting from 2 */
context->curY += 4;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 1;
}
break;
case 4: /* 4th pass : every odd row */
context->curY += 2;
break;
}
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width;
context->frbuff_p.p8 = context->line_p.p8 + i->posX;
#else
context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#ifndef NGIFLIB_INDEXED_ONLY
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width;
context->frbuff_p.p32 = context->line_p.p32 + i->posX;
#else
context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
n -= tocopy;
}
}
Commit Message: fix deinterlacing for small pictures
fixes #12
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int follow_automount(struct path *path, unsigned flags,
bool *need_mntput)
{
struct vfsmount *mnt;
int err;
if (!path->dentry->d_op || !path->dentry->d_op->d_automount)
return -EREMOTE;
/* We don't want to mount if someone's just doing a stat -
* unless they're stat'ing a directory and appended a '/' to
* the name.
*
* We do, however, want to mount if someone wants to open or
* create a file of any type under the mountpoint, wants to
* traverse through the mountpoint or wants to open the
* mounted directory. Also, autofs may mark negative dentries
* as being automount points. These will need the attentions
* of the daemon to instantiate them before they can be used.
*/
if (!(flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
path->dentry->d_inode)
return -EISDIR;
current->total_link_count++;
if (current->total_link_count >= 40)
return -ELOOP;
mnt = path->dentry->d_op->d_automount(path);
if (IS_ERR(mnt)) {
/*
* The filesystem is allowed to return -EISDIR here to indicate
* it doesn't want to automount. For instance, autofs would do
* this so that its userspace daemon can mount on this dentry.
*
* However, we can only permit this if it's a terminal point in
* the path being looked up; if it wasn't then the remainder of
* the path is inaccessible and we should say so.
*/
if (PTR_ERR(mnt) == -EISDIR && (flags & LOOKUP_PARENT))
return -EREMOTE;
return PTR_ERR(mnt);
}
if (!mnt) /* mount collision */
return 0;
if (!*need_mntput) {
/* lock_mount() may release path->mnt on error */
mntget(path->mnt);
*need_mntput = true;
}
err = finish_automount(mnt, path);
switch (err) {
case -EBUSY:
/* Someone else made a mount here whilst we were busy */
return 0;
case 0:
path_put(path);
path->mnt = mnt;
path->dentry = dget(mnt->mnt_root);
return 0;
default:
return err;
}
}
Commit Message: fs: umount on symlink leaks mnt count
Currently umount on symlink blocks following umount:
/vz is separate mount
# ls /vz/ -al | grep test
drwxr-xr-x. 2 root root 4096 Jul 19 01:14 testdir
lrwxrwxrwx. 1 root root 11 Jul 19 01:16 testlink -> /vz/testdir
# umount -l /vz/testlink
umount: /vz/testlink: not mounted (expected)
# lsof /vz
# umount /vz
umount: /vz: device is busy. (unexpected)
In this case mountpoint_last() gets an extra refcount on path->mnt
Signed-off-by: Vasily Averin <[email protected]>
Acked-by: Ian Kent <[email protected]>
Acked-by: Jeff Layton <[email protected]>
Cc: [email protected]
Signed-off-by: Christoph Hellwig <[email protected]>
CWE ID: CWE-59
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void show_object(struct object *obj,
struct strbuf *path, const char *component,
void *cb_data)
{
struct rev_list_info *info = cb_data;
finish_object(obj, path, component, cb_data);
if (info->flags & REV_LIST_QUIET)
return;
show_object_with_name(stdout, obj, path, component);
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long ContentEncoding::ParseContentEncodingEntry(long long start, long long size,
IMkvReader* pReader) {
assert(pReader);
long long pos = start;
const long long stop = start + size;
int compression_count = 0;
int encryption_count = 0;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x1034) // ContentCompression ID
++compression_count;
if (id == 0x1035) // ContentEncryption ID
++encryption_count;
pos += size; // consume payload
assert(pos <= stop);
}
if (compression_count <= 0 && encryption_count <= 0)
return -1;
if (compression_count > 0) {
compression_entries_ =
new (std::nothrow) ContentCompression* [compression_count];
if (!compression_entries_)
return -1;
compression_entries_end_ = compression_entries_;
}
if (encryption_count > 0) {
encryption_entries_ =
new (std::nothrow) ContentEncryption* [encryption_count];
if (!encryption_entries_) {
delete[] compression_entries_;
return -1;
}
encryption_entries_end_ = encryption_entries_;
}
pos = start;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x1031) {
encoding_order_ = UnserializeUInt(pReader, pos, size);
} else if (id == 0x1032) {
encoding_scope_ = UnserializeUInt(pReader, pos, size);
if (encoding_scope_ < 1)
return -1;
} else if (id == 0x1033) {
encoding_type_ = UnserializeUInt(pReader, pos, size);
} else if (id == 0x1034) {
ContentCompression* const compression =
new (std::nothrow) ContentCompression();
if (!compression)
return -1;
status = ParseCompressionEntry(pos, size, pReader, compression);
if (status) {
delete compression;
return status;
}
*compression_entries_end_++ = compression;
} else if (id == 0x1035) {
ContentEncryption* const encryption =
new (std::nothrow) ContentEncryption();
if (!encryption)
return -1;
status = ParseEncryptionEntry(pos, size, pReader, encryption);
if (status) {
delete encryption;
return status;
}
*encryption_entries_end_++ = encryption;
}
pos += size; // consume payload
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
Target: 1
Example 2:
Code: void PrintPreviewDialogController::RemovePreviewDialog(
WebContents* preview_dialog) {
WebContents* initiator = GetInitiator(preview_dialog);
if (initiator) {
RemoveObservers(initiator);
PrintViewManager::FromWebContents(initiator)->PrintPreviewDone();
}
preview_dialog_map_.erase(preview_dialog);
RemoveObservers(preview_dialog);
}
Commit Message: Use pdf compositor service for printing when OOPIF is enabled
When OOPIF is enabled (by site-per-process flag or
top-document-isolation feature), use the pdf compositor service for
converting PaintRecord to PDF on renderers.
In the future, this will make compositing PDF from multiple renderers
possible.
[email protected]
BUG=455764
Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f
Reviewed-on: https://chromium-review.googlesource.com/699765
Commit-Queue: Wei Li <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#511616}
CWE ID: CWE-254
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static unsigned int get_fault_insn(struct pt_regs *regs, unsigned int insn)
{
if (!insn) {
if (!regs->tpc || (regs->tpc & 0x3))
return 0;
if (regs->tstate & TSTATE_PRIV) {
insn = *(unsigned int *) regs->tpc;
} else {
insn = get_user_insn(regs->tpc);
}
}
return insn;
}
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
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool SiteInstanceImpl::DoesSiteRequireDedicatedProcess(
BrowserContext* browser_context,
const GURL& url) {
if (SiteIsolationPolicy::UseDedicatedProcessesForAllSites())
return true;
if (url.SchemeIs(kChromeErrorScheme))
return true;
GURL site_url = SiteInstance::GetSiteForURL(browser_context, url);
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
if (policy->IsIsolatedOrigin(url::Origin::Create(site_url)))
return true;
if (GetContentClient()->browser()->DoesSiteRequireDedicatedProcess(
browser_context, site_url)) {
return true;
}
return false;
}
Commit Message: Allow origin lock for WebUI pages.
Returning true for WebUI pages in DoesSiteRequireDedicatedProcess helps
to keep enforcing a SiteInstance swap during chrome://foo ->
chrome://bar navigation, even after relaxing
BrowsingInstance::GetSiteInstanceForURL to consider RPH::IsSuitableHost
(see https://crrev.com/c/783470 for that fixes process sharing in
isolated(b(c),d(c)) scenario).
I've manually tested this CL by visiting the following URLs:
- chrome://welcome/
- chrome://settings
- chrome://extensions
- chrome://history
- chrome://help and chrome://chrome (both redirect to chrome://settings/help)
Bug: 510588, 847127
Change-Id: I55073bce00f32cb8bc5c1c91034438ff9a3f8971
Reviewed-on: https://chromium-review.googlesource.com/1237392
Commit-Queue: Łukasz Anforowicz <[email protected]>
Reviewed-by: François Doray <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#595259}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool GLES2DecoderImpl::GenRenderbuffersHelper(
GLsizei n, const GLuint* client_ids) {
for (GLsizei ii = 0; ii < n; ++ii) {
if (GetRenderbuffer(client_ids[ii])) {
return false;
}
}
scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
glGenRenderbuffersEXT(n, service_ids.get());
for (GLsizei ii = 0; ii < n; ++ii) {
CreateRenderbuffer(client_ids[ii], service_ids[ii]);
}
return true;
}
Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled.
This is when we expose DrawBuffers extension.
BUG=376951
TEST=the attached test case, webgl conformance
[email protected],[email protected]
Review URL: https://codereview.chromium.org/315283002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching session ticket extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->handshake->new_session_ticket = 1;
return( 0 );
}
Commit Message: Add bounds check before length read
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int decode_bit_string(const u8 * inbuf, size_t inlen, void *outbuf,
size_t outlen, int invert)
{
const u8 *in = inbuf;
u8 *out = (u8 *) outbuf;
int zero_bits = *in & 0x07;
size_t octets_left = inlen - 1;
int i, count = 0;
memset(outbuf, 0, outlen);
in++;
if (outlen < octets_left)
return SC_ERROR_BUFFER_TOO_SMALL;
if (inlen < 1)
return SC_ERROR_INVALID_ASN1_OBJECT;
while (octets_left) {
/* 1st octet of input: ABCDEFGH, where A is the MSB */
/* 1st octet of output: HGFEDCBA, where A is the LSB */
/* first bit in bit string is the LSB in first resulting octet */
int bits_to_go;
*out = 0;
if (octets_left == 1)
bits_to_go = 8 - zero_bits;
else
bits_to_go = 8;
if (invert)
for (i = 0; i < bits_to_go; i++) {
*out |= ((*in >> (7 - i)) & 1) << i;
}
else {
*out = *in;
}
out++;
in++;
octets_left--;
count++;
}
return (count * 8) - zero_bits;
}
Commit Message: fixed out of bounds access of ASN.1 Bitstring
Credit to OSS-Fuzz
CWE ID: CWE-119
Target: 1
Example 2:
Code: static struct dentry *udf_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
return mount_bdev(fs_type, flags, dev_name, data, udf_fill_super);
}
Commit Message: udf: Avoid run away loop when partition table length is corrupted
Check provided length of partition table so that (possibly maliciously)
corrupted partition table cannot cause accessing data beyond current buffer.
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Page* WebPagePrivate::core(const WebPage* webPage)
{
return webPage->d->m_page;
}
Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API
https://bugs.webkit.org/show_bug.cgi?id=105143
RIM PR 171941
Reviewed by Rob Buis.
Internally reviewed by George Staikos.
Source/WebCore:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit.
Also adapt to new method names and encapsulation of TouchPoint data
members.
No change in behavior, no new tests.
* platform/blackberry/PlatformTouchPointBlackBerry.cpp:
(WebCore::PlatformTouchPoint::PlatformTouchPoint):
Source/WebKit/blackberry:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit. One exception
is when passing events to a full screen plugin.
Also adapt to new method names and encapsulation of TouchPoint data
members.
* Api/WebPage.cpp:
(BlackBerry::WebKit::WebPage::touchEvent):
(BlackBerry::WebKit::WebPage::touchPointAsMouseEvent):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin):
* WebKitSupport/InputHandler.cpp:
(BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint):
* WebKitSupport/InputHandler.h:
(InputHandler):
* WebKitSupport/TouchEventHandler.cpp:
(BlackBerry::WebKit::TouchEventHandler::doFatFingers):
(BlackBerry::WebKit::TouchEventHandler::handleTouchPoint):
* WebKitSupport/TouchEventHandler.h:
(TouchEventHandler):
Tools:
Adapt to new method names and encapsulation of TouchPoint data members.
* DumpRenderTree/blackberry/EventSender.cpp:
(addTouchPointCallback):
(updateTouchPointCallback):
(touchEndCallback):
(releaseTouchPointCallback):
(sendTouchEvent):
git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int verify_vc_kbmode(int fd) {
int curr_mode;
/*
* Make sure we only adjust consoles in K_XLATE or K_UNICODE mode.
* Otherwise we would (likely) interfere with X11's processing of the
* key events.
*
* http://lists.freedesktop.org/archives/systemd-devel/2013-February/008573.html
*/
if (ioctl(fd, KDGKBMODE, &curr_mode) < 0)
return -errno;
return IN_SET(curr_mode, K_XLATE, K_UNICODE) ? 0 : -EBUSY;
}
Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check
VT kbd reset check
CWE ID: CWE-255
Target: 1
Example 2:
Code: OMX_ERRORTYPE omx_vdec::get_buffer_req(vdec_allocatorproperty *buffer_prop)
{
OMX_ERRORTYPE eRet = OMX_ErrorNone;
struct v4l2_requestbuffers bufreq;
unsigned int buf_size = 0, extra_data_size = 0, default_extra_data_size = 0;
unsigned int final_extra_data_size = 0;
struct v4l2_format fmt;
int ret = 0;
DEBUG_PRINT_LOW("GetBufReq IN: ActCnt(%d) Size(%u)",
buffer_prop->actualcount, (unsigned int)buffer_prop->buffer_size);
bufreq.memory = V4L2_MEMORY_USERPTR;
bufreq.count = 1;
if (buffer_prop->buffer_type == VDEC_BUFFER_TYPE_INPUT) {
bufreq.type=V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
fmt.type =V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
fmt.fmt.pix_mp.pixelformat = output_capability;
} else if (buffer_prop->buffer_type == VDEC_BUFFER_TYPE_OUTPUT) {
bufreq.type=V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
fmt.type =V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
fmt.fmt.pix_mp.pixelformat = capture_capability;
} else {
eRet = OMX_ErrorBadParameter;
}
if (eRet==OMX_ErrorNone) {
ret = ioctl(drv_ctx.video_driver_fd,VIDIOC_REQBUFS, &bufreq);
}
if (ret) {
DEBUG_PRINT_ERROR("Requesting buffer requirements failed");
/*TODO: How to handle this case */
eRet = OMX_ErrorInsufficientResources;
return eRet;
} else {
buffer_prop->actualcount = bufreq.count;
buffer_prop->mincount = bufreq.count;
DEBUG_PRINT_HIGH("Count = %d",bufreq.count);
}
DEBUG_PRINT_LOW("GetBufReq IN: ActCnt(%d) Size(%u)",
buffer_prop->actualcount, (unsigned int)buffer_prop->buffer_size);
fmt.fmt.pix_mp.height = drv_ctx.video_resolution.frame_height;
fmt.fmt.pix_mp.width = drv_ctx.video_resolution.frame_width;
ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_G_FMT, &fmt);
update_resolution(fmt.fmt.pix_mp.width,
fmt.fmt.pix_mp.height,
fmt.fmt.pix_mp.plane_fmt[0].bytesperline,
fmt.fmt.pix_mp.plane_fmt[0].reserved[0]);
if (fmt.type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
drv_ctx.num_planes = fmt.fmt.pix_mp.num_planes;
DEBUG_PRINT_HIGH("Buffer Size = %d",fmt.fmt.pix_mp.plane_fmt[0].sizeimage);
if (ret) {
/*TODO: How to handle this case */
DEBUG_PRINT_ERROR("Requesting buffer requirements failed");
eRet = OMX_ErrorInsufficientResources;
} else {
int extra_idx = 0;
eRet = is_video_session_supported();
if (eRet)
return eRet;
buffer_prop->buffer_size = fmt.fmt.pix_mp.plane_fmt[0].sizeimage;
buf_size = buffer_prop->buffer_size;
extra_idx = EXTRADATA_IDX(drv_ctx.num_planes);
if (extra_idx && (extra_idx < VIDEO_MAX_PLANES)) {
extra_data_size = fmt.fmt.pix_mp.plane_fmt[extra_idx].sizeimage;
} else if (extra_idx >= VIDEO_MAX_PLANES) {
DEBUG_PRINT_ERROR("Extradata index is more than allowed: %d", extra_idx);
return OMX_ErrorBadParameter;
}
default_extra_data_size = VENUS_EXTRADATA_SIZE(
drv_ctx.video_resolution.frame_height,
drv_ctx.video_resolution.frame_width);
final_extra_data_size = extra_data_size > default_extra_data_size ?
extra_data_size : default_extra_data_size;
final_extra_data_size = (final_extra_data_size + buffer_prop->alignment - 1) &
(~(buffer_prop->alignment - 1));
drv_ctx.extradata_info.size = buffer_prop->actualcount * final_extra_data_size;
drv_ctx.extradata_info.count = buffer_prop->actualcount;
drv_ctx.extradata_info.buffer_size = final_extra_data_size;
if (!secure_mode)
buf_size += final_extra_data_size;
buf_size = (buf_size + buffer_prop->alignment - 1)&(~(buffer_prop->alignment - 1));
DEBUG_PRINT_LOW("GetBufReq UPDATE: ActCnt(%d) Size(%u) BufSize(%d)",
buffer_prop->actualcount, (unsigned int)buffer_prop->buffer_size, buf_size);
if (extra_data_size)
DEBUG_PRINT_LOW("GetBufReq UPDATE: extradata: TotalSize(%d) BufferSize(%lu)",
drv_ctx.extradata_info.size, drv_ctx.extradata_info.buffer_size);
if (in_reconfig) // BufReq will be set to driver when port is disabled
buffer_prop->buffer_size = buf_size;
else if (buf_size != buffer_prop->buffer_size) {
buffer_prop->buffer_size = buf_size;
eRet = set_buffer_req(buffer_prop);
}
}
DEBUG_PRINT_LOW("GetBufReq OUT: ActCnt(%d) Size(%u)",
buffer_prop->actualcount, (unsigned int)buffer_prop->buffer_size);
return eRet;
}
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27890802
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVdec problem #6)
CRs-Fixed: 1008882
Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool is_same_document() {
EXPECT_EQ(1U, is_same_documents_.size());
return is_same_documents_[0];
}
Commit Message: Abort navigations on 304 responses.
A recent change (https://chromium-review.googlesource.com/1161479)
accidentally resulted in treating 304 responses as downloads. This CL
treats them as ERR_ABORTED instead. This doesn't exactly match old
behavior, which passed them on to the renderer, which then aborted them.
The new code results in correctly restoring the original URL in the
omnibox, and has a shiny new test to prevent future regressions.
Bug: 882270
Change-Id: Ic73dcce9e9596d43327b13acde03b4ed9bd0c82e
Reviewed-on: https://chromium-review.googlesource.com/1252684
Commit-Queue: Matt Menke <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#595641}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RenderBlockFlow::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
RenderBlock::styleDidChange(diff, oldStyle);
bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats();
if (diff == StyleDifferenceLayout && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) {
RenderBlockFlow* parentBlockFlow = this;
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = floatingObjectSet.end();
for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
if (curr->isRenderBlockFlow()) {
RenderBlockFlow* currBlock = toRenderBlockFlow(curr);
if (currBlock->hasOverhangingFloats()) {
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
RenderBox* renderer = (*it)->renderer();
if (currBlock->hasOverhangingFloat(renderer)) {
parentBlockFlow = currBlock;
break;
}
}
}
}
}
parentBlockFlow->markAllDescendantsWithFloatsForLayout();
parentBlockFlow->markSiblingsWithFloatsForLayout();
}
if (diff == StyleDifferenceLayout || !oldStyle)
createOrDestroyMultiColumnFlowThreadIfNeeded();
}
Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1)
Previously StyleDifference was an enum that proximately bigger values
imply smaller values (e.g. StyleDifferenceLayout implies
StyleDifferenceRepaint). This causes unnecessary repaints in some cases
on layout change.
Convert StyleDifference to a structure containing relatively independent
flags.
This change doesn't directly improve the result, but can make further
repaint optimizations possible.
Step 1 doesn't change any functionality. RenderStyle still generate the
legacy StyleDifference enum when comparing styles and convert the result
to the new StyleDifference. Implicit requirements are not handled during
the conversion.
Converted call sites to use the new StyleDifference according to the
following conversion rules:
- diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange()
- diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly()
- diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer()
- diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer()
- diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout()
- diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout()
- diff > StyleDifferenceRepaintLayer => diff.needsLayout()
- diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly()
- diff == StyleDifferenceLayout => diff.needsFullLayout()
BUG=358460
TEST=All existing layout tests.
[email protected], [email protected], [email protected]
Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983
Review URL: https://codereview.chromium.org/236203020
git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Target: 1
Example 2:
Code: void AppCache::InitializeWithManifest(AppCacheManifest* manifest) {
DCHECK(manifest);
intercept_namespaces_.swap(manifest->intercept_namespaces);
fallback_namespaces_.swap(manifest->fallback_namespaces);
online_whitelist_namespaces_.swap(manifest->online_whitelist_namespaces);
online_whitelist_all_ = manifest->online_whitelist_all;
std::sort(intercept_namespaces_.begin(), intercept_namespaces_.end(),
SortNamespacesByLength);
std::sort(fallback_namespaces_.begin(), fallback_namespaces_.end(),
SortNamespacesByLength);
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int SSL_in_init(SSL *s)
{
return s->statem.in_init;
}
Commit Message:
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: nfs4_proc_create(struct inode *dir, struct dentry *dentry, struct iattr *sattr,
int flags, struct nameidata *nd)
{
struct path path = {
.mnt = nd->path.mnt,
.dentry = dentry,
};
struct nfs4_state *state;
struct rpc_cred *cred;
int status = 0;
cred = rpc_lookup_cred();
if (IS_ERR(cred)) {
status = PTR_ERR(cred);
goto out;
}
state = nfs4_do_open(dir, &path, flags, sattr, cred);
d_drop(dentry);
if (IS_ERR(state)) {
status = PTR_ERR(state);
goto out_putcred;
}
d_add(dentry, igrab(state->inode));
nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
if (flags & O_EXCL) {
struct nfs_fattr fattr;
status = nfs4_do_setattr(state->inode, cred, &fattr, sattr, state);
if (status == 0)
nfs_setattr_update_inode(state->inode, sattr);
nfs_post_op_update_inode(state->inode, &fattr);
}
if (status == 0 && (nd->flags & LOOKUP_OPEN) != 0)
status = nfs4_intent_set_file(nd, &path, state);
else
nfs4_close_sync(&path, state, flags);
out_putcred:
put_rpccred(cred);
out:
return status;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: static void anyCallbackFunctionOptionalAnyArgAttributeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
TestObjectPythonV8Internal::anyCallbackFunctionOptionalAnyArgAttributeAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
Commit Message: document.location bindings fix
BUG=352374
[email protected]
Review URL: https://codereview.chromium.org/196343011
git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void php_zip_get_from(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */
{
struct zip *intern;
zval *self = getThis();
struct zip_stat sb;
struct zip_file *zf;
zend_long index = -1;
zend_long flags = 0;
zend_long len = 0;
zend_string *filename;
zend_string *buffer;
int n = 0;
if (!self) {
RETURN_FALSE;
}
ZIP_FROM_OBJECT(intern, self);
if (type == 1) {
if (zend_parse_parameters(ZEND_NUM_ARGS(), "P|ll", &filename, &len, &flags) == FAILURE) {
return;
}
PHP_ZIP_STAT_PATH(intern, ZSTR_VAL(filename), ZSTR_LEN(filename), flags, sb);
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|ll", &index, &len, &flags) == FAILURE) {
return;
}
PHP_ZIP_STAT_INDEX(intern, index, 0, sb);
}
if (sb.size < 1) {
RETURN_EMPTY_STRING();
}
if (len < 1) {
len = sb.size;
}
if (index >= 0) {
zf = zip_fopen_index(intern, index, flags);
} else {
zf = zip_fopen(intern, ZSTR_VAL(filename), flags);
}
if (zf == NULL) {
RETURN_FALSE;
}
buffer = zend_string_alloc(len, 0);
n = zip_fread(zf, ZSTR_VAL(buffer), ZSTR_LEN(buffer));
if (n < 1) {
zend_string_free(buffer);
RETURN_EMPTY_STRING();
}
zip_fclose(zf);
ZSTR_VAL(buffer)[n] = '\0';
ZSTR_LEN(buffer) = n;
RETURN_NEW_STR(buffer);
}
/* }}} */
Commit Message: Fix bug #71923 - integer overflow in ZipArchive::getFrom*
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ParseCaffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
uint32_t chan_chunk = 0, channel_layout = 0, bcount;
unsigned char *channel_identities = NULL;
unsigned char *channel_reorder = NULL;
int64_t total_samples = 0, infilesize;
CAFFileHeader caf_file_header;
CAFChunkHeader caf_chunk_header;
CAFAudioFormat caf_audio_format;
int i;
infilesize = DoGetFileSize (infile);
memcpy (&caf_file_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &caf_file_header) + 4, sizeof (CAFFileHeader) - 4, &bcount) ||
bcount != sizeof (CAFFileHeader) - 4)) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &caf_file_header, sizeof (CAFFileHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&caf_file_header, CAFFileHeaderFormat);
if (caf_file_header.mFileVersion != 1) {
error_line ("%s: can't handle version %d .CAF files!", infilename, caf_file_header.mFileVersion);
return WAVPACK_SOFT_ERROR;
}
while (1) {
if (!DoReadFile (infile, &caf_chunk_header, sizeof (CAFChunkHeader), &bcount) ||
bcount != sizeof (CAFChunkHeader)) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &caf_chunk_header, sizeof (CAFChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&caf_chunk_header, CAFChunkHeaderFormat);
if (!strncmp (caf_chunk_header.mChunkType, "desc", 4)) {
int supported = TRUE;
if (caf_chunk_header.mChunkSize != sizeof (CAFAudioFormat) ||
!DoReadFile (infile, &caf_audio_format, (uint32_t) caf_chunk_header.mChunkSize, &bcount) ||
bcount != caf_chunk_header.mChunkSize) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &caf_audio_format, (uint32_t) caf_chunk_header.mChunkSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&caf_audio_format, CAFAudioFormatFormat);
if (debug_logging_mode) {
char formatstr [5];
memcpy (formatstr, caf_audio_format.mFormatID, 4);
formatstr [4] = 0;
error_line ("format = %s, flags = %x, sampling rate = %g",
formatstr, caf_audio_format.mFormatFlags, caf_audio_format.mSampleRate);
error_line ("packet = %d bytes and %d frames",
caf_audio_format.mBytesPerPacket, caf_audio_format.mFramesPerPacket);
error_line ("channels per frame = %d, bits per channel = %d",
caf_audio_format.mChannelsPerFrame, caf_audio_format.mBitsPerChannel);
}
if (strncmp (caf_audio_format.mFormatID, "lpcm", 4) || (caf_audio_format.mFormatFlags & ~3))
supported = FALSE;
else if (caf_audio_format.mSampleRate < 1.0 || caf_audio_format.mSampleRate > 16777215.0 ||
caf_audio_format.mSampleRate != floor (caf_audio_format.mSampleRate))
supported = FALSE;
else if (!caf_audio_format.mChannelsPerFrame || caf_audio_format.mChannelsPerFrame > 256)
supported = FALSE;
else if (caf_audio_format.mBitsPerChannel < 1 || caf_audio_format.mBitsPerChannel > 32 ||
((caf_audio_format.mFormatFlags & CAF_FORMAT_FLOAT) && caf_audio_format.mBitsPerChannel != 32))
supported = FALSE;
else if (caf_audio_format.mFramesPerPacket != 1 ||
caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame < (caf_audio_format.mBitsPerChannel + 7) / 8 ||
caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame > 4 ||
caf_audio_format.mBytesPerPacket % caf_audio_format.mChannelsPerFrame)
supported = FALSE;
if (!supported) {
error_line ("%s is an unsupported .CAF format!", infilename);
return WAVPACK_SOFT_ERROR;
}
config->bytes_per_sample = caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame;
config->float_norm_exp = (caf_audio_format.mFormatFlags & CAF_FORMAT_FLOAT) ? 127 : 0;
config->bits_per_sample = caf_audio_format.mBitsPerChannel;
config->num_channels = caf_audio_format.mChannelsPerFrame;
config->sample_rate = (int) caf_audio_format.mSampleRate;
if (!(caf_audio_format.mFormatFlags & CAF_FORMAT_LITTLE_ENDIAN) && config->bytes_per_sample > 1)
config->qmode |= QMODE_BIG_ENDIAN;
if (config->bytes_per_sample == 1)
config->qmode |= QMODE_SIGNED_BYTES;
if (debug_logging_mode) {
if (config->float_norm_exp == 127)
error_line ("data format: 32-bit %s-endian floating point", (config->qmode & QMODE_BIG_ENDIAN) ? "big" : "little");
else
error_line ("data format: %d-bit %s-endian integers stored in %d byte(s)",
config->bits_per_sample, (config->qmode & QMODE_BIG_ENDIAN) ? "big" : "little", config->bytes_per_sample);
}
}
else if (!strncmp (caf_chunk_header.mChunkType, "chan", 4)) {
CAFChannelLayout *caf_channel_layout;
if (caf_chunk_header.mChunkSize < 0 || caf_chunk_header.mChunkSize > 1024 ||
caf_chunk_header.mChunkSize < sizeof (CAFChannelLayout)) {
error_line ("this .CAF file has an invalid 'chan' chunk!");
return WAVPACK_SOFT_ERROR;
}
if (debug_logging_mode)
error_line ("'chan' chunk is %d bytes", (int) caf_chunk_header.mChunkSize);
caf_channel_layout = malloc ((size_t) caf_chunk_header.mChunkSize);
if (!DoReadFile (infile, caf_channel_layout, (uint32_t) caf_chunk_header.mChunkSize, &bcount) ||
bcount != caf_chunk_header.mChunkSize) {
error_line ("%s is not a valid .CAF file!", infilename);
free (caf_channel_layout);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, caf_channel_layout, (uint32_t) caf_chunk_header.mChunkSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (caf_channel_layout);
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (caf_channel_layout, CAFChannelLayoutFormat);
chan_chunk = 1;
if (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED)) {
error_line ("this CAF file already has channel order information!");
free (caf_channel_layout);
return WAVPACK_SOFT_ERROR;
}
switch (caf_channel_layout->mChannelLayoutTag) {
case kCAFChannelLayoutTag_UseChannelDescriptions:
{
CAFChannelDescription *descriptions = (CAFChannelDescription *) (caf_channel_layout + 1);
int num_descriptions = caf_channel_layout->mNumberChannelDescriptions;
int label, cindex = 0, idents = 0;
if (caf_chunk_header.mChunkSize != sizeof (CAFChannelLayout) + sizeof (CAFChannelDescription) * num_descriptions ||
num_descriptions != config->num_channels) {
error_line ("channel descriptions in 'chan' chunk are the wrong size!");
free (caf_channel_layout);
return WAVPACK_SOFT_ERROR;
}
if (num_descriptions >= 256) {
error_line ("%d channel descriptions is more than we can handle...ignoring!");
break;
}
channel_reorder = malloc (num_descriptions);
memset (channel_reorder, -1, num_descriptions);
channel_identities = malloc (num_descriptions+1);
for (i = 0; i < num_descriptions; ++i) {
WavpackBigEndianToNative (descriptions + i, CAFChannelDescriptionFormat);
if (debug_logging_mode)
error_line ("chan %d --> %d", i + 1, descriptions [i].mChannelLabel);
}
for (label = 1; label <= 18; ++label)
for (i = 0; i < num_descriptions; ++i)
if (descriptions [i].mChannelLabel == label) {
config->channel_mask |= 1 << (label - 1);
channel_reorder [i] = cindex++;
break;
}
for (i = 0; i < num_descriptions; ++i)
if (channel_reorder [i] == (unsigned char) -1) {
uint32_t clabel = descriptions [i].mChannelLabel;
if (clabel == 0 || clabel == 0xffffffff || clabel == 100)
channel_identities [idents++] = 0xff;
else if ((clabel >= 33 && clabel <= 44) || (clabel >= 200 && clabel <= 207) || (clabel >= 301 && clabel <= 305))
channel_identities [idents++] = clabel >= 301 ? clabel - 80 : clabel;
else {
error_line ("warning: unknown channel descriptions label: %d", clabel);
channel_identities [idents++] = 0xff;
}
channel_reorder [i] = cindex++;
}
for (i = 0; i < num_descriptions; ++i)
if (channel_reorder [i] != i)
break;
if (i == num_descriptions) {
free (channel_reorder); // no reordering required, so don't
channel_reorder = NULL;
}
else {
config->qmode |= QMODE_REORDERED_CHANS; // reordering required, put channel count into layout
channel_layout = num_descriptions;
}
if (!idents) { // if no non-MS channels, free the identities string
free (channel_identities);
channel_identities = NULL;
}
else
channel_identities [idents] = 0; // otherwise NULL terminate it
if (debug_logging_mode) {
error_line ("layout_tag = 0x%08x, so generated bitmap of 0x%08x from %d descriptions, %d non-MS",
caf_channel_layout->mChannelLayoutTag, config->channel_mask,
caf_channel_layout->mNumberChannelDescriptions, idents);
if (channel_reorder && num_descriptions <= 8) {
char reorder_string [] = "12345678";
for (i = 0; i < num_descriptions; ++i)
reorder_string [i] = channel_reorder [i] + '1';
reorder_string [i] = 0;
error_line ("reordering string = \"%s\"\n", reorder_string);
}
}
}
break;
case kCAFChannelLayoutTag_UseChannelBitmap:
config->channel_mask = caf_channel_layout->mChannelBitmap;
if (debug_logging_mode)
error_line ("layout_tag = 0x%08x, so using supplied bitmap of 0x%08x",
caf_channel_layout->mChannelLayoutTag, caf_channel_layout->mChannelBitmap);
break;
default:
for (i = 0; i < NUM_LAYOUTS; ++i)
if (caf_channel_layout->mChannelLayoutTag == layouts [i].mChannelLayoutTag) {
config->channel_mask = layouts [i].mChannelBitmap;
channel_layout = layouts [i].mChannelLayoutTag;
if (layouts [i].mChannelReorder) {
channel_reorder = (unsigned char *) strdup (layouts [i].mChannelReorder);
config->qmode |= QMODE_REORDERED_CHANS;
}
if (layouts [i].mChannelIdentities)
channel_identities = (unsigned char *) strdup (layouts [i].mChannelIdentities);
if (debug_logging_mode)
error_line ("layout_tag 0x%08x found in table, bitmap = 0x%08x, reorder = %s, identities = %s",
channel_layout, config->channel_mask, channel_reorder ? "yes" : "no", channel_identities ? "yes" : "no");
break;
}
if (i == NUM_LAYOUTS && debug_logging_mode)
error_line ("layout_tag 0x%08x not found in table...all channels unassigned",
caf_channel_layout->mChannelLayoutTag);
break;
}
free (caf_channel_layout);
}
else if (!strncmp (caf_chunk_header.mChunkType, "data", 4)) { // on the data chunk, get size and exit loop
uint32_t mEditCount;
if (!DoReadFile (infile, &mEditCount, sizeof (mEditCount), &bcount) ||
bcount != sizeof (mEditCount)) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &mEditCount, sizeof (mEditCount))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
if ((config->qmode & QMODE_IGNORE_LENGTH) || caf_chunk_header.mChunkSize == -1) {
config->qmode |= QMODE_IGNORE_LENGTH;
if (infilesize && DoGetFilePosition (infile) != -1)
total_samples = (infilesize - DoGetFilePosition (infile)) / caf_audio_format.mBytesPerPacket;
else
total_samples = -1;
}
else {
if (infilesize && infilesize - caf_chunk_header.mChunkSize > 16777216) {
error_line (".CAF file %s has over 16 MB of extra CAFF data, probably is corrupt!", infilename);
return WAVPACK_SOFT_ERROR;
}
if ((caf_chunk_header.mChunkSize - 4) % caf_audio_format.mBytesPerPacket) {
error_line (".CAF file %s has an invalid data chunk size, probably is corrupt!", infilename);
return WAVPACK_SOFT_ERROR;
}
total_samples = (caf_chunk_header.mChunkSize - 4) / caf_audio_format.mBytesPerPacket;
if (!total_samples) {
error_line ("this .CAF file has no audio samples, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
if (total_samples > MAX_WAVPACK_SAMPLES) {
error_line ("%s has too many samples for WavPack!", infilename);
return WAVPACK_SOFT_ERROR;
}
}
break;
}
else { // just copy unknown chunks to output file
uint32_t bytes_to_copy = (uint32_t) caf_chunk_header.mChunkSize;
char *buff;
if (caf_chunk_header.mChunkSize < 0 || caf_chunk_header.mChunkSize > 1048576) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
caf_chunk_header.mChunkType [0], caf_chunk_header.mChunkType [1], caf_chunk_header.mChunkType [2],
caf_chunk_header.mChunkType [3], caf_chunk_header.mChunkSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (!chan_chunk && !config->channel_mask && config->num_channels <= 2 && !(config->qmode & QMODE_CHANS_UNASSIGNED))
config->channel_mask = 0x5 - config->num_channels;
if (!WavpackSetConfiguration64 (wpc, config, total_samples, channel_identities)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
if (channel_identities)
free (channel_identities);
if (channel_layout || channel_reorder) {
if (!WavpackSetChannelLayout (wpc, channel_layout, channel_reorder)) {
error_line ("problem with setting channel layout (should not happen)");
return WAVPACK_SOFT_ERROR;
}
if (channel_reorder)
free (channel_reorder);
}
return WAVPACK_NO_ERROR;
}
Commit Message: issue #66: make sure CAF files have a "desc" chunk
CWE ID: CWE-665
Target: 1
Example 2:
Code: void HTMLInputElement::parseMaxLengthAttribute(const AtomicString& value)
{
int maxLength;
if (!parseHTMLInteger(value, maxLength))
maxLength = maximumLength;
if (maxLength < 0 || maxLength > maximumLength)
maxLength = maximumLength;
int oldMaxLength = m_maxLength;
m_maxLength = maxLength;
if (oldMaxLength != maxLength)
updateValueIfNeeded();
setNeedsStyleRecalc();
setNeedsValidityCheck();
}
Commit Message: Setting input.x-webkit-speech should not cause focus change
In r150866, we introduced element()->focus() in destroyShadowSubtree()
to retain focus on <input> when its type attribute gets changed.
But when x-webkit-speech attribute is changed, the element is detached
before calling destroyShadowSubtree() and element()->focus() failed
This patch moves detach() after destroyShadowSubtree() to fix the
problem.
BUG=243818
TEST=fast/forms/input-type-change-focusout.html
NOTRY=true
Review URL: https://chromiumcodereview.appspot.com/16084005
git-svn-id: svn://svn.chromium.org/blink/trunk@151444 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int ZSTD_minCLevel(void) { return (int)-ZSTD_TARGETLENGTH_MAX; }
Commit Message: fixed T36302429
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int wasm_dis(WasmOp *op, const unsigned char *buf, int buf_len) {
op->len = 1;
op->op = buf[0];
if (op->op > 0xbf) {
return 1;
}
WasmOpDef *opdef = &opcodes[op->op];
switch (op->op) {
case WASM_OP_TRAP:
case WASM_OP_NOP:
case WASM_OP_ELSE:
case WASM_OP_RETURN:
case WASM_OP_DROP:
case WASM_OP_SELECT:
case WASM_OP_I32EQZ:
case WASM_OP_I32EQ:
case WASM_OP_I32NE:
case WASM_OP_I32LTS:
case WASM_OP_I32LTU:
case WASM_OP_I32GTS:
case WASM_OP_I32GTU:
case WASM_OP_I32LES:
case WASM_OP_I32LEU:
case WASM_OP_I32GES:
case WASM_OP_I32GEU:
case WASM_OP_I64EQZ:
case WASM_OP_I64EQ:
case WASM_OP_I64NE:
case WASM_OP_I64LTS:
case WASM_OP_I64LTU:
case WASM_OP_I64GTS:
case WASM_OP_I64GTU:
case WASM_OP_I64LES:
case WASM_OP_I64LEU:
case WASM_OP_I64GES:
case WASM_OP_I64GEU:
case WASM_OP_F32EQ:
case WASM_OP_F32NE:
case WASM_OP_F32LT:
case WASM_OP_F32GT:
case WASM_OP_F32LE:
case WASM_OP_F32GE:
case WASM_OP_F64EQ:
case WASM_OP_F64NE:
case WASM_OP_F64LT:
case WASM_OP_F64GT:
case WASM_OP_F64LE:
case WASM_OP_F64GE:
case WASM_OP_I32CLZ:
case WASM_OP_I32CTZ:
case WASM_OP_I32POPCNT:
case WASM_OP_I32ADD:
case WASM_OP_I32SUB:
case WASM_OP_I32MUL:
case WASM_OP_I32DIVS:
case WASM_OP_I32DIVU:
case WASM_OP_I32REMS:
case WASM_OP_I32REMU:
case WASM_OP_I32AND:
case WASM_OP_I32OR:
case WASM_OP_I32XOR:
case WASM_OP_I32SHL:
case WASM_OP_I32SHRS:
case WASM_OP_I32SHRU:
case WASM_OP_I32ROTL:
case WASM_OP_I32ROTR:
case WASM_OP_I64CLZ:
case WASM_OP_I64CTZ:
case WASM_OP_I64POPCNT:
case WASM_OP_I64ADD:
case WASM_OP_I64SUB:
case WASM_OP_I64MUL:
case WASM_OP_I64DIVS:
case WASM_OP_I64DIVU:
case WASM_OP_I64REMS:
case WASM_OP_I64REMU:
case WASM_OP_I64AND:
case WASM_OP_I64OR:
case WASM_OP_I64XOR:
case WASM_OP_I64SHL:
case WASM_OP_I64SHRS:
case WASM_OP_I64SHRU:
case WASM_OP_I64ROTL:
case WASM_OP_I64ROTR:
case WASM_OP_F32ABS:
case WASM_OP_F32NEG:
case WASM_OP_F32CEIL:
case WASM_OP_F32FLOOR:
case WASM_OP_F32TRUNC:
case WASM_OP_F32NEAREST:
case WASM_OP_F32SQRT:
case WASM_OP_F32ADD:
case WASM_OP_F32SUB:
case WASM_OP_F32MUL:
case WASM_OP_F32DIV:
case WASM_OP_F32MIN:
case WASM_OP_F32MAX:
case WASM_OP_F32COPYSIGN:
case WASM_OP_F64ABS:
case WASM_OP_F64NEG:
case WASM_OP_F64CEIL:
case WASM_OP_F64FLOOR:
case WASM_OP_F64TRUNC:
case WASM_OP_F64NEAREST:
case WASM_OP_F64SQRT:
case WASM_OP_F64ADD:
case WASM_OP_F64SUB:
case WASM_OP_F64MUL:
case WASM_OP_F64DIV:
case WASM_OP_F64MIN:
case WASM_OP_F64MAX:
case WASM_OP_F64COPYSIGN:
case WASM_OP_I32WRAPI64:
case WASM_OP_I32TRUNCSF32:
case WASM_OP_I32TRUNCUF32:
case WASM_OP_I32TRUNCSF64:
case WASM_OP_I32TRUNCUF64:
case WASM_OP_I64EXTENDSI32:
case WASM_OP_I64EXTENDUI32:
case WASM_OP_I64TRUNCSF32:
case WASM_OP_I64TRUNCUF32:
case WASM_OP_I64TRUNCSF64:
case WASM_OP_I64TRUNCUF64:
case WASM_OP_F32CONVERTSI32:
case WASM_OP_F32CONVERTUI32:
case WASM_OP_F32CONVERTSI64:
case WASM_OP_F32CONVERTUI64:
case WASM_OP_F32DEMOTEF64:
case WASM_OP_F64CONVERTSI32:
case WASM_OP_F64CONVERTUI32:
case WASM_OP_F64CONVERTSI64:
case WASM_OP_F64CONVERTUI64:
case WASM_OP_F64PROMOTEF32:
case WASM_OP_I32REINTERPRETF32:
case WASM_OP_I64REINTERPRETF64:
case WASM_OP_F32REINTERPRETI32:
case WASM_OP_F64REINTERPRETI64:
case WASM_OP_END:
{
snprintf (op->txt, R_ASM_BUFSIZE, "%s", opdef->txt);
}
break;
case WASM_OP_BLOCK:
case WASM_OP_LOOP:
case WASM_OP_IF:
{
st32 val = 0;
size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
switch (0x80 - val) {
case R_BIN_WASM_VALUETYPE_EMPTY:
snprintf (op->txt, R_ASM_BUFSIZE, "%s", opdef->txt);
break;
case R_BIN_WASM_VALUETYPE_i32:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result i32)", opdef->txt);
break;
case R_BIN_WASM_VALUETYPE_i64:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result i64)", opdef->txt);
break;
case R_BIN_WASM_VALUETYPE_f32:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result f32)", opdef->txt);
break;
case R_BIN_WASM_VALUETYPE_f64:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result f64)", opdef->txt);
break;
default:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result ?)", opdef->txt);
break;
}
op->len += n;
}
break;
case WASM_OP_BR:
case WASM_OP_BRIF:
case WASM_OP_CALL:
{
ut32 val = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, val);
op->len += n;
}
break;
case WASM_OP_BRTABLE:
{
ut32 count = 0, *table = NULL, def = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &count);
if (!(n > 0 && n < buf_len)) {
goto err;
}
if (!(table = calloc (count, sizeof (ut32)))) {
goto err;
}
int i = 0;
op->len += n;
for (i = 0; i < count; i++) {
n = read_u32_leb128 (buf + op->len, buf + buf_len, &table[i]);
if (!(op->len + n <= buf_len)) {
goto beach;
}
op->len += n;
}
n = read_u32_leb128 (buf + op->len, buf + buf_len, &def);
if (!(n > 0 && n + op->len < buf_len)) {
goto beach;
}
op->len += n;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d ", opdef->txt, count);
for (i = 0; i < count && strlen (op->txt) + 10 < R_ASM_BUFSIZE; i++) {
int optxtlen = strlen (op->txt);
snprintf (op->txt + optxtlen, R_ASM_BUFSIZE - optxtlen, "%d ", table[i]);
}
snprintf (op->txt + strlen (op->txt), R_ASM_BUFSIZE, "%d", def);
free (table);
break;
beach:
free (table);
goto err;
}
break;
case WASM_OP_CALLINDIRECT:
{
ut32 val = 0, reserved = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
op->len += n;
n = read_u32_leb128 (buf + op->len, buf + buf_len, &reserved);
if (!(n == 1 && op->len + n <= buf_len)) goto err;
reserved &= 0x1;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d %d", opdef->txt, val, reserved);
op->len += n;
}
break;
case WASM_OP_GETLOCAL:
case WASM_OP_SETLOCAL:
case WASM_OP_TEELOCAL:
case WASM_OP_GETGLOBAL:
case WASM_OP_SETGLOBAL:
{
ut32 val = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, val);
op->len += n;
}
break;
case WASM_OP_I32LOAD:
case WASM_OP_I64LOAD:
case WASM_OP_F32LOAD:
case WASM_OP_F64LOAD:
case WASM_OP_I32LOAD8S:
case WASM_OP_I32LOAD8U:
case WASM_OP_I32LOAD16S:
case WASM_OP_I32LOAD16U:
case WASM_OP_I64LOAD8S:
case WASM_OP_I64LOAD8U:
case WASM_OP_I64LOAD16S:
case WASM_OP_I64LOAD16U:
case WASM_OP_I64LOAD32S:
case WASM_OP_I64LOAD32U:
case WASM_OP_I32STORE:
case WASM_OP_I64STORE:
case WASM_OP_F32STORE:
case WASM_OP_F64STORE:
case WASM_OP_I32STORE8:
case WASM_OP_I32STORE16:
case WASM_OP_I64STORE8:
case WASM_OP_I64STORE16:
case WASM_OP_I64STORE32:
{
ut32 flag = 0, offset = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &flag);
if (!(n > 0 && n < buf_len)) goto err;
op->len += n;
n = read_u32_leb128 (buf + op->len, buf + buf_len, &offset);
if (!(n > 0 && op->len + n <= buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d %d", opdef->txt, flag, offset);
op->len += n;
}
break;
case WASM_OP_CURRENTMEMORY:
case WASM_OP_GROWMEMORY:
{
ut32 reserved = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &reserved);
if (!(n == 1 && n < buf_len)) goto err;
reserved &= 0x1;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, reserved);
op->len += n;
}
break;
case WASM_OP_I32CONST:
{
st32 val = 0;
size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %" PFMT32d, opdef->txt, val);
op->len += n;
}
break;
case WASM_OP_I64CONST:
{
st64 val = 0;
size_t n = read_i64_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %" PFMT64d, opdef->txt, val);
op->len += n;
}
break;
case WASM_OP_F32CONST:
{
ut32 val = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
long double d = (long double)val;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %" LDBLFMT, opdef->txt, d);
op->len += n;
}
break;
case WASM_OP_F64CONST:
{
ut64 val = 0;
size_t n = read_u64_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
long double d = (long double)val;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %" LDBLFMT, opdef->txt, d);
op->len += n;
}
break;
default:
goto err;
}
return op->len;
err:
op->len = 1;
snprintf (op->txt, R_ASM_BUFSIZE, "invalid");
return op->len;
}
Commit Message: Fix #9969 - Stack overflow in wasm disassembler
CWE ID: CWE-119
Target: 1
Example 2:
Code: ResourcePtr<Resource> fetchImage()
{
FetchRequest fetchRequest(ResourceRequest(KURL(ParsedURLString, kResourceURL)), FetchInitiatorInfo());
return ImageResource::fetch(fetchRequest, fetcher());
}
Commit Message: Add assertions that the empty Platform::cryptographicallyRandomValues() overrides are not being used.
These implementations are not safe and look scary if not accompanied by an assertion. Also one of the comments was incorrect.
BUG=552749
Review URL: https://codereview.chromium.org/1419293005
Cr-Commit-Position: refs/heads/master@{#359229}
CWE ID: CWE-310
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int bzrtp_packetParser(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext, const uint8_t * input, uint16_t inputLength, bzrtpPacket_t *zrtpPacket) {
int i;
/* now allocate and fill the correct message structure according to the message type */
/* messageContent points to the begining of the ZRTP message */
uint8_t *messageContent = (uint8_t *)(input+ZRTP_PACKET_HEADER_LENGTH+ZRTP_MESSAGE_HEADER_LENGTH);
switch (zrtpPacket->messageType) {
case MSGTYPE_HELLO :
{
/* allocate a Hello message structure */
bzrtpHelloMessage_t *messageData;
messageData = (bzrtpHelloMessage_t *)malloc(sizeof(bzrtpHelloMessage_t));
/* fill it */
memcpy(messageData->version, messageContent, 4);
messageContent +=4;
memcpy(messageData->clientIdentifier, messageContent, 16);
messageContent +=16;
memcpy(messageData->H3, messageContent, 32);
messageContent +=32;
memcpy(messageData->ZID, messageContent, 12);
messageContent +=12;
messageData->S = ((*messageContent)>>6)&0x01;
messageData->M = ((*messageContent)>>5)&0x01;
messageData->P = ((*messageContent)>>4)&0x01;
messageContent +=1;
messageData->hc = MIN((*messageContent)&0x0F, 7);
messageContent +=1;
messageData->cc = MIN(((*messageContent)>>4)&0x0F, 7);
messageData->ac = MIN((*messageContent)&0x0F, 7);
messageContent +=1;
messageData->kc = MIN(((*messageContent)>>4)&0x0F, 7);
messageData->sc = MIN((*messageContent)&0x0F, 7);
messageContent +=1;
/* Check message length according to value in hc, cc, ac, kc and sc */
if (zrtpPacket->messageLength != ZRTP_HELLOMESSAGE_FIXED_LENGTH + 4*((uint16_t)(messageData->hc)+(uint16_t)(messageData->cc)+(uint16_t)(messageData->ac)+(uint16_t)(messageData->kc)+(uint16_t)(messageData->sc))) {
free(messageData);
return BZRTP_PARSER_ERROR_INVALIDMESSAGE;
}
/* parse the variable length part: algorithms types */
for (i=0; i<messageData->hc; i++) {
messageData->supportedHash[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_HASH_TYPE);
messageContent +=4;
}
for (i=0; i<messageData->cc; i++) {
messageData->supportedCipher[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_CIPHERBLOCK_TYPE);
messageContent +=4;
}
for (i=0; i<messageData->ac; i++) {
messageData->supportedAuthTag[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_AUTHTAG_TYPE);
messageContent +=4;
}
for (i=0; i<messageData->kc; i++) {
messageData->supportedKeyAgreement[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_KEYAGREEMENT_TYPE);
messageContent +=4;
}
for (i=0; i<messageData->sc; i++) {
messageData->supportedSas[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_SAS_TYPE);
messageContent +=4;
}
addMandatoryCryptoTypesIfNeeded(ZRTP_HASH_TYPE, messageData->supportedHash, &messageData->hc);
addMandatoryCryptoTypesIfNeeded(ZRTP_CIPHERBLOCK_TYPE, messageData->supportedCipher, &messageData->cc);
addMandatoryCryptoTypesIfNeeded(ZRTP_AUTHTAG_TYPE, messageData->supportedAuthTag, &messageData->ac);
addMandatoryCryptoTypesIfNeeded(ZRTP_KEYAGREEMENT_TYPE, messageData->supportedKeyAgreement, &messageData->kc);
addMandatoryCryptoTypesIfNeeded(ZRTP_SAS_TYPE, messageData->supportedSas, &messageData->sc);
memcpy(messageData->MAC, messageContent, 8);
/* attach the message structure to the packet one */
zrtpPacket->messageData = (void *)messageData;
/* the parsed Hello packet must be saved as it may be used to generate commit message or the total_hash */
zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t));
memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */
}
break; /* MSGTYPE_HELLO */
case MSGTYPE_HELLOACK :
{
/* check message length */
if (zrtpPacket->messageLength != ZRTP_HELLOACKMESSAGE_FIXED_LENGTH) {
return BZRTP_PARSER_ERROR_INVALIDMESSAGE;
}
}
break; /* MSGTYPE_HELLOACK */
case MSGTYPE_COMMIT:
{
uint8_t checkH3[32];
uint8_t checkMAC[32];
bzrtpHelloMessage_t *peerHelloMessageData;
uint16_t variableLength = 0;
/* allocate a commit message structure */
bzrtpCommitMessage_t *messageData;
messageData = (bzrtpCommitMessage_t *)malloc(sizeof(bzrtpCommitMessage_t));
/* fill the structure */
memcpy(messageData->H2, messageContent, 32);
messageContent +=32;
/* We have now H2, check it matches the H3 we had in the hello message H3=SHA256(H2) and that the Hello message MAC is correct */
if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] == NULL) {
free (messageData);
/* we have no Hello message in this channel, this commit shall never have arrived, discard it as invalid */
return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
}
peerHelloMessageData = (bzrtpHelloMessage_t *)zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData;
/* Check H3 = SHA256(H2) */
bctoolbox_sha256(messageData->H2, 32, 32, checkH3);
if (memcmp(checkH3, peerHelloMessageData->H3, 32) != 0) {
free (messageData);
return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN;
}
/* Check the hello MAC message.
* MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */
bctoolbox_hmacSha256(messageData->H2, 32, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC);
if (memcmp(checkMAC, peerHelloMessageData->MAC, 8) != 0) {
free (messageData);
return BZRTP_PARSER_ERROR_UNMATCHINGMAC;
}
memcpy(messageData->ZID, messageContent, 12);
messageContent +=12;
messageData->hashAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_HASH_TYPE);
messageContent += 4;
messageData->cipherAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_CIPHERBLOCK_TYPE);
messageContent += 4;
messageData->authTagAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_AUTHTAG_TYPE);
messageContent += 4;
messageData->keyAgreementAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_KEYAGREEMENT_TYPE);
messageContent += 4;
/* commit message length depends on the key agreement type choosen (and set in the zrtpContext->keyAgreementAlgo) */
switch(messageData->keyAgreementAlgo) {
case ZRTP_KEYAGREEMENT_DH2k :
case ZRTP_KEYAGREEMENT_EC25 :
case ZRTP_KEYAGREEMENT_DH3k :
case ZRTP_KEYAGREEMENT_EC38 :
case ZRTP_KEYAGREEMENT_EC52 :
variableLength = 32; /* hvi is 32 bytes length in DH Commit message format */
break;
case ZRTP_KEYAGREEMENT_Prsh :
variableLength = 24; /* nonce (16 bytes) and keyID(8 bytes) are 24 bytes length in preshared Commit message format */
break;
case ZRTP_KEYAGREEMENT_Mult :
variableLength = 16; /* nonce is 24 bytes length in multistream Commit message format */
break;
default:
free(messageData);
return BZRTP_PARSER_ERROR_INVALIDMESSAGE;
}
if (zrtpPacket->messageLength != ZRTP_COMMITMESSAGE_FIXED_LENGTH + variableLength) {
free(messageData);
return BZRTP_PARSER_ERROR_INVALIDMESSAGE;
}
messageData->sasAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_SAS_TYPE);
messageContent += 4;
/* if it is a multistream or preshared commit, get the 16 bytes nonce */
if ((messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) || (messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult)) {
memcpy(messageData->nonce, messageContent, 16);
messageContent +=16;
/* and the keyID for preshared commit only */
if (messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) {
memcpy(messageData->keyID, messageContent, 8);
messageContent +=8;
}
} else { /* it's a DH commit message, get the hvi */
memcpy(messageData->hvi, messageContent, 32);
messageContent +=32;
}
/* get the MAC and attach the message data to the packet structure */
memcpy(messageData->MAC, messageContent, 8);
zrtpPacket->messageData = (void *)messageData;
/* the parsed commit packet must be saved as it is used to generate the total_hash */
zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t));
memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */
}
break; /* MSGTYPE_COMMIT */
case MSGTYPE_DHPART1 :
case MSGTYPE_DHPART2 :
{
bzrtpDHPartMessage_t *messageData;
/*check message length, depends on the selected key agreement algo set in zrtpContext */
uint16_t pvLength = computeKeyAgreementPrivateValueLength(zrtpChannelContext->keyAgreementAlgo);
if (pvLength == 0) {
return BZRTP_PARSER_ERROR_INVALIDCONTEXT;
}
if (zrtpPacket->messageLength != ZRTP_DHPARTMESSAGE_FIXED_LENGTH+pvLength) {
return BZRTP_PARSER_ERROR_INVALIDMESSAGE;
}
/* allocate a DHPart message structure and pv */
messageData = (bzrtpDHPartMessage_t *)malloc(sizeof(bzrtpDHPartMessage_t));
messageData->pv = (uint8_t *)malloc(pvLength*sizeof(uint8_t));
/* fill the structure */
memcpy(messageData->H1, messageContent, 32);
messageContent +=32;
/* We have now H1, check it matches the H2 we had in the commit message H2=SHA256(H1) and that the Commit message MAC is correct */
if ( zrtpChannelContext->role == RESPONDER) { /* do it only if we are responder (we received a commit packet) */
uint8_t checkH2[32];
uint8_t checkMAC[32];
bzrtpCommitMessage_t *peerCommitMessageData;
if (zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID] == NULL) {
free (messageData);
/* we have no Commit message in this channel, this DHPart2 shall never have arrived, discard it as invalid */
return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
}
peerCommitMessageData = (bzrtpCommitMessage_t *)zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageData;
/* Check H2 = SHA256(H1) */
bctoolbox_sha256(messageData->H1, 32, 32, checkH2);
if (memcmp(checkH2, peerCommitMessageData->H2, 32) != 0) {
free (messageData);
return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN;
}
/* Check the Commit MAC message.
* MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */
bctoolbox_hmacSha256(messageData->H1, 32, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC);
if (memcmp(checkMAC, peerCommitMessageData->MAC, 8) != 0) {
free (messageData);
return BZRTP_PARSER_ERROR_UNMATCHINGMAC;
}
} else { /* if we are initiator(we didn't received any commit message and then no H2), we must check that H3=SHA256(SHA256(H1)) and the Hello message MAC */
uint8_t checkH2[32];
uint8_t checkH3[32];
uint8_t checkMAC[32];
bzrtpHelloMessage_t *peerHelloMessageData;
if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] == NULL) {
free (messageData);
/* we have no Hello message in this channel, this DHPart1 shall never have arrived, discard it as invalid */
return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
}
peerHelloMessageData = (bzrtpHelloMessage_t *)zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData;
/* Check H3 = SHA256(SHA256(H1)) */
bctoolbox_sha256(messageData->H1, 32, 32, checkH2);
bctoolbox_sha256(checkH2, 32, 32, checkH3);
if (memcmp(checkH3, peerHelloMessageData->H3, 32) != 0) {
free (messageData);
return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN;
}
/* Check the hello MAC message.
* MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */
bctoolbox_hmacSha256(checkH2, 32, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC);
if (memcmp(checkMAC, peerHelloMessageData->MAC, 8) != 0) {
free (messageData);
return BZRTP_PARSER_ERROR_UNMATCHINGMAC;
}
}
memcpy(messageData->rs1ID, messageContent, 8);
messageContent +=8;
memcpy(messageData->rs2ID, messageContent, 8);
messageContent +=8;
memcpy(messageData->auxsecretID, messageContent, 8);
messageContent +=8;
memcpy(messageData->pbxsecretID, messageContent, 8);
messageContent +=8;
memcpy(messageData->pv, messageContent, pvLength);
messageContent +=pvLength;
memcpy(messageData->MAC, messageContent, 8);
/* attach the message structure to the packet one */
zrtpPacket->messageData = (void *)messageData;
/* the parsed commit packet must be saved as it is used to generate the total_hash */
zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t));
memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */
}
break; /* MSGTYPE_DHPART1 and MSGTYPE_DHPART2 */
case MSGTYPE_CONFIRM1:
case MSGTYPE_CONFIRM2:
{
uint8_t *confirmMessageKey = NULL;
uint8_t *confirmMessageMacKey = NULL;
bzrtpConfirmMessage_t *messageData;
uint16_t cipherTextLength;
uint8_t computedHmac[8];
uint8_t *confirmPlainMessageBuffer;
uint8_t *confirmPlainMessage;
/* we shall first decrypt and validate the message, check we have the keys to do it */
if (zrtpChannelContext->role == RESPONDER) { /* responder uses initiator's keys to decrypt */
if ((zrtpChannelContext->zrtpkeyi == NULL) || (zrtpChannelContext->mackeyi == NULL)) {
return BZRTP_PARSER_ERROR_INVALIDCONTEXT;
}
confirmMessageKey = zrtpChannelContext->zrtpkeyi;
confirmMessageMacKey = zrtpChannelContext->mackeyi;
}
if (zrtpChannelContext->role == INITIATOR) { /* the iniator uses responder's keys to decrypt */
if ((zrtpChannelContext->zrtpkeyr == NULL) || (zrtpChannelContext->mackeyr == NULL)) {
return BZRTP_PARSER_ERROR_INVALIDCONTEXT;
}
confirmMessageKey = zrtpChannelContext->zrtpkeyr;
confirmMessageMacKey = zrtpChannelContext->mackeyr;
}
/* allocate a confirm message structure */
messageData = (bzrtpConfirmMessage_t *)malloc(sizeof(bzrtpConfirmMessage_t));
/* get the mac and the IV */
memcpy(messageData->confirm_mac, messageContent, 8);
messageContent +=8;
memcpy(messageData->CFBIV, messageContent, 16);
messageContent +=16;
/* get the cipher text length */
cipherTextLength = zrtpPacket->messageLength - ZRTP_MESSAGE_HEADER_LENGTH - 24; /* confirm message is header, confirm_mac(8 bytes), CFB IV(16 bytes), encrypted part */
/* validate the mac over the cipher text */
zrtpChannelContext->hmacFunction(confirmMessageMacKey, zrtpChannelContext->hashLength, messageContent, cipherTextLength, 8, computedHmac);
if (memcmp(computedHmac, messageData->confirm_mac, 8) != 0) { /* confirm_mac doesn't match */
free(messageData);
return BZRTP_PARSER_ERROR_UNMATCHINGCONFIRMMAC;
}
/* get plain message */
confirmPlainMessageBuffer = (uint8_t *)malloc(cipherTextLength*sizeof(uint8_t));
zrtpChannelContext->cipherDecryptionFunction(confirmMessageKey, messageData->CFBIV, messageContent, cipherTextLength, confirmPlainMessageBuffer);
confirmPlainMessage = confirmPlainMessageBuffer; /* point into the allocated buffer */
/* parse it */
memcpy(messageData->H0, confirmPlainMessage, 32);
confirmPlainMessage +=33; /* +33 because next 8 bits are unused */
/* Hash chain checking: if we are in multichannel or shared mode, we had not DHPart and then no H1 */
if (zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh || zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult) {
/* compute the H1=SHA256(H0) we never received */
uint8_t checkH1[32];
bctoolbox_sha256(messageData->H0, 32, 32, checkH1);
/* if we are responder, we received a commit packet with H2 then check that H2=SHA256(H1) and that the commit message MAC keyed with H1 match */
if ( zrtpChannelContext->role == RESPONDER) {
uint8_t checkH2[32];
uint8_t checkMAC[32];
bzrtpCommitMessage_t *peerCommitMessageData;
if (zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID] == NULL) {
free (messageData);
/* we have no Commit message in this channel, this Confirm2 shall never have arrived, discard it as invalid */
return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
}
peerCommitMessageData = (bzrtpCommitMessage_t *)zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageData;
/* Check H2 = SHA256(H1) */
bctoolbox_sha256(checkH1, 32, 32, checkH2);
if (memcmp(checkH2, peerCommitMessageData->H2, 32) != 0) {
free (messageData);
return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN;
}
/* Check the Commit MAC message.
* MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */
bctoolbox_hmacSha256(checkH1, 32, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC);
if (memcmp(checkMAC, peerCommitMessageData->MAC, 8) != 0) {
free (messageData);
return BZRTP_PARSER_ERROR_UNMATCHINGMAC;
}
} else { /* if we are initiator(we didn't received any commit message and then no H2), we must check that H3=SHA256(SHA256(H1)) and the Hello message MAC */
uint8_t checkH2[32];
uint8_t checkH3[32];
uint8_t checkMAC[32];
bzrtpHelloMessage_t *peerHelloMessageData;
if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] == NULL) {
free (messageData);
/* we have no Hello message in this channel, this Confirm1 shall never have arrived, discard it as invalid */
return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
}
peerHelloMessageData = (bzrtpHelloMessage_t *)zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData;
/* Check H3 = SHA256(SHA256(H1)) */
bctoolbox_sha256(checkH1, 32, 32, checkH2);
bctoolbox_sha256(checkH2, 32, 32, checkH3);
if (memcmp(checkH3, peerHelloMessageData->H3, 32) != 0) {
free (messageData);
return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN;
}
/* Check the hello MAC message.
* MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */
bctoolbox_hmacSha256(checkH2, 32, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC);
if (memcmp(checkMAC, peerHelloMessageData->MAC, 8) != 0) {
free (messageData);
return BZRTP_PARSER_ERROR_UNMATCHINGMAC;
}
}
} else { /* we are in DHM mode */
/* We have now H0, check it matches the H1 we had in the DHPart message H1=SHA256(H0) and that the DHPart message MAC is correct */
uint8_t checkH1[32];
uint8_t checkMAC[32];
bzrtpDHPartMessage_t *peerDHPartMessageData;
if (zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID] == NULL) {
free (messageData);
/* we have no DHPART message in this channel, this confirm shall never have arrived, discard it as invalid */
return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
}
peerDHPartMessageData = (bzrtpDHPartMessage_t *)zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageData;
/* Check H1 = SHA256(H0) */
bctoolbox_sha256(messageData->H0, 32, 32, checkH1);
if (memcmp(checkH1, peerDHPartMessageData->H1, 32) != 0) {
free (messageData);
return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN;
}
/* Check the DHPart message.
* MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */
bctoolbox_hmacSha256(messageData->H0, 32, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC);
if (memcmp(checkMAC, peerDHPartMessageData->MAC, 8) != 0) {
free (messageData);
return BZRTP_PARSER_ERROR_UNMATCHINGMAC;
}
}
messageData->sig_len = ((uint16_t)(confirmPlainMessage[0]&0x01))<<8 | (((uint16_t)confirmPlainMessage[1])&0x00FF);
confirmPlainMessage += 2;
messageData->E = ((*confirmPlainMessage)&0x08)>>3;
messageData->V = ((*confirmPlainMessage)&0x04)>>2;
messageData->A = ((*confirmPlainMessage)&0x02)>>1;
messageData->D = (*confirmPlainMessage)&0x01;
confirmPlainMessage += 1;
messageData->cacheExpirationInterval = (((uint32_t)confirmPlainMessage[0])<<24) | (((uint32_t)confirmPlainMessage[1])<<16) | (((uint32_t)confirmPlainMessage[2])<<8) | ((uint32_t)confirmPlainMessage[3]);
confirmPlainMessage += 4;
/* if sig_len indicate a signature, parse it */
if (messageData->sig_len>0) {
memcpy(messageData->signatureBlockType, confirmPlainMessage, 4);
confirmPlainMessage += 4;
/* allocate memory for the signature block, sig_len is in words(32 bits) and includes the signature block type word */
messageData->signatureBlock = (uint8_t *)malloc(4*(messageData->sig_len-1)*sizeof(uint8_t));
memcpy(messageData->signatureBlock, confirmPlainMessage, 4*(messageData->sig_len-1));
} else {
messageData->signatureBlock = NULL;
}
/* free plain buffer */
free(confirmPlainMessageBuffer);
/* the parsed commit packet must be saved as it is used to check correct packet repetition */
zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t));
memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */
/* attach the message structure to the packet one */
zrtpPacket->messageData = (void *)messageData;
}
break; /* MSGTYPE_CONFIRM1 and MSGTYPE_CONFIRM2 */
case MSGTYPE_CONF2ACK:
/* nothing to do for this one */
break; /* MSGTYPE_CONF2ACK */
case MSGTYPE_PING:
{
/* allocate a ping message structure */
bzrtpPingMessage_t *messageData;
messageData = (bzrtpPingMessage_t *)malloc(sizeof(bzrtpPingMessage_t));
/* fill the structure */
memcpy(messageData->version, messageContent, 4);
messageContent +=4;
memcpy(messageData->endpointHash, messageContent, 8);
/* attach the message structure to the packet one */
zrtpPacket->messageData = (void *)messageData;
}
break; /* MSGTYPE_PING */
}
return 0;
}
Commit Message: Add ZRTP Commit packet hvi check on DHPart2 packet reception
CWE ID: CWE-254
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ossl_cipher_initialize(VALUE self, VALUE str)
{
EVP_CIPHER_CTX *ctx;
const EVP_CIPHER *cipher;
char *name;
unsigned char dummy_key[EVP_MAX_KEY_LENGTH] = { 0 };
name = StringValueCStr(str);
GetCipherInit(self, ctx);
if (ctx) {
ossl_raise(rb_eRuntimeError, "Cipher already inititalized!");
}
AllocCipher(self, ctx);
if (!(cipher = EVP_get_cipherbyname(name))) {
ossl_raise(rb_eRuntimeError, "unsupported cipher algorithm (%"PRIsVALUE")", str);
}
/*
* EVP_CipherInit_ex() allows to specify NULL to key and IV, however some
* ciphers don't handle well (OpenSSL's bug). [Bug #2768]
*
* The EVP which has EVP_CIPH_RAND_KEY flag (such as DES3) allows
* uninitialized key, but other EVPs (such as AES) does not allow it.
* Calling EVP_CipherUpdate() without initializing key causes SEGV so we
* set the data filled with "\0" as the key by default.
*/
if (EVP_CipherInit_ex(ctx, cipher, NULL, dummy_key, NULL, -1) != 1)
ossl_raise(eCipherError, NULL);
return self;
}
Commit Message: cipher: don't set dummy encryption key in Cipher#initialize
Remove the encryption key initialization from Cipher#initialize. This
is effectively a revert of r32723 ("Avoid possible SEGV from AES
encryption/decryption", 2011-07-28).
r32723, which added the key initialization, was a workaround for
Ruby Bug #2768. For some certain ciphers, calling EVP_CipherUpdate()
before setting an encryption key caused segfault. It was not a problem
until OpenSSL implemented GCM mode - the encryption key could be
overridden by repeated calls of EVP_CipherInit_ex(). But, it is not the
case for AES-GCM ciphers. Setting a key, an IV, a key, in this order
causes the IV to be reset to an all-zero IV.
The problem of Bug #2768 persists on the current versions of OpenSSL.
So, make Cipher#update raise an exception if a key is not yet set by the
user. Since encrypting or decrypting without key does not make any
sense, this should not break existing applications.
Users can still call Cipher#key= and Cipher#iv= multiple times with
their own responsibility.
Reference: https://bugs.ruby-lang.org/issues/2768
Reference: https://bugs.ruby-lang.org/issues/8221
Reference: https://github.com/ruby/openssl/issues/49
CWE ID: CWE-310
Target: 1
Example 2:
Code: bool PopupContainer::handleMouseMoveEvent(const PlatformMouseEvent& event)
{
UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
return m_listBox->handleMouseMoveEvent(
constructRelativeMouseEvent(event, this, m_listBox.get()));
}
Commit Message: [REGRESSION] Refreshed autofill popup renders garbage
https://bugs.webkit.org/show_bug.cgi?id=83255
http://code.google.com/p/chromium/issues/detail?id=118374
The code used to update only the PopupContainer coordinates as if they were the coordinates relative
to the root view. Instead, a WebWidget positioned relative to the screen origin holds the PopupContainer,
so it is the WebWidget that should be positioned in PopupContainer::refresh(), and the PopupContainer's
location should be (0, 0) (and their sizes should always be equal).
Reviewed by Kent Tamura.
No new tests, as the popup appearance is not testable in WebKit.
* platform/chromium/PopupContainer.cpp:
(WebCore::PopupContainer::layoutAndCalculateWidgetRect): Variable renamed.
(WebCore::PopupContainer::showPopup): Use m_originalFrameRect rather than frameRect()
for passing into chromeClient.
(WebCore::PopupContainer::showInRect): Set up the correct frameRect() for the container.
(WebCore::PopupContainer::refresh): Resize the container and position the WebWidget correctly.
* platform/chromium/PopupContainer.h:
(PopupContainer):
git-svn-id: svn://svn.chromium.org/blink/trunk@113418 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: gs_main_finit(gs_main_instance * minst, int exit_status, int code)
{
i_ctx_t *i_ctx_p = minst->i_ctx_p;
gs_dual_memory_t dmem = {0};
int exit_code;
ref error_object;
char *tempnames;
/* NB: need to free gs_name_table
*/
/*
* Previous versions of this code closed the devices in the
* device list here. Since these devices are now prototypes,
* they cannot be opened, so they do not need to be closed;
* alloc_restore_all will close dynamically allocated devices.
*/
tempnames = gs_main_tempnames(minst);
/* by the time we get here, we *must* avoid any random redefinitions of
* operators etc, so we push systemdict onto the top of the dict stack.
* We do this in C to avoid running into any other re-defininitions in the
* Postscript world.
*/
gs_finit_push_systemdict(i_ctx_p);
/* We have to disable BGPrint before we call interp_reclaim() to prevent the
* parent rendering thread initialising for the next page, whilst we are
* removing objects it may want to access - for example, the I/O device table.
* We also have to mess with the BeginPage/EndPage procs so that we don't
* trigger a spurious extra page to be emitted.
*/
if (minst->init_done >= 2) {
gs_main_run_string(minst,
"/BGPrint /GetDeviceParam .special_op \
{{ <</BeginPage {pop} /EndPage {pop pop //false } \
/BGPrint false /NumRenderingThreads 0>> setpagedevice} if} if \
serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse \
.systemvar exec",
0 , &exit_code, &error_object);
}
/*
* Close the "main" device, because it may need to write out
* data before destruction. pdfwrite needs so.
*/
if (minst->init_done >= 2) {
int code = 0;
if (idmemory->reclaim != 0) {
code = interp_reclaim(&minst->i_ctx_p, avm_global);
if (code < 0) {
ref error_name;
if (tempnames)
free(tempnames);
if (gs_errorname(i_ctx_p, code, &error_name) >= 0) {
char err_str[32] = {0};
name_string_ref(imemory, &error_name, &error_name);
memcpy(err_str, error_name.value.const_bytes, r_size(&error_name));
emprintf2(imemory, "ERROR: %s (%d) reclaiming the memory while the interpreter finalization.\n", err_str, code);
}
else {
emprintf1(imemory, "UNKNOWN ERROR %d reclaiming the memory while the interpreter finalization.\n", code);
}
#ifdef MEMENTO_SQUEEZE_BUILD
if (code != gs_error_VMerror ) return gs_error_Fatal;
#else
return gs_error_Fatal;
#endif
}
i_ctx_p = minst->i_ctx_p; /* interp_reclaim could change it. */
}
if (i_ctx_p->pgs != NULL && i_ctx_p->pgs->device != NULL) {
gx_device *pdev = i_ctx_p->pgs->device;
const char * dname = pdev->dname;
if (code < 0) {
ref error_name;
if (gs_errorname(i_ctx_p, code, &error_name) >= 0) {
char err_str[32] = {0};
name_string_ref(imemory, &error_name, &error_name);
memcpy(err_str, error_name.value.const_bytes, r_size(&error_name));
emprintf3(imemory, "ERROR: %s (%d) on closing %s device.\n", err_str, code, dname);
}
else {
emprintf2(imemory, "UNKNOWN ERROR %d closing %s device.\n", code, dname);
}
}
rc_decrement(pdev, "gs_main_finit"); /* device might be freed */
if (exit_status == 0 || exit_status == gs_error_Quit)
exit_status = code;
}
/* Flush stdout and stderr */
gs_main_run_string(minst,
"(%stdout) (w) file closefile (%stderr) (w) file closefile \
serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse .systemexec \
systemdict /savedinitialgstate .forceundef",
0 , &exit_code, &error_object);
}
gp_readline_finit(minst->readline_data);
i_ctx_p = minst->i_ctx_p; /* get current interp context */
if (gs_debug_c(':')) {
print_resource_usage(minst, &gs_imemory, "Final");
dmprintf1(minst->heap, "%% Exiting instance 0x%p\n", minst);
}
/* Do the equivalent of a restore "past the bottom". */
/* This will release all memory, close all open files, etc. */
if (minst->init_done >= 1) {
gs_memory_t *mem_raw = i_ctx_p->memory.current->non_gc_memory;
i_plugin_holder *h = i_ctx_p->plugin_list;
dmem = *idmemory;
code = alloc_restore_all(i_ctx_p);
if (code < 0)
emprintf1(mem_raw,
"ERROR %d while the final restore. See gs/psi/ierrors.h for code explanation.\n",
code);
i_iodev_finit(&dmem);
i_plugin_finit(mem_raw, h);
}
/* clean up redirected stdout */
if (minst->heap->gs_lib_ctx->fstdout2
&& (minst->heap->gs_lib_ctx->fstdout2 != minst->heap->gs_lib_ctx->fstdout)
&& (minst->heap->gs_lib_ctx->fstdout2 != minst->heap->gs_lib_ctx->fstderr)) {
fclose(minst->heap->gs_lib_ctx->fstdout2);
minst->heap->gs_lib_ctx->fstdout2 = (FILE *)NULL;
}
minst->heap->gs_lib_ctx->stdout_is_redirected = 0;
minst->heap->gs_lib_ctx->stdout_to_stderr = 0;
/* remove any temporary files, after ghostscript has closed files */
if (tempnames) {
char *p = tempnames;
while (*p) {
unlink(p);
p += strlen(p) + 1;
}
free(tempnames);
}
gs_lib_finit(exit_status, code, minst->heap);
gs_free_object(minst->heap, minst->lib_path.container.value.refs, "lib_path array");
ialloc_finit(&dmem);
return exit_status;
}
Commit Message:
CWE ID: CWE-416
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: asmlinkage void __sched schedule(void)
{
struct task_struct *prev, *next;
unsigned long *switch_count;
struct rq *rq;
int cpu;
need_resched:
preempt_disable();
cpu = smp_processor_id();
rq = cpu_rq(cpu);
rcu_note_context_switch(cpu);
prev = rq->curr;
release_kernel_lock(prev);
need_resched_nonpreemptible:
schedule_debug(prev);
if (sched_feat(HRTICK))
hrtick_clear(rq);
raw_spin_lock_irq(&rq->lock);
clear_tsk_need_resched(prev);
switch_count = &prev->nivcsw;
if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
if (unlikely(signal_pending_state(prev->state, prev))) {
prev->state = TASK_RUNNING;
} else {
/*
* If a worker is going to sleep, notify and
* ask workqueue whether it wants to wake up a
* task to maintain concurrency. If so, wake
* up the task.
*/
if (prev->flags & PF_WQ_WORKER) {
struct task_struct *to_wakeup;
to_wakeup = wq_worker_sleeping(prev, cpu);
if (to_wakeup)
try_to_wake_up_local(to_wakeup);
}
deactivate_task(rq, prev, DEQUEUE_SLEEP);
}
switch_count = &prev->nvcsw;
}
pre_schedule(rq, prev);
if (unlikely(!rq->nr_running))
idle_balance(cpu, rq);
put_prev_task(rq, prev);
next = pick_next_task(rq);
if (likely(prev != next)) {
sched_info_switch(prev, next);
perf_event_task_sched_out(prev, next);
rq->nr_switches++;
rq->curr = next;
++*switch_count;
context_switch(rq, prev, next); /* unlocks the rq */
/*
* The context switch have flipped the stack from under us
* and restored the local variables which were saved when
* this task called schedule() in the past. prev == current
* is still correct, but it can be moved to another cpu/rq.
*/
cpu = smp_processor_id();
rq = cpu_rq(cpu);
} else
raw_spin_unlock_irq(&rq->lock);
post_schedule(rq);
if (unlikely(reacquire_kernel_lock(prev)))
goto need_resched_nonpreemptible;
preempt_enable_no_resched();
if (need_resched())
goto need_resched;
}
Commit Message: Sched: fix skip_clock_update optimization
idle_balance() drops/retakes rq->lock, leaving the previous task
vulnerable to set_tsk_need_resched(). Clear it after we return
from balancing instead, and in setup_thread_stack() as well, so
no successfully descheduled or never scheduled task has it set.
Need resched confused the skip_clock_update logic, which assumes
that the next call to update_rq_clock() will come nearly immediately
after being set. Make the optimization robust against the waking
a sleeper before it sucessfully deschedules case by checking that
the current task has not been dequeued before setting the flag,
since it is that useless clock update we're trying to save, and
clear unconditionally in schedule() proper instead of conditionally
in put_prev_task().
Signed-off-by: Mike Galbraith <[email protected]>
Reported-by: Bjoern B. Brandenburg <[email protected]>
Tested-by: Yong Zhang <[email protected]>
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: [email protected]
LKML-Reference: <[email protected]>
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: static void tg3_remove_one(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
if (dev) {
struct tg3 *tp = netdev_priv(dev);
release_firmware(tp->fw);
tg3_reset_task_cancel(tp);
if (tg3_flag(tp, USE_PHYLIB)) {
tg3_phy_fini(tp);
tg3_mdio_fini(tp);
}
unregister_netdev(dev);
if (tp->aperegs) {
iounmap(tp->aperegs);
tp->aperegs = NULL;
}
if (tp->regs) {
iounmap(tp->regs);
tp->regs = NULL;
}
free_netdev(dev);
pci_release_regions(pdev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
}
}
Commit Message: tg3: fix length overflow in VPD firmware parsing
Commit 184b89044fb6e2a74611dafa69b1dce0d98612c6 ("tg3: Use VPD fw version
when present") introduced VPD parsing that contained a potential length
overflow.
Limit the hardware's reported firmware string length (max 255 bytes) to
stay inside the driver's firmware string length (32 bytes). On overflow,
truncate the formatted firmware string instead of potentially overwriting
portions of the tg3 struct.
http://cansecwest.com/slides/2013/PrivateCore%20CSW%202013.pdf
Signed-off-by: Kees Cook <[email protected]>
Reported-by: Oded Horovitz <[email protected]>
Reported-by: Brad Spengler <[email protected]>
Cc: [email protected]
Cc: Matt Carlson <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void LocalFileSystem::deleteFileSystem(ExecutionContext* context, FileSystemType type, PassOwnPtr<AsyncFileSystemCallbacks> callbacks)
{
RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context);
ASSERT(context);
ASSERT_WITH_SECURITY_IMPLICATION(context->isDocument());
RefPtr<CallbackWrapper> wrapper = adoptRef(new CallbackWrapper(callbacks));
requestFileSystemAccessInternal(context,
bind(&LocalFileSystem::deleteFileSystemInternal, this, contextPtr, type, wrapper),
bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper));
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ExtensionInstalledBubbleGtk::ShowInternal() {
BrowserWindowGtk* browser_window =
BrowserWindowGtk::GetBrowserWindowForNativeWindow(
browser_->window()->GetNativeHandle());
GtkWidget* reference_widget = NULL;
if (type_ == BROWSER_ACTION) {
BrowserActionsToolbarGtk* toolbar =
browser_window->GetToolbar()->GetBrowserActionsToolbar();
if (toolbar->animating() && animation_wait_retries_-- > 0) {
MessageLoopForUI::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&ExtensionInstalledBubbleGtk::ShowInternal, this),
base::TimeDelta::FromMilliseconds(kAnimationWaitMS));
return;
}
reference_widget = toolbar->GetBrowserActionWidget(extension_);
gtk_container_check_resize(GTK_CONTAINER(
browser_window->GetToolbar()->widget()));
if (reference_widget && !gtk_widget_get_visible(reference_widget)) {
reference_widget = gtk_widget_get_visible(toolbar->chevron()) ?
toolbar->chevron() : NULL;
}
} else if (type_ == PAGE_ACTION) {
LocationBarViewGtk* location_bar_view =
browser_window->GetToolbar()->GetLocationBarView();
location_bar_view->SetPreviewEnabledPageAction(extension_->page_action(),
true); // preview_enabled
reference_widget = location_bar_view->GetPageActionWidget(
extension_->page_action());
gtk_container_check_resize(GTK_CONTAINER(
browser_window->GetToolbar()->widget()));
DCHECK(reference_widget);
} else if (type_ == OMNIBOX_KEYWORD) {
LocationBarViewGtk* location_bar_view =
browser_window->GetToolbar()->GetLocationBarView();
reference_widget = location_bar_view->location_entry_widget();
DCHECK(reference_widget);
}
if (reference_widget == NULL)
reference_widget = browser_window->GetToolbar()->GetAppMenuButton();
GtkThemeService* theme_provider = GtkThemeService::GetFrom(
browser_->profile());
GtkWidget* bubble_content = gtk_hbox_new(FALSE, kHorizontalColumnSpacing);
gtk_container_set_border_width(GTK_CONTAINER(bubble_content), kContentBorder);
if (!icon_.isNull()) {
GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&icon_);
gfx::Size size(icon_.width(), icon_.height());
if (size.width() > kIconSize || size.height() > kIconSize) {
if (size.width() > size.height()) {
size.set_height(size.height() * kIconSize / size.width());
size.set_width(kIconSize);
} else {
size.set_width(size.width() * kIconSize / size.height());
size.set_height(kIconSize);
}
GdkPixbuf* old = pixbuf;
pixbuf = gdk_pixbuf_scale_simple(pixbuf, size.width(), size.height(),
GDK_INTERP_BILINEAR);
g_object_unref(old);
}
GtkWidget* icon_column = gtk_vbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(bubble_content), icon_column, FALSE, FALSE,
kIconPadding);
GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
g_object_unref(pixbuf);
gtk_box_pack_start(GTK_BOX(icon_column), image, FALSE, FALSE, 0);
}
GtkWidget* text_column = gtk_vbox_new(FALSE, kTextColumnVerticalSpacing);
gtk_box_pack_start(GTK_BOX(bubble_content), text_column, FALSE, FALSE, 0);
GtkWidget* heading_label = gtk_label_new(NULL);
string16 extension_name = UTF8ToUTF16(extension_->name());
base::i18n::AdjustStringForLocaleDirection(&extension_name);
std::string heading_text = l10n_util::GetStringFUTF8(
IDS_EXTENSION_INSTALLED_HEADING, extension_name,
l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME));
char* markup = g_markup_printf_escaped("<span size=\"larger\">%s</span>",
heading_text.c_str());
gtk_label_set_markup(GTK_LABEL(heading_label), markup);
g_free(markup);
gtk_util::SetLabelWidth(heading_label, kTextColumnWidth);
gtk_box_pack_start(GTK_BOX(text_column), heading_label, FALSE, FALSE, 0);
if (type_ == PAGE_ACTION) {
GtkWidget* info_label = gtk_label_new(l10n_util::GetStringUTF8(
IDS_EXTENSION_INSTALLED_PAGE_ACTION_INFO).c_str());
gtk_util::SetLabelWidth(info_label, kTextColumnWidth);
gtk_box_pack_start(GTK_BOX(text_column), info_label, FALSE, FALSE, 0);
}
if (type_ == OMNIBOX_KEYWORD) {
GtkWidget* info_label = gtk_label_new(l10n_util::GetStringFUTF8(
IDS_EXTENSION_INSTALLED_OMNIBOX_KEYWORD_INFO,
UTF8ToUTF16(extension_->omnibox_keyword())).c_str());
gtk_util::SetLabelWidth(info_label, kTextColumnWidth);
gtk_box_pack_start(GTK_BOX(text_column), info_label, FALSE, FALSE, 0);
}
GtkWidget* manage_label = gtk_label_new(
l10n_util::GetStringUTF8(IDS_EXTENSION_INSTALLED_MANAGE_INFO).c_str());
gtk_util::SetLabelWidth(manage_label, kTextColumnWidth);
gtk_box_pack_start(GTK_BOX(text_column), manage_label, FALSE, FALSE, 0);
GtkWidget* close_column = gtk_vbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(bubble_content), close_column, FALSE, FALSE, 0);
close_button_.reset(CustomDrawButton::CloseButton(theme_provider));
g_signal_connect(close_button_->widget(), "clicked",
G_CALLBACK(OnButtonClick), this);
gtk_box_pack_start(GTK_BOX(close_column), close_button_->widget(),
FALSE, FALSE, 0);
BubbleGtk::ArrowLocationGtk arrow_location =
!base::i18n::IsRTL() ?
BubbleGtk::ARROW_LOCATION_TOP_RIGHT :
BubbleGtk::ARROW_LOCATION_TOP_LEFT;
gfx::Rect bounds = gtk_util::WidgetBounds(reference_widget);
if (type_ == OMNIBOX_KEYWORD) {
arrow_location =
!base::i18n::IsRTL() ?
BubbleGtk::ARROW_LOCATION_TOP_LEFT :
BubbleGtk::ARROW_LOCATION_TOP_RIGHT;
if (base::i18n::IsRTL())
bounds.Offset(bounds.width(), 0);
bounds.set_width(0);
}
bubble_ = BubbleGtk::Show(reference_widget,
&bounds,
bubble_content,
arrow_location,
true, // match_system_theme
true, // grab_input
theme_provider,
this);
}
Commit Message: [i18n-fixlet] Make strings branding specific in extension code.
IDS_EXTENSIONS_UNINSTALL
IDS_EXTENSIONS_INCOGNITO_WARNING
IDS_EXTENSION_INSTALLED_HEADING
IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug.
IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE
BUG=NONE
TEST=NONE
Review URL: http://codereview.chromium.org/9107061
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: static ssize_t regulator_suspend_standby_uV_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", rdev->constraints->state_standby.uV);
}
Commit Message: regulator: core: Fix regualtor_ena_gpio_free not to access pin after freeing
After freeing pin from regulator_ena_gpio_free, loop can access
the pin. So this patch fixes not to access pin after freeing.
Signed-off-by: Seung-Woo Kim <[email protected]>
Signed-off-by: Mark Brown <[email protected]>
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void uipc_flush_ch_locked(tUIPC_CH_ID ch_id)
{
char buf[UIPC_FLUSH_BUFFER_SIZE];
struct pollfd pfd;
int ret;
pfd.events = POLLIN;
pfd.fd = uipc_main.ch[ch_id].fd;
if (uipc_main.ch[ch_id].fd == UIPC_DISCONNECTED)
{
BTIF_TRACE_EVENT("%s() - fd disconnected. Exiting", __FUNCTION__);
return;
}
while (1)
{
ret = poll(&pfd, 1, 1);
BTIF_TRACE_VERBOSE("%s() - polling fd %d, revents: 0x%x, ret %d",
__FUNCTION__, pfd.fd, pfd.revents, ret);
if (pfd.revents & (POLLERR|POLLHUP))
{
BTIF_TRACE_EVENT("%s() - POLLERR or POLLHUP. Exiting", __FUNCTION__);
return;
}
if (ret <= 0)
{
BTIF_TRACE_EVENT("%s() - error (%d). Exiting", __FUNCTION__, ret);
return;
}
/* read sufficiently large buffer to ensure flush empties socket faster than
it is getting refilled */
read(pfd.fd, &buf, UIPC_FLUSH_BUFFER_SIZE);
}
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DiceResponseHandler::ProcessDiceSignoutHeader(
const std::vector<signin::DiceResponseParams::AccountInfo>& account_infos) {
VLOG(1) << "Start processing Dice signout response";
if (account_consistency_ ==
signin::AccountConsistencyMethod::kDiceFixAuthErrors) {
return;
}
std::string primary_account = signin_manager_->GetAuthenticatedAccountId();
bool primary_account_signed_out = false;
for (const auto& account_info : account_infos) {
std::string signed_out_account =
account_tracker_service_->PickAccountIdForAccount(account_info.gaia_id,
account_info.email);
if (signed_out_account == primary_account) {
primary_account_signed_out = true;
RecordDiceResponseHeader(kSignoutPrimary);
RecordGaiaSignoutMetrics(
(account_info.session_index == 0)
? kChromePrimaryAccountIsFirstGaiaAccount
: kChromePrimaryAccountIsSecondaryGaiaAccount);
if (account_consistency_ == signin::AccountConsistencyMethod::kDice) {
token_service_->UpdateCredentials(
primary_account,
MutableProfileOAuth2TokenServiceDelegate::kInvalidRefreshToken);
} else {
continue;
}
} else {
token_service_->RevokeCredentials(signed_out_account);
}
for (auto it = token_fetchers_.begin(); it != token_fetchers_.end(); ++it) {
std::string token_fetcher_account_id =
account_tracker_service_->PickAccountIdForAccount(
it->get()->gaia_id(), it->get()->email());
if (token_fetcher_account_id == signed_out_account) {
token_fetchers_.erase(it);
break;
}
}
}
if (!primary_account_signed_out) {
RecordDiceResponseHeader(kSignoutSecondary);
RecordGaiaSignoutMetrics(primary_account.empty()
? kNoChromePrimaryAccount
: kChromePrimaryAccountIsNotInGaiaAccounts);
}
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20
Target: 1
Example 2:
Code: int UDPSocketWin::SendToOrWrite(IOBuffer* buf,
int buf_len,
const IPEndPoint* address,
const CompletionCallback& callback) {
DCHECK(CalledOnValidThread());
DCHECK_NE(INVALID_SOCKET, socket_);
DCHECK(write_callback_.is_null());
DCHECK(!callback.is_null()); // Synchronous operation not supported.
DCHECK_GT(buf_len, 0);
DCHECK(!send_to_address_.get());
int nwrite = InternalSendTo(buf, buf_len, address);
if (nwrite != ERR_IO_PENDING)
return nwrite;
if (address)
send_to_address_.reset(new IPEndPoint(*address));
write_callback_ = callback;
return ERR_IO_PENDING;
}
Commit Message: Map posix error codes in bind better, and fix one windows mapping.
r=wtc
BUG=330233
Review URL: https://codereview.chromium.org/101193008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@242224 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Chapters::Display::~Display()
{
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin,
RBinDexClass *c, int MI, int MA, int paddr, int ins_size,
int insns_size, char *class_name, int regsz,
int debug_info_off) {
struct r_bin_t *rbin = binfile->rbin;
const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL);
const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off;
ut64 line_start;
ut64 parameters_size;
ut64 param_type_idx;
ut16 argReg = regsz - ins_size;
ut64 source_file_idx = c->source_file;
RList *params, *debug_positions, *emitted_debug_locals = NULL;
bool keep = true;
if (argReg > regsz) {
return; // this return breaks tests
}
p4 = r_uleb128 (p4, p4_end - p4, &line_start);
p4 = r_uleb128 (p4, p4_end - p4, ¶meters_size);
ut32 address = 0;
ut32 line = line_start;
if (!(debug_positions = r_list_newf ((RListFree)free))) {
return;
}
if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) {
r_list_free (debug_positions);
return;
}
struct dex_debug_local_t debug_locals[regsz];
memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz);
if (!(MA & 0x0008)) {
debug_locals[argReg].name = "this";
debug_locals[argReg].descriptor = r_str_newf("%s;", class_name);
debug_locals[argReg].startAddress = 0;
debug_locals[argReg].signature = NULL;
debug_locals[argReg].live = true;
argReg++;
}
if (!(params = dex_method_signature2 (bin, MI))) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
return;
}
RListIter *iter = r_list_iterator (params);
char *name;
char *type;
int reg;
r_list_foreach (params, iter, type) {
if ((argReg >= regsz) || !type || parameters_size <= 0) {
r_list_free (debug_positions);
r_list_free (params);
r_list_free (emitted_debug_locals);
return;
}
p4 = r_uleb128 (p4, p4_end - p4, ¶m_type_idx); // read uleb128p1
param_type_idx -= 1;
name = getstr (bin, param_type_idx);
reg = argReg;
switch (type[0]) {
case 'D':
case 'J':
argReg += 2;
break;
default:
argReg += 1;
break;
}
if (name) {
debug_locals[reg].name = name;
debug_locals[reg].descriptor = type;
debug_locals[reg].signature = NULL;
debug_locals[reg].startAddress = address;
debug_locals[reg].live = true;
}
--parameters_size;
}
ut8 opcode = *(p4++) & 0xff;
while (keep) {
switch (opcode) {
case 0x0: // DBG_END_SEQUENCE
keep = false;
break;
case 0x1: // DBG_ADVANCE_PC
{
ut64 addr_diff;
p4 = r_uleb128 (p4, p4_end - p4, &addr_diff);
address += addr_diff;
}
break;
case 0x2: // DBG_ADVANCE_LINE
{
st64 line_diff = r_sleb128 (&p4, p4_end);
line += line_diff;
}
break;
case 0x3: // DBG_START_LOCAL
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = NULL;
debug_locals[register_num].live = true;
}
break;
case 0x4: //DBG_START_LOCAL_EXTENDED
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
ut64 sig_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &sig_idx);
sig_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = getstr (bin, sig_idx);
debug_locals[register_num].live = true;
}
break;
case 0x5: // DBG_END_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].live = false;
}
break;
case 0x6: // DBG_RESTART_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
if (!debug_locals[register_num].live) {
debug_locals[register_num].startAddress = address;
debug_locals[register_num].live = true;
}
}
break;
case 0x7: //DBG_SET_PROLOGUE_END
break;
case 0x8: //DBG_SET_PROLOGUE_BEGIN
break;
case 0x9:
{
p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx);
source_file_idx--;
}
break;
default:
{
int adjusted_opcode = opcode - 0x0a;
address += (adjusted_opcode / 15);
line += -4 + (adjusted_opcode % 15);
struct dex_debug_position_t *position =
malloc (sizeof (struct dex_debug_position_t));
if (!position) {
keep = false;
break;
}
position->source_file_idx = source_file_idx;
position->address = address;
position->line = line;
r_list_append (debug_positions, position);
}
break;
}
opcode = *(p4++) & 0xff;
}
if (!binfile->sdb_addrinfo) {
binfile->sdb_addrinfo = sdb_new0 ();
}
char *fileline;
char offset[64];
char *offset_ptr;
RListIter *iter1;
struct dex_debug_position_t *pos;
r_list_foreach (debug_positions, iter1, pos) {
fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line);
offset_ptr = sdb_itoa (pos->address + paddr, offset, 16);
sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0);
sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0);
}
if (!dexdump) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
return;
}
RListIter *iter2;
struct dex_debug_position_t *position;
rbin->cb_printf (" positions :\n");
r_list_foreach (debug_positions, iter2, position) {
rbin->cb_printf (" 0x%04llx line=%llu\n",
position->address, position->line);
}
rbin->cb_printf (" locals :\n");
RListIter *iter3;
struct dex_debug_local_t *local;
r_list_foreach (emitted_debug_locals, iter3, local) {
if (local->signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor,
local->signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor);
}
}
for (reg = 0; reg < regsz; reg++) {
if (debug_locals[reg].live) {
if (debug_locals[reg].signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s "
"%s\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor,
debug_locals[reg].signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s"
"\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor);
}
}
}
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
}
Commit Message: fix #6872
CWE ID: CWE-476
Target: 1
Example 2:
Code: int sc_file_add_acl_entry(sc_file_t *file, unsigned int operation,
unsigned int method, unsigned long key_ref)
{
sc_acl_entry_t *p, *_new;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return SC_ERROR_INVALID_ARGUMENTS;
}
switch (method) {
case SC_AC_NEVER:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 1;
return SC_SUCCESS;
case SC_AC_NONE:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 2;
return SC_SUCCESS;
case SC_AC_UNKNOWN:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 3;
return SC_SUCCESS;
default:
/* NONE and UNKNOWN get zapped when a new AC is added.
* If the ACL is NEVER, additional entries will be
* dropped silently. */
if (file->acl[operation] == (sc_acl_entry_t *) 1)
return SC_SUCCESS;
if (file->acl[operation] == (sc_acl_entry_t *) 2
|| file->acl[operation] == (sc_acl_entry_t *) 3)
file->acl[operation] = NULL;
}
/* If the entry is already present (e.g. due to the mapping)
* of the card's AC with OpenSC's), don't add it again. */
for (p = file->acl[operation]; p != NULL; p = p->next) {
if ((p->method == method) && (p->key_ref == key_ref))
return SC_SUCCESS;
}
_new = malloc(sizeof(sc_acl_entry_t));
if (_new == NULL)
return SC_ERROR_OUT_OF_MEMORY;
_new->method = method;
_new->key_ref = key_ref;
_new->next = NULL;
p = file->acl[operation];
if (p == NULL) {
file->acl[operation] = _new;
return SC_SUCCESS;
}
while (p->next != NULL)
p = p->next;
p->next = _new;
return SC_SUCCESS;
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void file_sb_list_del(struct file *file)
{
if (!list_empty(&file->f_u.fu_list)) {
lg_local_lock_cpu(&files_lglock, file_list_cpu(file));
list_del_init(&file->f_u.fu_list);
lg_local_unlock_cpu(&files_lglock, file_list_cpu(file));
}
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int DecodeTeredo(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq)
{
if (!g_teredo_enabled)
return TM_ECODE_FAILED;
uint8_t *start = pkt;
/* Is this packet to short to contain an IPv6 packet ? */
if (len < IPV6_HEADER_LEN)
return TM_ECODE_FAILED;
/* Teredo encapsulate IPv6 in UDP and can add some custom message
* part before the IPv6 packet. In our case, we just want to get
* over an ORIGIN indication. So we just make one offset if needed. */
if (start[0] == 0x0) {
switch (start[1]) {
/* origin indication: compatible with tunnel */
case 0x0:
/* offset is coherent with len and presence of an IPv6 header */
if (len >= TEREDO_ORIG_INDICATION_LENGTH + IPV6_HEADER_LEN)
start += TEREDO_ORIG_INDICATION_LENGTH;
else
return TM_ECODE_FAILED;
break;
/* authentication: negotiation not real tunnel */
case 0x1:
return TM_ECODE_FAILED;
/* this case is not possible in Teredo: not that protocol */
default:
return TM_ECODE_FAILED;
}
}
/* There is no specific field that we can check to prove that the packet
* is a Teredo packet. We've zapped here all the possible Teredo header
* and we should have an IPv6 packet at the start pointer.
* We then can only do two checks before sending the encapsulated packets
* to decoding:
* - The packet has a protocol version which is IPv6.
* - The IPv6 length of the packet matches what remains in buffer.
*/
if (IP_GET_RAW_VER(start) == 6) {
IPV6Hdr *thdr = (IPV6Hdr *)start;
if (len == IPV6_HEADER_LEN +
IPV6_GET_RAW_PLEN(thdr) + (start - pkt)) {
if (pq != NULL) {
int blen = len - (start - pkt);
/* spawn off tunnel packet */
Packet *tp = PacketTunnelPktSetup(tv, dtv, p, start, blen,
DECODE_TUNNEL_IPV6, pq);
if (tp != NULL) {
PKT_SET_SRC(tp, PKT_SRC_DECODER_TEREDO);
/* add the tp to the packet queue. */
PacketEnqueue(pq,tp);
StatsIncr(tv, dtv->counter_teredo);
return TM_ECODE_OK;
}
}
}
return TM_ECODE_FAILED;
}
return TM_ECODE_FAILED;
}
Commit Message: teredo: be stricter on what to consider valid teredo
Invalid Teredo can lead to valid DNS traffic (or other UDP traffic)
being misdetected as Teredo. This leads to false negatives in the
UDP payload inspection.
Make the teredo code only consider a packet teredo if the encapsulated
data was decoded without any 'invalid' events being set.
Bug #2736.
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void brcmf_configure_wowl(struct brcmf_cfg80211_info *cfg,
struct brcmf_if *ifp,
struct cfg80211_wowlan *wowl)
{
u32 wowl_config;
struct brcmf_wowl_wakeind_le wowl_wakeind;
u32 i;
brcmf_dbg(TRACE, "Suspend, wowl config.\n");
if (!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_ARP_ND))
brcmf_configure_arp_nd_offload(ifp, false);
brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_PM, &cfg->wowl.pre_pmmode);
brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PM, PM_MAX);
wowl_config = 0;
if (wowl->disconnect)
wowl_config = BRCMF_WOWL_DIS | BRCMF_WOWL_BCN | BRCMF_WOWL_RETR;
if (wowl->magic_pkt)
wowl_config |= BRCMF_WOWL_MAGIC;
if ((wowl->patterns) && (wowl->n_patterns)) {
wowl_config |= BRCMF_WOWL_NET;
for (i = 0; i < wowl->n_patterns; i++) {
brcmf_config_wowl_pattern(ifp, "add",
(u8 *)wowl->patterns[i].pattern,
wowl->patterns[i].pattern_len,
(u8 *)wowl->patterns[i].mask,
wowl->patterns[i].pkt_offset);
}
}
if (wowl->nd_config) {
brcmf_cfg80211_sched_scan_start(cfg->wiphy, ifp->ndev,
wowl->nd_config);
wowl_config |= BRCMF_WOWL_PFN_FOUND;
cfg->wowl.nd_data_completed = false;
cfg->wowl.nd_enabled = true;
/* Now reroute the event for PFN to the wowl function. */
brcmf_fweh_unregister(cfg->pub, BRCMF_E_PFN_NET_FOUND);
brcmf_fweh_register(cfg->pub, BRCMF_E_PFN_NET_FOUND,
brcmf_wowl_nd_results);
}
if (wowl->gtk_rekey_failure)
wowl_config |= BRCMF_WOWL_GTK_FAILURE;
if (!test_bit(BRCMF_VIF_STATUS_CONNECTED, &ifp->vif->sme_state))
wowl_config |= BRCMF_WOWL_UNASSOC;
memcpy(&wowl_wakeind, "clear", 6);
brcmf_fil_iovar_data_set(ifp, "wowl_wakeind", &wowl_wakeind,
sizeof(wowl_wakeind));
brcmf_fil_iovar_int_set(ifp, "wowl", wowl_config);
brcmf_fil_iovar_int_set(ifp, "wowl_activate", 1);
brcmf_bus_wowl_config(cfg->pub->bus_if, true);
cfg->wowl.active = true;
}
Commit Message: brcmfmac: fix possible buffer overflow in brcmf_cfg80211_mgmt_tx()
The lower level nl80211 code in cfg80211 ensures that "len" is between
25 and NL80211_ATTR_FRAME (2304). We subtract DOT11_MGMT_HDR_LEN (24) from
"len" so thats's max of 2280. However, the action_frame->data[] buffer is
only BRCMF_FIL_ACTION_FRAME_SIZE (1800) bytes long so this memcpy() can
overflow.
memcpy(action_frame->data, &buf[DOT11_MGMT_HDR_LEN],
le16_to_cpu(action_frame->len));
Cc: [email protected] # 3.9.x
Fixes: 18e2f61db3b70 ("brcmfmac: P2P action frame tx.")
Reported-by: "freenerguo(郭大兴)" <[email protected]>
Signed-off-by: Arend van Spriel <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void red_channel_pipes_add_type(RedChannel *channel, int pipe_item_type)
{
RingItem *link;
RING_FOREACH(link, &channel->clients) {
red_channel_client_pipe_add_type(
SPICE_CONTAINEROF(link, RedChannelClient, channel_link),
pipe_item_type);
}
}
Commit Message:
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond)
{
PurpleXfer *xfer = data;
struct im_connection *ic = purple_ic_by_pa(xfer->account);
struct prpl_xfer_data *px = xfer->ui_data;
PurpleBuddy *buddy;
const char *who;
buddy = purple_find_buddy(xfer->account, xfer->who);
who = buddy ? purple_buddy_get_name(buddy) : xfer->who;
/* TODO(wilmer): After spreading some more const goodness in BitlBee,
remove the evil cast below. */
px->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size);
px->ft->data = px;
px->ft->accept = prpl_xfer_accept;
px->ft->canceled = prpl_xfer_canceled;
px->ft->free = prpl_xfer_free;
px->ft->write_request = prpl_xfer_write_request;
return FALSE;
}
Commit Message: purple: Fix crash on ft requests from unknown contacts
Followup to 701ab81 (included in 3.5) which was a partial fix which only
improved things for non-libpurple file transfers (that is, just jabber)
CWE ID: CWE-476
Target: 1
Example 2:
Code: void enable_kernel_altivec(void)
{
WARN_ON(preemptible());
#ifdef CONFIG_SMP
if (current->thread.regs && (current->thread.regs->msr & MSR_VEC))
giveup_altivec_maybe_transactional(current);
else
giveup_altivec_notask();
#else
giveup_altivec_maybe_transactional(last_task_used_altivec);
#endif /* CONFIG_SMP */
}
Commit Message: powerpc/tm: Fix crash when forking inside a transaction
When we fork/clone we currently don't copy any of the TM state to the new
thread. This results in a TM bad thing (program check) when the new process is
switched in as the kernel does a tmrechkpt with TEXASR FS not set. Also, since
R1 is from userspace, we trigger the bad kernel stack pointer detection. So we
end up with something like this:
Bad kernel stack pointer 0 at c0000000000404fc
cpu 0x2: Vector: 700 (Program Check) at [c00000003ffefd40]
pc: c0000000000404fc: restore_gprs+0xc0/0x148
lr: 0000000000000000
sp: 0
msr: 9000000100201030
current = 0xc000001dd1417c30
paca = 0xc00000000fe00800 softe: 0 irq_happened: 0x01
pid = 0, comm = swapper/2
WARNING: exception is not recoverable, can't continue
The below fixes this by flushing the TM state before we copy the task_struct to
the clone. To do this we go through the tmreclaim patch, which removes the
checkpointed registers from the CPU and transitions the CPU out of TM suspend
mode. Hence we need to call tmrechkpt after to restore the checkpointed state
and the TM mode for the current task.
To make this fail from userspace is simply:
tbegin
li r0, 2
sc
<boom>
Kudos to Adhemerval Zanella Neto for finding this.
Signed-off-by: Michael Neuling <[email protected]>
cc: Adhemerval Zanella Neto <[email protected]>
cc: [email protected]
Signed-off-by: Benjamin Herrenschmidt <[email protected]>
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void jpc_qmfb_split_col(jpc_fix_t *a, int numrows, int stride,
int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE];
jpc_fix_t *buf = splitbuf;
register jpc_fix_t *srcptr;
register jpc_fix_t *dstptr;
register int n;
register int m;
int hstartcol;
/* Get a buffer. */
if (bufsize > QMFB_SPLITBUFSIZE) {
if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide in this case. */
abort();
}
}
if (numrows >= 2) {
hstartcol = (numrows + 1 - parity) >> 1;
m = numrows - hstartcol;
/* Save the samples destined for the highpass channel. */
n = m;
dstptr = buf;
srcptr = &a[(1 - parity) * stride];
while (n-- > 0) {
*dstptr = *srcptr;
++dstptr;
srcptr += stride << 1;
}
/* Copy the appropriate samples into the lowpass channel. */
dstptr = &a[(1 - parity) * stride];
srcptr = &a[(2 - parity) * stride];
n = numrows - m - (!parity);
while (n-- > 0) {
*dstptr = *srcptr;
dstptr += stride;
srcptr += stride << 1;
}
/* Copy the saved samples into the highpass channel. */
dstptr = &a[hstartcol * stride];
srcptr = buf;
n = m;
while (n-- > 0) {
*dstptr = *srcptr;
dstptr += stride;
++srcptr;
}
}
/* If the split buffer was allocated on the heap, free this memory. */
if (buf != splitbuf) {
jas_free(buf);
}
}
Commit Message: Fixed a buffer overrun problem in the QMFB code in the JPC codec
that was caused by a buffer being allocated with a size that was too small
in some cases.
Added a new regression test case.
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: set_value(png_bytep row, size_t rowbytes, png_uint_32 x, unsigned int bit_depth,
png_uint_32 value, png_const_bytep gamma_table, double conv)
{
unsigned int mask = (1U << bit_depth)-1;
x *= bit_depth; /* Maximum x is 4*1024, maximum bit_depth is 16 */
if (value <= mask)
{
png_uint_32 offset = x >> 3;
if (offset < rowbytes && (bit_depth < 16 || offset+1 < rowbytes))
{
row += offset;
switch (bit_depth)
{
case 1:
case 2:
case 4:
/* Don't gamma correct - values get smashed */
{
unsigned int shift = (8 - bit_depth) - (x & 0x7U);
mask <<= shift;
value = (value << shift) & mask;
*row = (png_byte)((*row & ~mask) | value);
}
return;
default:
fprintf(stderr, "makepng: bad bit depth (internal error)\n");
exit(1);
case 16:
value = (unsigned int)floor(65535*pow(value/65535.,conv)+.5);
*row++ = (png_byte)(value >> 8);
*row = (png_byte)value;
return;
case 8:
*row = gamma_table[value];
return;
}
}
else
{
fprintf(stderr, "makepng: row buffer overflow (internal error)\n");
exit(1);
}
}
else
{
fprintf(stderr, "makepng: component overflow (internal error)\n");
exit(1);
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: iperf_set_test_state(struct iperf_test *ipt, signed char state)
{
ipt->state = state;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderFrameHostImpl::OnAssociatedInterfaceRequest(
const std::string& interface_name,
mojo::ScopedInterfaceEndpointHandle handle) {
ContentBrowserClient* browser_client = GetContentClient()->browser();
if (!associated_registry_->TryBindInterface(interface_name, &handle) &&
!browser_client->BindAssociatedInterfaceRequestFromFrame(
this, interface_name, &handle)) {
delegate_->OnAssociatedInterfaceRequest(this, interface_name,
std::move(handle));
}
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#653137}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h,
const void *p, size_t tail, int line)
{
const char *b = (const char *)sst->sst_tab;
const char *e = ((const char *)p) + tail;
(void)&line;
if (e >= b && (size_t)(e - b) <= CDF_SEC_SIZE(h) * sst->sst_len)
return 0;
DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u"
" > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %"
SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b),
CDF_SEC_SIZE(h) * sst->sst_len, CDF_SEC_SIZE(h), sst->sst_len));
errno = EFTYPE;
return -1;
}
Commit Message: Use the proper sector size when checking stream offsets (Francisco Alonso and
Jan Kaluza at RedHat)
CWE ID: CWE-189
Target: 1
Example 2:
Code: CompositorAnimationHost* PaintLayerScrollableArea::GetCompositorAnimationHost()
const {
return layer_->GetLayoutObject().GetFrameView()->GetCompositorAnimationHost();
}
Commit Message: Always call UpdateCompositedScrollOffset, not just for the root layer
Bug: 927560
Change-Id: I1d5522aae4f11dd3f5b8947bb089bac1bf19bdb4
Reviewed-on: https://chromium-review.googlesource.com/c/1452701
Reviewed-by: Chris Harrelson <[email protected]>
Commit-Queue: Mason Freed <[email protected]>
Cr-Commit-Position: refs/heads/master@{#628942}
CWE ID: CWE-79
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int nbd_negotiate_drop_sync(QIOChannel *ioc, size_t size)
{
ssize_t ret;
uint8_t *buffer = g_malloc(MIN(65536, size));
while (size > 0) {
size_t count = MIN(65536, size);
ret = nbd_negotiate_read(ioc, buffer, count);
if (ret < 0) {
g_free(buffer);
return ret;
}
size -= count;
}
g_free(buffer);
return 0;
}
Commit Message:
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void TestFlashMessageLoop::DestroyMessageLoopResourceTask(int32_t unused) {
if (message_loop_) {
delete message_loop_;
message_loop_ = NULL;
} else {
PP_NOTREACHED();
}
}
Commit Message: Fix PPB_Flash_MessageLoop.
This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop.
BUG=569496
Review URL: https://codereview.chromium.org/1559113002
Cr-Commit-Position: refs/heads/master@{#374529}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
int *psignhash_nid, const unsigned char *data)
{
int sign_nid = NID_undef, hash_nid = NID_undef;
if (!phash_nid && !psign_nid && !psignhash_nid)
return;
if (phash_nid || psignhash_nid) {
hash_nid = tls12_find_nid(data[0], tls12_md, OSSL_NELEM(tls12_md));
if (phash_nid)
*phash_nid = hash_nid;
}
if (psign_nid || psignhash_nid) {
sign_nid = tls12_find_nid(data[1], tls12_sig, OSSL_NELEM(tls12_sig));
if (psign_nid)
*psign_nid = sign_nid;
}
if (psignhash_nid) {
if (sign_nid == NID_undef || hash_nid == NID_undef
|| OBJ_find_sigid_by_algs(psignhash_nid, hash_nid, sign_nid) <= 0)
*psignhash_nid = NID_undef;
}
}
Commit Message:
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ext4_lazyinit_thread(void *arg)
{
struct ext4_lazy_init *eli = (struct ext4_lazy_init *)arg;
struct list_head *pos, *n;
struct ext4_li_request *elr;
unsigned long next_wakeup, cur;
BUG_ON(NULL == eli);
cont_thread:
while (true) {
next_wakeup = MAX_JIFFY_OFFSET;
mutex_lock(&eli->li_list_mtx);
if (list_empty(&eli->li_request_list)) {
mutex_unlock(&eli->li_list_mtx);
goto exit_thread;
}
list_for_each_safe(pos, n, &eli->li_request_list) {
elr = list_entry(pos, struct ext4_li_request,
lr_request);
if (time_after_eq(jiffies, elr->lr_next_sched)) {
if (ext4_run_li_request(elr) != 0) {
/* error, remove the lazy_init job */
ext4_remove_li_request(elr);
continue;
}
}
if (time_before(elr->lr_next_sched, next_wakeup))
next_wakeup = elr->lr_next_sched;
}
mutex_unlock(&eli->li_list_mtx);
if (freezing(current))
refrigerator();
cur = jiffies;
if ((time_after_eq(cur, next_wakeup)) ||
(MAX_JIFFY_OFFSET == next_wakeup)) {
cond_resched();
continue;
}
schedule_timeout_interruptible(next_wakeup - cur);
if (kthread_should_stop()) {
ext4_clear_request_list();
goto exit_thread;
}
}
exit_thread:
/*
* It looks like the request list is empty, but we need
* to check it under the li_list_mtx lock, to prevent any
* additions into it, and of course we should lock ext4_li_mtx
* to atomically free the list and ext4_li_info, because at
* this point another ext4 filesystem could be registering
* new one.
*/
mutex_lock(&ext4_li_mtx);
mutex_lock(&eli->li_list_mtx);
if (!list_empty(&eli->li_request_list)) {
mutex_unlock(&eli->li_list_mtx);
mutex_unlock(&ext4_li_mtx);
goto cont_thread;
}
mutex_unlock(&eli->li_list_mtx);
kfree(ext4_li_info);
ext4_li_info = NULL;
mutex_unlock(&ext4_li_mtx);
return 0;
}
Commit Message: ext4: fix undefined behavior in ext4_fill_flex_info()
Commit 503358ae01b70ce6909d19dd01287093f6b6271c ("ext4: avoid divide by
zero when trying to mount a corrupted file system") fixes CVE-2009-4307
by performing a sanity check on s_log_groups_per_flex, since it can be
set to a bogus value by an attacker.
sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
groups_per_flex = 1 << sbi->s_log_groups_per_flex;
if (groups_per_flex < 2) { ... }
This patch fixes two potential issues in the previous commit.
1) The sanity check might only work on architectures like PowerPC.
On x86, 5 bits are used for the shifting amount. That means, given a
large s_log_groups_per_flex value like 36, groups_per_flex = 1 << 36
is essentially 1 << 4 = 16, rather than 0. This will bypass the check,
leaving s_log_groups_per_flex and groups_per_flex inconsistent.
2) The sanity check relies on undefined behavior, i.e., oversized shift.
A standard-confirming C compiler could rewrite the check in unexpected
ways. Consider the following equivalent form, assuming groups_per_flex
is unsigned for simplicity.
groups_per_flex = 1 << sbi->s_log_groups_per_flex;
if (groups_per_flex == 0 || groups_per_flex == 1) {
We compile the code snippet using Clang 3.0 and GCC 4.6. Clang will
completely optimize away the check groups_per_flex == 0, leaving the
patched code as vulnerable as the original. GCC keeps the check, but
there is no guarantee that future versions will do the same.
Signed-off-by: Xi Wang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
Cc: [email protected]
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static enum try_read_result try_read_network(conn *c) {
enum try_read_result gotdata = READ_NO_DATA_RECEIVED;
int res;
assert(c != NULL);
if (c->rcurr != c->rbuf) {
if (c->rbytes != 0) /* otherwise there's nothing to copy */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
}
while (1) {
if (c->rbytes >= c->rsize) {
char *new_rbuf = realloc(c->rbuf, c->rsize * 2);
if (!new_rbuf) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't realloc input buffer\n");
c->rbytes = 0; /* ignore what we read */
out_string(c, "SERVER_ERROR out of memory reading request");
c->write_and_go = conn_closing;
return READ_MEMORY_ERROR;
}
c->rcurr = c->rbuf = new_rbuf;
c->rsize *= 2;
}
int avail = c->rsize - c->rbytes;
res = read(c->sfd, c->rbuf + c->rbytes, avail);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
gotdata = READ_DATA_RECEIVED;
c->rbytes += res;
if (res == avail) {
continue;
} else {
break;
}
}
if (res == 0) {
return READ_ERROR;
}
if (res == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
return READ_ERROR;
}
}
return gotdata;
}
Commit Message: Issue 102: Piping null to the server will crash it
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int ftrace_process_locs(struct module *mod,
unsigned long *start,
unsigned long *end)
{
struct ftrace_page *start_pg;
struct ftrace_page *pg;
struct dyn_ftrace *rec;
unsigned long count;
unsigned long *p;
unsigned long addr;
unsigned long flags = 0; /* Shut up gcc */
int ret = -ENOMEM;
count = end - start;
if (!count)
return 0;
sort(start, count, sizeof(*start),
ftrace_cmp_ips, ftrace_swap_ips);
start_pg = ftrace_allocate_pages(count);
if (!start_pg)
return -ENOMEM;
mutex_lock(&ftrace_lock);
/*
* Core and each module needs their own pages, as
* modules will free them when they are removed.
* Force a new page to be allocated for modules.
*/
if (!mod) {
WARN_ON(ftrace_pages || ftrace_pages_start);
/* First initialization */
ftrace_pages = ftrace_pages_start = start_pg;
} else {
if (!ftrace_pages)
goto out;
if (WARN_ON(ftrace_pages->next)) {
/* Hmm, we have free pages? */
while (ftrace_pages->next)
ftrace_pages = ftrace_pages->next;
}
ftrace_pages->next = start_pg;
}
p = start;
pg = start_pg;
while (p < end) {
addr = ftrace_call_adjust(*p++);
/*
* Some architecture linkers will pad between
* the different mcount_loc sections of different
* object files to satisfy alignments.
* Skip any NULL pointers.
*/
if (!addr)
continue;
if (pg->index == pg->size) {
/* We should have allocated enough */
if (WARN_ON(!pg->next))
break;
pg = pg->next;
}
rec = &pg->records[pg->index++];
rec->ip = addr;
}
/* We should have used all pages */
WARN_ON(pg->next);
/* Assign the last page to ftrace_pages */
ftrace_pages = pg;
/* These new locations need to be initialized */
ftrace_new_pgs = start_pg;
/*
* We only need to disable interrupts on start up
* because we are modifying code that an interrupt
* may execute, and the modification is not atomic.
* But for modules, nothing runs the code we modify
* until we are finished with it, and there's no
* reason to cause large interrupt latencies while we do it.
*/
if (!mod)
local_irq_save(flags);
ftrace_update_code(mod);
if (!mod)
local_irq_restore(flags);
ret = 0;
out:
mutex_unlock(&ftrace_lock);
return ret;
}
Commit Message: tracing: Fix possible NULL pointer dereferences
Currently set_ftrace_pid and set_graph_function files use seq_lseek
for their fops. However seq_open() is called only for FMODE_READ in
the fops->open() so that if an user tries to seek one of those file
when she open it for writing, it sees NULL seq_file and then panic.
It can be easily reproduced with following command:
$ cd /sys/kernel/debug/tracing
$ echo 1234 | sudo tee -a set_ftrace_pid
In this example, GNU coreutils' tee opens the file with fopen(, "a")
and then the fopen() internally calls lseek().
Link: http://lkml.kernel.org/r/[email protected]
Cc: Frederic Weisbecker <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Namhyung Kim <[email protected]>
Cc: [email protected]
Signed-off-by: Namhyung Kim <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline ogg_uint32_t decode_packed_entry_number(codebook *book,
oggpack_buffer *b){
ogg_uint32_t chase=0;
int read=book->dec_maxlength;
long lok = oggpack_look(b,read),i;
while(lok<0 && read>1)
lok = oggpack_look(b, --read);
if(lok<0){
oggpack_adv(b,1); /* force eop */
return -1;
}
/* chase the tree with the bits we got */
switch (book->dec_method)
{
case 0:
{
/* book->dec_nodeb==1, book->dec_leafw==1 */
/* 8/8 - Used */
unsigned char *t=(unsigned char *)book->dec_table;
for(i=0;i<read;i++){
chase=t[chase*2+((lok>>i)&1)];
if(chase&0x80UL)break;
}
chase&=0x7fUL;
break;
}
case 1:
{
/* book->dec_nodeb==1, book->dec_leafw!=1 */
/* 8/16 - Used by infile2 */
unsigned char *t=(unsigned char *)book->dec_table;
for(i=0;i<read;i++){
int bit=(lok>>i)&1;
int next=t[chase+bit];
if(next&0x80){
chase= (next<<8) | t[chase+bit+1+(!bit || t[chase]&0x80)];
break;
}
chase=next;
}
chase&=~0x8000UL;
break;
}
case 2:
{
/* book->dec_nodeb==2, book->dec_leafw==1 */
/* 16/16 - Used */
for(i=0;i<read;i++){
chase=((ogg_uint16_t *)(book->dec_table))[chase*2+((lok>>i)&1)];
if(chase&0x8000UL)break;
}
chase&=~0x8000UL;
break;
}
case 3:
{
/* book->dec_nodeb==2, book->dec_leafw!=1 */
/* 16/32 - Used by infile2 */
ogg_uint16_t *t=(ogg_uint16_t *)book->dec_table;
for(i=0;i<read;i++){
int bit=(lok>>i)&1;
int next=t[chase+bit];
if(next&0x8000){
chase= (next<<16) | t[chase+bit+1+(!bit || t[chase]&0x8000)];
break;
}
chase=next;
}
chase&=~0x80000000UL;
break;
}
case 4:
{
for(i=0;i<read;i++){
chase=((ogg_uint32_t *)(book->dec_table))[chase*2+((lok>>i)&1)];
if(chase&0x80000000UL)break;
}
chase&=~0x80000000UL;
break;
}
}
if(i<read){
oggpack_adv(b,i+1);
return chase;
}
oggpack_adv(b,read+1);
return(-1);
}
Commit Message: Fix out of bounds access in codebook processing
Bug: 62800140
Test: ran poc, CTS
Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37
(cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0)
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void _isdn_setup(struct net_device *dev)
{
isdn_net_local *lp = netdev_priv(dev);
ether_setup(dev);
/* Setup the generic properties */
dev->flags = IFF_NOARP|IFF_POINTOPOINT;
dev->header_ops = NULL;
dev->netdev_ops = &isdn_netdev_ops;
/* for clients with MPPP maybe higher values better */
dev->tx_queue_len = 30;
lp->p_encap = ISDN_NET_ENCAP_RAWIP;
lp->magic = ISDN_NET_MAGIC;
lp->last = lp;
lp->next = lp;
lp->isdn_device = -1;
lp->isdn_channel = -1;
lp->pre_device = -1;
lp->pre_channel = -1;
lp->exclusive = -1;
lp->ppp_slot = -1;
lp->pppbind = -1;
skb_queue_head_init(&lp->super_tx_queue);
lp->l2_proto = ISDN_PROTO_L2_X75I;
lp->l3_proto = ISDN_PROTO_L3_TRANS;
lp->triggercps = 6000;
lp->slavedelay = 10 * HZ;
lp->hupflags = ISDN_INHUP; /* Do hangup even on incoming calls */
lp->onhtime = 10; /* Default hangup-time for saving costs */
lp->dialmax = 1;
/* Hangup before Callback, manual dial */
lp->flags = ISDN_NET_CBHUP | ISDN_NET_DM_MANUAL;
lp->cbdelay = 25; /* Wait 5 secs before Callback */
lp->dialtimeout = -1; /* Infinite Dial-Timeout */
lp->dialwait = 5 * HZ; /* Wait 5 sec. after failed dial */
lp->dialstarted = 0; /* Jiffies of last dial-start */
lp->dialwait_timer = 0; /* Jiffies of earliest next dial-start */
}
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
Target: 1
Example 2:
Code: const AtomicString& HTMLDocument::linkColor() const
{
return bodyAttributeValue(linkAttr);
}
Commit Message: Fix tracking of the id attribute string if it is shared across elements.
The patch to remove AtomicStringImpl:
http://src.chromium.org/viewvc/blink?view=rev&rev=154790
Exposed a lifetime issue with strings for id attributes. We simply need to use
AtomicString.
BUG=290566
Review URL: https://codereview.chromium.org/33793004
git-svn-id: svn://svn.chromium.org/blink/trunk@160250 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void mk_request_free(struct session_request *sr)
{
if (sr->fd_file > 0) {
mk_vhost_close(sr);
}
if (sr->headers.location) {
mk_mem_free(sr->headers.location);
}
if (sr->uri_processed.data != sr->uri.data) {
mk_ptr_free(&sr->uri_processed);
}
if (sr->real_path.data != sr->real_path_static) {
mk_ptr_free(&sr->real_path);
}
}
Commit Message: Request: new request session flag to mark those files opened by FDT
This patch aims to fix a potential DDoS problem that can be caused
in the server quering repetitive non-existent resources.
When serving a static file, the core use Vhost FDT mechanism, but if
it sends a static error page it does a direct open(2). When closing
the resources for the same request it was just calling mk_vhost_close()
which did not clear properly the file descriptor.
This patch adds a new field on the struct session_request called 'fd_is_fdt',
which contains MK_TRUE or MK_FALSE depending of how fd_file was opened.
Thanks to Matthew Daley <[email protected]> for report and troubleshoot this
problem.
Signed-off-by: Eduardo Silva <[email protected]>
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ImageBitmapFactories::ImageBitmapLoader::ImageBitmapLoader(
ImageBitmapFactories& factory,
base::Optional<IntRect> crop_rect,
ScriptState* script_state,
const ImageBitmapOptions* options)
: loader_(
FileReaderLoader::Create(FileReaderLoader::kReadAsArrayBuffer, this)),
factory_(&factory),
resolver_(ScriptPromiseResolver::Create(script_state)),
crop_rect_(crop_rect),
options_(options) {}
Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader
FileReaderLoader stores its client as a raw pointer, so in cases like
ImageBitmapLoader where the FileReaderLoaderClient really is garbage
collected we have to make sure to destroy the FileReaderLoader when
the ExecutionContext that owns it is destroyed.
Bug: 913970
Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861
Reviewed-on: https://chromium-review.googlesource.com/c/1374511
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Marijn Kruisselbrink <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616342}
CWE ID: CWE-416
Target: 1
Example 2:
Code: int HttpProxyClientSocket::DoSendRequestComplete(int result) {
if (result < 0)
return result;
next_state_ = STATE_READ_HEADERS;
return OK;
}
Commit Message: Sanitize headers in Proxy Authentication Required responses
BUG=431504
Review URL: https://codereview.chromium.org/769043003
Cr-Commit-Position: refs/heads/master@{#310014}
CWE ID: CWE-19
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void BackTexture::DestroyNativeGpuMemoryBuffer(bool have_context) {
if (image_) {
ScopedGLErrorSuppressor suppressor(
"BackTexture::DestroyNativeGpuMemoryBuffer",
decoder_->error_state_.get());
image_->ReleaseTexImage(Target());
decoder_->texture_manager()->SetLevelImage(texture_ref_.get(), Target(), 0,
nullptr, Texture::UNBOUND);
image_ = nullptr;
}
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static ssize_t environ_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
char *page;
unsigned long src = *ppos;
int ret = 0;
struct mm_struct *mm = file->private_data;
unsigned long env_start, env_end;
if (!mm)
return 0;
page = (char *)__get_free_page(GFP_TEMPORARY);
if (!page)
return -ENOMEM;
ret = 0;
if (!atomic_inc_not_zero(&mm->mm_users))
goto free;
down_read(&mm->mmap_sem);
env_start = mm->env_start;
env_end = mm->env_end;
up_read(&mm->mmap_sem);
while (count > 0) {
size_t this_len, max_len;
int retval;
if (src >= (env_end - env_start))
break;
this_len = env_end - (env_start + src);
max_len = min_t(size_t, PAGE_SIZE, count);
this_len = min(max_len, this_len);
retval = access_remote_vm(mm, (env_start + src),
page, this_len, 0);
if (retval <= 0) {
ret = retval;
break;
}
if (copy_to_user(buf, page, retval)) {
ret = -EFAULT;
break;
}
ret += retval;
src += retval;
buf += retval;
count -= retval;
}
*ppos = src;
mmput(mm);
free:
free_page((unsigned long) page);
return ret;
}
Commit Message: proc: prevent accessing /proc/<PID>/environ until it's ready
If /proc/<PID>/environ gets read before the envp[] array is fully set up
in create_{aout,elf,elf_fdpic,flat}_tables(), we might end up trying to
read more bytes than are actually written, as env_start will already be
set but env_end will still be zero, making the range calculation
underflow, allowing to read beyond the end of what has been written.
Fix this as it is done for /proc/<PID>/cmdline by testing env_end for
zero. It is, apparently, intentionally set last in create_*_tables().
This bug was found by the PaX size_overflow plugin that detected the
arithmetic underflow of 'this_len = env_end - (env_start + src)' when
env_end is still zero.
The expected consequence is that userland trying to access
/proc/<PID>/environ of a not yet fully set up process may get
inconsistent data as we're in the middle of copying in the environment
variables.
Fixes: https://forums.grsecurity.net/viewtopic.php?f=3&t=4363
Fixes: https://bugzilla.kernel.org/show_bug.cgi?id=116461
Signed-off-by: Mathias Krause <[email protected]>
Cc: Emese Revfy <[email protected]>
Cc: Pax Team <[email protected]>
Cc: Al Viro <[email protected]>
Cc: Mateusz Guzik <[email protected]>
Cc: Alexey Dobriyan <[email protected]>
Cc: Cyrill Gorcunov <[email protected]>
Cc: Jarod Wilson <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: void BackendIO::DoomEntriesBetween(const base::Time initial_time,
const base::Time end_time) {
operation_ = OP_DOOM_BETWEEN;
initial_time_ = initial_time;
end_time_ = end_time;
}
Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem
Thanks to nedwilliamson@ (on gmail) for an alternative perspective
plus a reduction to make fixing this much easier.
Bug: 826626, 518908, 537063, 802886
Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f
Reviewed-on: https://chromium-review.googlesource.com/985052
Reviewed-by: Matt Menke <[email protected]>
Commit-Queue: Maks Orlovich <[email protected]>
Cr-Commit-Position: refs/heads/master@{#547103}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PassRefPtr<RTCSessionDescriptionDescriptor> RTCPeerConnectionHandlerChromium::remoteDescription()
{
if (!m_webHandler)
return 0;
return m_webHandler->remoteDescription();
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PropertyTreeState LayerState() {
DEFINE_STATIC_REF(
TransformPaintPropertyNode, transform,
CreateTransform(TransformPaintPropertyNode::Root(),
TransformationMatrix().Translate(123, 456),
FloatPoint3D(1, 2, 3)));
DEFINE_STATIC_REF(ClipPaintPropertyNode, clip,
CreateClip(ClipPaintPropertyNode::Root(), transform,
FloatRoundedRect(12, 34, 56, 78)));
DEFINE_STATIC_REF(
EffectPaintPropertyNode, effect,
EffectPaintPropertyNode::Create(
EffectPaintPropertyNode::Root(),
EffectPaintPropertyNode::State{
transform, clip, kColorFilterLuminanceToAlpha,
CompositorFilterOperations(), 0.789f, SkBlendMode::kSrcIn}));
return PropertyTreeState(transform, clip, effect);
}
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:
Target: 1
Example 2:
Code: ppp_channel_push(struct channel *pch)
{
struct sk_buff *skb;
struct ppp *ppp;
spin_lock_bh(&pch->downl);
if (pch->chan) {
while (!skb_queue_empty(&pch->file.xq)) {
skb = skb_dequeue(&pch->file.xq);
if (!pch->chan->ops->start_xmit(pch->chan, skb)) {
/* put the packet back and try again later */
skb_queue_head(&pch->file.xq, skb);
break;
}
}
} else {
/* channel got deregistered */
skb_queue_purge(&pch->file.xq);
}
spin_unlock_bh(&pch->downl);
/* see if there is anything from the attached unit to be sent */
if (skb_queue_empty(&pch->file.xq)) {
read_lock_bh(&pch->upl);
ppp = pch->ppp;
if (ppp)
ppp_xmit_process(ppp);
read_unlock_bh(&pch->upl);
}
}
Commit Message: ppp: take reference on channels netns
Let channels hold a reference on their network namespace.
Some channel types, like ppp_async and ppp_synctty, can have their
userspace controller running in a different namespace. Therefore they
can't rely on them to preclude their netns from being removed from
under them.
==================================================================
BUG: KASAN: use-after-free in ppp_unregister_channel+0x372/0x3a0 at
addr ffff880064e217e0
Read of size 8 by task syz-executor/11581
=============================================================================
BUG net_namespace (Not tainted): kasan: bad access detected
-----------------------------------------------------------------------------
Disabling lock debugging due to kernel taint
INFO: Allocated in copy_net_ns+0x6b/0x1a0 age=92569 cpu=3 pid=6906
[< none >] ___slab_alloc+0x4c7/0x500 kernel/mm/slub.c:2440
[< none >] __slab_alloc+0x4c/0x90 kernel/mm/slub.c:2469
[< inline >] slab_alloc_node kernel/mm/slub.c:2532
[< inline >] slab_alloc kernel/mm/slub.c:2574
[< none >] kmem_cache_alloc+0x23a/0x2b0 kernel/mm/slub.c:2579
[< inline >] kmem_cache_zalloc kernel/include/linux/slab.h:597
[< inline >] net_alloc kernel/net/core/net_namespace.c:325
[< none >] copy_net_ns+0x6b/0x1a0 kernel/net/core/net_namespace.c:360
[< none >] create_new_namespaces+0x2f6/0x610 kernel/kernel/nsproxy.c:95
[< none >] copy_namespaces+0x297/0x320 kernel/kernel/nsproxy.c:150
[< none >] copy_process.part.35+0x1bf4/0x5760 kernel/kernel/fork.c:1451
[< inline >] copy_process kernel/kernel/fork.c:1274
[< none >] _do_fork+0x1bc/0xcb0 kernel/kernel/fork.c:1723
[< inline >] SYSC_clone kernel/kernel/fork.c:1832
[< none >] SyS_clone+0x37/0x50 kernel/kernel/fork.c:1826
[< none >] entry_SYSCALL_64_fastpath+0x16/0x7a kernel/arch/x86/entry/entry_64.S:185
INFO: Freed in net_drop_ns+0x67/0x80 age=575 cpu=2 pid=2631
[< none >] __slab_free+0x1fc/0x320 kernel/mm/slub.c:2650
[< inline >] slab_free kernel/mm/slub.c:2805
[< none >] kmem_cache_free+0x2a0/0x330 kernel/mm/slub.c:2814
[< inline >] net_free kernel/net/core/net_namespace.c:341
[< none >] net_drop_ns+0x67/0x80 kernel/net/core/net_namespace.c:348
[< none >] cleanup_net+0x4e5/0x600 kernel/net/core/net_namespace.c:448
[< none >] process_one_work+0x794/0x1440 kernel/kernel/workqueue.c:2036
[< none >] worker_thread+0xdb/0xfc0 kernel/kernel/workqueue.c:2170
[< none >] kthread+0x23f/0x2d0 kernel/drivers/block/aoe/aoecmd.c:1303
[< none >] ret_from_fork+0x3f/0x70 kernel/arch/x86/entry/entry_64.S:468
INFO: Slab 0xffffea0001938800 objects=3 used=0 fp=0xffff880064e20000
flags=0x5fffc0000004080
INFO: Object 0xffff880064e20000 @offset=0 fp=0xffff880064e24200
CPU: 1 PID: 11581 Comm: syz-executor Tainted: G B 4.4.0+
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS
rel-1.8.2-0-g33fbe13 by qemu-project.org 04/01/2014
00000000ffffffff ffff8800662c7790 ffffffff8292049d ffff88003e36a300
ffff880064e20000 ffff880064e20000 ffff8800662c77c0 ffffffff816f2054
ffff88003e36a300 ffffea0001938800 ffff880064e20000 0000000000000000
Call Trace:
[< inline >] __dump_stack kernel/lib/dump_stack.c:15
[<ffffffff8292049d>] dump_stack+0x6f/0xa2 kernel/lib/dump_stack.c:50
[<ffffffff816f2054>] print_trailer+0xf4/0x150 kernel/mm/slub.c:654
[<ffffffff816f875f>] object_err+0x2f/0x40 kernel/mm/slub.c:661
[< inline >] print_address_description kernel/mm/kasan/report.c:138
[<ffffffff816fb0c5>] kasan_report_error+0x215/0x530 kernel/mm/kasan/report.c:236
[< inline >] kasan_report kernel/mm/kasan/report.c:259
[<ffffffff816fb4de>] __asan_report_load8_noabort+0x3e/0x40 kernel/mm/kasan/report.c:280
[< inline >] ? ppp_pernet kernel/include/linux/compiler.h:218
[<ffffffff83ad71b2>] ? ppp_unregister_channel+0x372/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392
[< inline >] ppp_pernet kernel/include/linux/compiler.h:218
[<ffffffff83ad71b2>] ppp_unregister_channel+0x372/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392
[< inline >] ? ppp_pernet kernel/drivers/net/ppp/ppp_generic.c:293
[<ffffffff83ad6f26>] ? ppp_unregister_channel+0xe6/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392
[<ffffffff83ae18f3>] ppp_asynctty_close+0xa3/0x130 kernel/drivers/net/ppp/ppp_async.c:241
[<ffffffff83ae1850>] ? async_lcp_peek+0x5b0/0x5b0 kernel/drivers/net/ppp/ppp_async.c:1000
[<ffffffff82c33239>] tty_ldisc_close.isra.1+0x99/0xe0 kernel/drivers/tty/tty_ldisc.c:478
[<ffffffff82c332c0>] tty_ldisc_kill+0x40/0x170 kernel/drivers/tty/tty_ldisc.c:744
[<ffffffff82c34943>] tty_ldisc_release+0x1b3/0x260 kernel/drivers/tty/tty_ldisc.c:772
[<ffffffff82c1ef21>] tty_release+0xac1/0x13e0 kernel/drivers/tty/tty_io.c:1901
[<ffffffff82c1e460>] ? release_tty+0x320/0x320 kernel/drivers/tty/tty_io.c:1688
[<ffffffff8174de36>] __fput+0x236/0x780 kernel/fs/file_table.c:208
[<ffffffff8174e405>] ____fput+0x15/0x20 kernel/fs/file_table.c:244
[<ffffffff813595ab>] task_work_run+0x16b/0x200 kernel/kernel/task_work.c:115
[< inline >] exit_task_work kernel/include/linux/task_work.h:21
[<ffffffff81307105>] do_exit+0x8b5/0x2c60 kernel/kernel/exit.c:750
[<ffffffff813fdd20>] ? debug_check_no_locks_freed+0x290/0x290 kernel/kernel/locking/lockdep.c:4123
[<ffffffff81306850>] ? mm_update_next_owner+0x6f0/0x6f0 kernel/kernel/exit.c:357
[<ffffffff813215e6>] ? __dequeue_signal+0x136/0x470 kernel/kernel/signal.c:550
[<ffffffff8132067b>] ? recalc_sigpending_tsk+0x13b/0x180 kernel/kernel/signal.c:145
[<ffffffff81309628>] do_group_exit+0x108/0x330 kernel/kernel/exit.c:880
[<ffffffff8132b9d4>] get_signal+0x5e4/0x14f0 kernel/kernel/signal.c:2307
[< inline >] ? kretprobe_table_lock kernel/kernel/kprobes.c:1113
[<ffffffff8151d355>] ? kprobe_flush_task+0xb5/0x450 kernel/kernel/kprobes.c:1158
[<ffffffff8115f7d3>] do_signal+0x83/0x1c90 kernel/arch/x86/kernel/signal.c:712
[<ffffffff8151d2a0>] ? recycle_rp_inst+0x310/0x310 kernel/include/linux/list.h:655
[<ffffffff8115f750>] ? setup_sigcontext+0x780/0x780 kernel/arch/x86/kernel/signal.c:165
[<ffffffff81380864>] ? finish_task_switch+0x424/0x5f0 kernel/kernel/sched/core.c:2692
[< inline >] ? finish_lock_switch kernel/kernel/sched/sched.h:1099
[<ffffffff81380560>] ? finish_task_switch+0x120/0x5f0 kernel/kernel/sched/core.c:2678
[< inline >] ? context_switch kernel/kernel/sched/core.c:2807
[<ffffffff85d794e9>] ? __schedule+0x919/0x1bd0 kernel/kernel/sched/core.c:3283
[<ffffffff81003901>] exit_to_usermode_loop+0xf1/0x1a0 kernel/arch/x86/entry/common.c:247
[< inline >] prepare_exit_to_usermode kernel/arch/x86/entry/common.c:282
[<ffffffff810062ef>] syscall_return_slowpath+0x19f/0x210 kernel/arch/x86/entry/common.c:344
[<ffffffff85d88022>] int_ret_from_sys_call+0x25/0x9f kernel/arch/x86/entry/entry_64.S:281
Memory state around the buggy address:
ffff880064e21680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff880064e21700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
>ffff880064e21780: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff880064e21800: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff880064e21880: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
Fixes: 273ec51dd7ce ("net: ppp_generic - introduce net-namespace functionality v2")
Reported-by: Baozeng Ding <[email protected]>
Signed-off-by: Guillaume Nault <[email protected]>
Reviewed-by: Cyrill Gorcunov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static GURL GetOriginalRequestURL(WebDataSource* ds) {
if (ds->hasUnreachableURL())
return ds->unreachableURL();
std::vector<GURL> redirects;
GetRedirectChain(ds, &redirects);
if (!redirects.empty())
return redirects.at(0);
return ds->originalRequest().url();
}
Commit Message: Add logging to figure out which IPC we're failing to deserialize in RenderFrame.
BUG=369553
[email protected]
Review URL: https://codereview.chromium.org/263833020
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268565 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: finish_process_as_req(struct as_req_state *state, krb5_error_code errcode)
{
krb5_key_data *server_key;
krb5_keyblock *as_encrypting_key = NULL;
krb5_data *response = NULL;
const char *emsg = 0;
int did_log = 0;
loop_respond_fn oldrespond;
void *oldarg;
kdc_realm_t *kdc_active_realm = state->active_realm;
krb5_audit_state *au_state = state->au_state;
assert(state);
oldrespond = state->respond;
oldarg = state->arg;
if (errcode)
goto egress;
au_state->stage = ENCR_REP;
if ((errcode = validate_forwardable(state->request, *state->client,
*state->server, state->kdc_time,
&state->status))) {
errcode += ERROR_TABLE_BASE_krb5;
goto egress;
}
errcode = check_indicators(kdc_context, state->server,
state->auth_indicators);
if (errcode) {
state->status = "HIGHER_AUTHENTICATION_REQUIRED";
goto egress;
}
state->ticket_reply.enc_part2 = &state->enc_tkt_reply;
/*
* Find the server key
*/
if ((errcode = krb5_dbe_find_enctype(kdc_context, state->server,
-1, /* ignore keytype */
-1, /* Ignore salttype */
0, /* Get highest kvno */
&server_key))) {
state->status = "FINDING_SERVER_KEY";
goto egress;
}
/*
* Convert server->key into a real key
* (it may be encrypted in the database)
*
* server_keyblock is later used to generate auth data signatures
*/
if ((errcode = krb5_dbe_decrypt_key_data(kdc_context, NULL,
server_key,
&state->server_keyblock,
NULL))) {
state->status = "DECRYPT_SERVER_KEY";
goto egress;
}
/* Start assembling the response */
state->reply.msg_type = KRB5_AS_REP;
state->reply.client = state->enc_tkt_reply.client; /* post canonization */
state->reply.ticket = &state->ticket_reply;
state->reply_encpart.session = &state->session_key;
if ((errcode = fetch_last_req_info(state->client,
&state->reply_encpart.last_req))) {
state->status = "FETCH_LAST_REQ";
goto egress;
}
state->reply_encpart.nonce = state->request->nonce;
state->reply_encpart.key_exp = get_key_exp(state->client);
state->reply_encpart.flags = state->enc_tkt_reply.flags;
state->reply_encpart.server = state->ticket_reply.server;
/* copy the time fields EXCEPT for authtime; it's location
* is used for ktime
*/
state->reply_encpart.times = state->enc_tkt_reply.times;
state->reply_encpart.times.authtime = state->authtime = state->kdc_time;
state->reply_encpart.caddrs = state->enc_tkt_reply.caddrs;
state->reply_encpart.enc_padata = NULL;
/* Fetch the padata info to be returned (do this before
* authdata to handle possible replacement of reply key
*/
errcode = return_padata(kdc_context, &state->rock, state->req_pkt,
state->request, &state->reply,
&state->client_keyblock, &state->pa_context);
if (errcode) {
state->status = "KDC_RETURN_PADATA";
goto egress;
}
/* If we didn't find a client long-term key and no preauth mechanism
* replaced the reply key, error out now. */
if (state->client_keyblock.enctype == ENCTYPE_NULL) {
state->status = "CANT_FIND_CLIENT_KEY";
errcode = KRB5KDC_ERR_ETYPE_NOSUPP;
goto egress;
}
errcode = handle_authdata(kdc_context,
state->c_flags,
state->client,
state->server,
NULL,
state->local_tgt,
&state->client_keyblock,
&state->server_keyblock,
NULL,
state->req_pkt,
state->request,
NULL, /* for_user_princ */
NULL, /* enc_tkt_request */
state->auth_indicators,
&state->enc_tkt_reply);
if (errcode) {
krb5_klog_syslog(LOG_INFO, _("AS_REQ : handle_authdata (%d)"),
errcode);
state->status = "HANDLE_AUTHDATA";
goto egress;
}
errcode = krb5_encrypt_tkt_part(kdc_context, &state->server_keyblock,
&state->ticket_reply);
if (errcode) {
state->status = "ENCRYPT_TICKET";
goto egress;
}
errcode = kau_make_tkt_id(kdc_context, &state->ticket_reply,
&au_state->tkt_out_id);
if (errcode) {
state->status = "GENERATE_TICKET_ID";
goto egress;
}
state->ticket_reply.enc_part.kvno = server_key->key_data_kvno;
errcode = kdc_fast_response_handle_padata(state->rstate,
state->request,
&state->reply,
state->client_keyblock.enctype);
if (errcode) {
state->status = "MAKE_FAST_RESPONSE";
goto egress;
}
/* now encode/encrypt the response */
state->reply.enc_part.enctype = state->client_keyblock.enctype;
errcode = kdc_fast_handle_reply_key(state->rstate, &state->client_keyblock,
&as_encrypting_key);
if (errcode) {
state->status = "MAKE_FAST_REPLY_KEY";
goto egress;
}
errcode = return_enc_padata(kdc_context, state->req_pkt, state->request,
as_encrypting_key, state->server,
&state->reply_encpart, FALSE);
if (errcode) {
state->status = "KDC_RETURN_ENC_PADATA";
goto egress;
}
if (kdc_fast_hide_client(state->rstate))
state->reply.client = (krb5_principal)krb5_anonymous_principal();
errcode = krb5_encode_kdc_rep(kdc_context, KRB5_AS_REP,
&state->reply_encpart, 0,
as_encrypting_key,
&state->reply, &response);
if (state->client_key != NULL)
state->reply.enc_part.kvno = state->client_key->key_data_kvno;
if (errcode) {
state->status = "ENCODE_KDC_REP";
goto egress;
}
/* these parts are left on as a courtesy from krb5_encode_kdc_rep so we
can use them in raw form if needed. But, we don't... */
memset(state->reply.enc_part.ciphertext.data, 0,
state->reply.enc_part.ciphertext.length);
free(state->reply.enc_part.ciphertext.data);
log_as_req(kdc_context, state->local_addr, state->remote_addr,
state->request, &state->reply, state->client, state->cname,
state->server, state->sname, state->authtime, 0, 0, 0);
did_log = 1;
egress:
if (errcode != 0)
assert (state->status != 0);
au_state->status = state->status;
au_state->reply = &state->reply;
kau_as_req(kdc_context,
(errcode || state->preauth_err) ? FALSE : TRUE, au_state);
kau_free_kdc_req(au_state);
free_padata_context(kdc_context, state->pa_context);
if (as_encrypting_key)
krb5_free_keyblock(kdc_context, as_encrypting_key);
if (errcode)
emsg = krb5_get_error_message(kdc_context, errcode);
if (state->status) {
log_as_req(kdc_context, state->local_addr, state->remote_addr,
state->request, &state->reply, state->client,
state->cname, state->server, state->sname, state->authtime,
state->status, errcode, emsg);
did_log = 1;
}
if (errcode) {
if (state->status == 0) {
state->status = emsg;
}
if (errcode != KRB5KDC_ERR_DISCARD) {
errcode -= ERROR_TABLE_BASE_krb5;
if (errcode < 0 || errcode > KRB_ERR_MAX)
errcode = KRB_ERR_GENERIC;
errcode = prepare_error_as(state->rstate, state->request,
state->local_tgt, errcode,
state->e_data, state->typed_e_data,
((state->client != NULL) ?
state->client->princ : NULL),
&response, state->status);
state->status = 0;
}
}
if (emsg)
krb5_free_error_message(kdc_context, emsg);
if (state->enc_tkt_reply.authorization_data != NULL)
krb5_free_authdata(kdc_context,
state->enc_tkt_reply.authorization_data);
if (state->server_keyblock.contents != NULL)
krb5_free_keyblock_contents(kdc_context, &state->server_keyblock);
if (state->client_keyblock.contents != NULL)
krb5_free_keyblock_contents(kdc_context, &state->client_keyblock);
if (state->reply.padata != NULL)
krb5_free_pa_data(kdc_context, state->reply.padata);
if (state->reply_encpart.enc_padata)
krb5_free_pa_data(kdc_context, state->reply_encpart.enc_padata);
if (state->cname != NULL)
free(state->cname);
if (state->sname != NULL)
free(state->sname);
krb5_db_free_principal(kdc_context, state->client);
krb5_db_free_principal(kdc_context, state->server);
krb5_db_free_principal(kdc_context, state->local_tgt_storage);
if (state->session_key.contents != NULL)
krb5_free_keyblock_contents(kdc_context, &state->session_key);
if (state->ticket_reply.enc_part.ciphertext.data != NULL) {
memset(state->ticket_reply.enc_part.ciphertext.data , 0,
state->ticket_reply.enc_part.ciphertext.length);
free(state->ticket_reply.enc_part.ciphertext.data);
}
krb5_free_pa_data(kdc_context, state->e_data);
krb5_free_data(kdc_context, state->inner_body);
kdc_free_rstate(state->rstate);
krb5_free_kdc_req(kdc_context, state->request);
k5_free_data_ptr_list(state->auth_indicators);
assert(did_log != 0);
free(state);
(*oldrespond)(oldarg, errcode, response);
}
Commit Message: Prevent KDC unset status assertion failures
Assign status values if S4U2Self padata fails to decode, if an
S4U2Proxy request uses invalid KDC options, or if an S4U2Proxy request
uses an evidence ticket which does not match the canonicalized request
server principal name. Reported by Samuel Cabrero.
If a status value is not assigned during KDC processing, default to
"UNKNOWN_REASON" rather than failing an assertion. This change will
prevent future denial of service bugs due to similar mistakes, and
will allow us to omit assigning status values for unlikely errors such
as small memory allocation failures.
CVE-2017-11368:
In MIT krb5 1.7 and later, an authenticated attacker can cause an
assertion failure in krb5kdc by sending an invalid S4U2Self or
S4U2Proxy request.
CVSSv3 Vector: AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H/E:H/RL:O/RC:C
ticket: 8599 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-617
Target: 1
Example 2:
Code: static void netlink_destroy_callback(struct netlink_callback *cb)
{
kfree_skb(cb->skb);
kfree(cb);
}
Commit Message: af_netlink: force credentials passing [CVE-2012-3520]
Pablo Neira Ayuso discovered that avahi and
potentially NetworkManager accept spoofed Netlink messages because of a
kernel bug. The kernel passes all-zero SCM_CREDENTIALS ancillary data
to the receiver if the sender did not provide such data, instead of not
including any such data at all or including the correct data from the
peer (as it is the case with AF_UNIX).
This bug was introduced in commit 16e572626961
(af_unix: dont send SCM_CREDENTIALS by default)
This patch forces passing credentials for netlink, as
before the regression.
Another fix would be to not add SCM_CREDENTIALS in
netlink messages if not provided by the sender, but it
might break some programs.
With help from Florian Weimer & Petr Matousek
This issue is designated as CVE-2012-3520
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Petr Matousek <[email protected]>
Cc: Florian Weimer <[email protected]>
Cc: Pablo Neira Ayuso <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-287
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static Image *ReadLABELImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
geometry[MaxTextExtent],
*property;
const char
*label;
DrawInfo
*draw_info;
Image
*image;
MagickBooleanType
status;
TypeMetric
metrics;
size_t
height,
width;
/*
Initialize Image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
(void) ResetImagePage(image,"0x0+0+0");
property=InterpretImageProperties(image_info,image,image_info->filename);
(void) SetImageProperty(image,"label",property);
property=DestroyString(property);
label=GetImageProperty(image,"label");
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
draw_info->text=ConstantString(label);
metrics.width=0;
metrics.ascent=0.0;
status=GetMultilineTypeMetrics(image,draw_info,&metrics);
if ((image->columns == 0) && (image->rows == 0))
{
image->columns=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
image->rows=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
}
else
if ((strlen(label) > 0) &&
(((image->columns == 0) || (image->rows == 0)) ||
(fabs(image_info->pointsize) < MagickEpsilon)))
{
double
high,
low;
/*
Auto fit text into bounding box.
*/
for ( ; ; draw_info->pointsize*=2.0)
{
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
-metrics.bounds.x1,metrics.ascent);
if (draw_info->gravity == UndefinedGravity)
(void) CloneString(&draw_info->geometry,geometry);
(void) GetMultilineTypeMetrics(image,draw_info,&metrics);
width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
if ((image->columns != 0) && (image->rows != 0))
{
if ((width >= image->columns) && (height >= image->rows))
break;
}
else
if (((image->columns != 0) && (width >= image->columns)) ||
((image->rows != 0) && (height >= image->rows)))
break;
}
high=draw_info->pointsize;
for (low=1.0; (high-low) > 0.5; )
{
draw_info->pointsize=(low+high)/2.0;
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
-metrics.bounds.x1,metrics.ascent);
if (draw_info->gravity == UndefinedGravity)
(void) CloneString(&draw_info->geometry,geometry);
(void) GetMultilineTypeMetrics(image,draw_info,&metrics);
width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
if ((image->columns != 0) && (image->rows != 0))
{
if ((width < image->columns) && (height < image->rows))
low=draw_info->pointsize+0.5;
else
high=draw_info->pointsize-0.5;
}
else
if (((image->columns != 0) && (width < image->columns)) ||
((image->rows != 0) && (height < image->rows)))
low=draw_info->pointsize+0.5;
else
high=draw_info->pointsize-0.5;
}
draw_info->pointsize=(low+high)/2.0-0.5;
}
status=GetMultilineTypeMetrics(image,draw_info,&metrics);
if (status == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (image->columns == 0)
image->columns=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
if (image->columns == 0)
image->columns=(size_t) floor(draw_info->pointsize+draw_info->stroke_width+
0.5);
if (image->rows == 0)
image->rows=(size_t) floor(metrics.ascent-metrics.descent+
draw_info->stroke_width+0.5);
if (image->rows == 0)
image->rows=(size_t) floor(draw_info->pointsize+draw_info->stroke_width+
0.5);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (SetImageBackgroundColor(image) == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Draw label.
*/
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
draw_info->direction == RightToLeftDirection ? image->columns-
metrics.bounds.x2 : 0.0,draw_info->gravity == UndefinedGravity ?
metrics.ascent : 0.0);
draw_info->geometry=AcquireString(geometry);
status=AnnotateImage(image,draw_info);
if (image_info->pointsize == 0.0)
{
char
pointsize[MaxTextExtent];
(void) FormatLocaleString(pointsize,MaxTextExtent,"%.20g",
draw_info->pointsize);
(void) SetImageProperty(image,"label:pointsize",pointsize);
}
draw_info=DestroyDrawInfo(draw_info);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
return(GetFirstImageInList(image));
}
Commit Message: Fix a small memory leak
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,
ext4_lblk_t iblock, unsigned int max_blocks,
struct ext4_ext_path *path, int flags,
unsigned int allocated, struct buffer_head *bh_result,
ext4_fsblk_t newblock)
{
int ret = 0;
int err = 0;
ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical"
"block %llu, max_blocks %u, flags %d, allocated %u",
inode->i_ino, (unsigned long long)iblock, max_blocks,
flags, allocated);
ext4_ext_show_leaf(inode, path);
/* get_block() before submit the IO, split the extent */
if (flags == EXT4_GET_BLOCKS_PRE_IO) {
ret = ext4_split_unwritten_extents(handle,
inode, path, iblock,
max_blocks, flags);
/*
* Flag the inode(non aio case) or end_io struct (aio case)
* that this IO needs to convertion to written when IO is
* completed
*/
if (io)
io->flag = EXT4_IO_UNWRITTEN;
else
ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
goto out;
}
/* IO end_io complete, convert the filled extent to written */
if (flags == EXT4_GET_BLOCKS_CONVERT) {
ret = ext4_convert_unwritten_extents_endio(handle, inode,
path);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
goto out2;
}
/* buffered IO case */
/*
* repeat fallocate creation request
* we already have an unwritten extent
*/
if (flags & EXT4_GET_BLOCKS_UNINIT_EXT)
goto map_out;
/* buffered READ or buffered write_begin() lookup */
if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
/*
* We have blocks reserved already. We
* return allocated blocks so that delalloc
* won't do block reservation for us. But
* the buffer head will be unmapped so that
* a read from the block returns 0s.
*/
set_buffer_unwritten(bh_result);
goto out1;
}
/* buffered write, writepage time, convert*/
ret = ext4_ext_convert_to_initialized(handle, inode,
path, iblock,
max_blocks);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
out:
if (ret <= 0) {
err = ret;
goto out2;
} else
allocated = ret;
set_buffer_new(bh_result);
/*
* if we allocated more blocks than requested
* we need to make sure we unmap the extra block
* allocated. The actual needed block will get
* unmapped later when we find the buffer_head marked
* new.
*/
if (allocated > max_blocks) {
unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
newblock + max_blocks,
allocated - max_blocks);
allocated = max_blocks;
}
/*
* If we have done fallocate with the offset that is already
* delayed allocated, we would have block reservation
* and quota reservation done in the delayed write path.
* But fallocate would have already updated quota and block
* count for this offset. So cancel these reservation
*/
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
ext4_da_update_reserve_space(inode, allocated, 0);
map_out:
set_buffer_mapped(bh_result);
out1:
if (allocated > max_blocks)
allocated = max_blocks;
ext4_ext_show_leaf(inode, path);
bh_result->b_bdev = inode->i_sb->s_bdev;
bh_result->b_blocknr = newblock;
out2:
if (path) {
ext4_ext_drop_refs(path);
kfree(path);
}
return err ? err : allocated;
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: static bool btif_fetch_property(const char *key, bt_bdaddr_t *addr) {
char val[PROPERTY_VALUE_MAX] = {0};
if (property_get(key, val, NULL)) {
if (string_to_bdaddr(val, addr)) {
BTIF_TRACE_DEBUG("%s: Got BDA %s", __func__, val);
return TRUE;
}
BTIF_TRACE_DEBUG("%s: System Property did not contain valid bdaddr", __func__);
}
return FALSE;
}
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
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)
{
const cdf_section_header_t *shp;
cdf_section_header_t sh;
const uint8_t *p, *q, *e;
int16_t s16;
int32_t s32;
uint32_t u32;
int64_t s64;
uint64_t u64;
cdf_timestamp_t tp;
size_t i, o, o4, nelements, j;
cdf_property_info_t *inp;
if (offs > UINT32_MAX / 4) {
errno = EFTYPE;
goto out;
}
shp = CAST(const cdf_section_header_t *, (const void *)
((const char *)sst->sst_tab + offs));
if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)
goto out;
sh.sh_len = CDF_TOLE4(shp->sh_len);
#define CDF_SHLEN_LIMIT (UINT32_MAX / 8)
if (sh.sh_len > CDF_SHLEN_LIMIT) {
errno = EFTYPE;
goto out;
}
sh.sh_properties = CDF_TOLE4(shp->sh_properties);
#define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp)))
if (sh.sh_properties > CDF_PROP_LIMIT)
goto out;
DPRINTF(("section len: %u properties %u\n", sh.sh_len,
sh.sh_properties));
if (*maxcount) {
if (*maxcount > CDF_PROP_LIMIT)
goto out;
*maxcount += sh.sh_properties;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
} else {
*maxcount = sh.sh_properties;
inp = CAST(cdf_property_info_t *,
malloc(*maxcount * sizeof(*inp)));
}
if (inp == NULL)
goto out;
*info = inp;
inp += *count;
*count += sh.sh_properties;
p = CAST(const uint8_t *, (const void *)
((const char *)(const void *)sst->sst_tab +
offs + sizeof(sh)));
e = CAST(const uint8_t *, (const void *)
(((const char *)(const void *)shp) + sh.sh_len));
if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)
goto out;
for (i = 0; i < sh.sh_properties; i++) {
q = (const uint8_t *)(const void *)
((const char *)(const void *)p +
CDF_GETUINT32(p, (i << 1) + 1)) - 2 * sizeof(uint32_t);
if (q > e) {
DPRINTF(("Ran of the end %p > %p\n", q, e));
goto out;
}
inp[i].pi_id = CDF_GETUINT32(p, i << 1);
inp[i].pi_type = CDF_GETUINT32(q, 0);
DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n", i,
inp[i].pi_id, inp[i].pi_type, q - p,
CDF_GETUINT32(p, (i << 1) + 1)));
if (inp[i].pi_type & CDF_VECTOR) {
nelements = CDF_GETUINT32(q, 1);
o = 2;
} else {
nelements = 1;
o = 1;
}
o4 = o * sizeof(uint32_t);
if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))
goto unknown;
switch (inp[i].pi_type & CDF_TYPEMASK) {
case CDF_NULL:
case CDF_EMPTY:
break;
case CDF_SIGNED16:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s16, &q[o4], sizeof(s16));
inp[i].pi_s16 = CDF_TOLE2(s16);
break;
case CDF_SIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s32, &q[o4], sizeof(s32));
inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32);
break;
case CDF_BOOL:
case CDF_UNSIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
inp[i].pi_u32 = CDF_TOLE4(u32);
break;
case CDF_SIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s64, &q[o4], sizeof(s64));
inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64);
break;
case CDF_UNSIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64);
break;
case CDF_FLOAT:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
u32 = CDF_TOLE4(u32);
memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f));
break;
case CDF_DOUBLE:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
u64 = CDF_TOLE8((uint64_t)u64);
memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d));
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
if (nelements > 1) {
size_t nelem = inp - *info;
if (*maxcount > CDF_PROP_LIMIT
|| nelements > CDF_PROP_LIMIT)
goto out;
*maxcount += nelements;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
if (inp == NULL)
goto out;
*info = inp;
inp = *info + nelem;
}
DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n",
nelements));
for (j = 0; j < nelements; j++, i++) {
uint32_t l = CDF_GETUINT32(q, o);
inp[i].pi_str.s_len = l;
inp[i].pi_str.s_buf = (const char *)
(const void *)(&q[o4 + sizeof(l)]);
DPRINTF(("l = %d, r = %" SIZE_T_FORMAT
"u, s = %s\n", l,
CDF_ROUND(l, sizeof(l)),
inp[i].pi_str.s_buf));
if (l & 1)
l++;
o += l >> 1;
if (q + o >= e)
goto out;
o4 = o * sizeof(uint32_t);
}
i--;
break;
case CDF_FILETIME:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&tp, &q[o4], sizeof(tp));
inp[i].pi_tp = CDF_TOLE8((uint64_t)tp);
break;
case CDF_CLIPBOARD:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
break;
default:
unknown:
DPRINTF(("Don't know how to deal with %x\n",
inp[i].pi_type));
break;
}
}
return 0;
out:
free(*info);
return -1;
}
Commit Message: Fix bounds checks again.
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: unsigned int arpt_do_table(struct sk_buff *skb,
const struct nf_hook_state *state,
struct xt_table *table)
{
unsigned int hook = state->hook;
static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long))));
unsigned int verdict = NF_DROP;
const struct arphdr *arp;
struct arpt_entry *e, **jumpstack;
const char *indev, *outdev;
const void *table_base;
unsigned int cpu, stackidx = 0;
const struct xt_table_info *private;
struct xt_action_param acpar;
unsigned int addend;
if (!pskb_may_pull(skb, arp_hdr_len(skb->dev)))
return NF_DROP;
indev = state->in ? state->in->name : nulldevname;
outdev = state->out ? state->out->name : nulldevname;
local_bh_disable();
addend = xt_write_recseq_begin();
private = READ_ONCE(table->private); /* Address dependency. */
cpu = smp_processor_id();
table_base = private->entries;
jumpstack = (struct arpt_entry **)private->jumpstack[cpu];
/* No TEE support for arptables, so no need to switch to alternate
* stack. All targets that reenter must return absolute verdicts.
*/
e = get_entry(table_base, private->hook_entry[hook]);
acpar.state = state;
acpar.hotdrop = false;
arp = arp_hdr(skb);
do {
const struct xt_entry_target *t;
struct xt_counters *counter;
if (!arp_packet_match(arp, skb->dev, indev, outdev, &e->arp)) {
e = arpt_next_entry(e);
continue;
}
counter = xt_get_this_cpu_counter(&e->counters);
ADD_COUNTER(*counter, arp_hdr_len(skb->dev), 1);
t = arpt_get_target_c(e);
/* Standard target? */
if (!t->u.kernel.target->target) {
int v;
v = ((struct xt_standard_target *)t)->verdict;
if (v < 0) {
/* Pop from stack? */
if (v != XT_RETURN) {
verdict = (unsigned int)(-v) - 1;
break;
}
if (stackidx == 0) {
e = get_entry(table_base,
private->underflow[hook]);
} else {
e = jumpstack[--stackidx];
e = arpt_next_entry(e);
}
continue;
}
if (table_base + v
!= arpt_next_entry(e)) {
jumpstack[stackidx++] = e;
}
e = get_entry(table_base, v);
continue;
}
acpar.target = t->u.kernel.target;
acpar.targinfo = t->data;
verdict = t->u.kernel.target->target(skb, &acpar);
if (verdict == XT_CONTINUE) {
/* Target might have changed stuff. */
arp = arp_hdr(skb);
e = arpt_next_entry(e);
} else {
/* Verdict */
break;
}
} while (!acpar.hotdrop);
xt_write_recseq_end(addend);
local_bh_enable();
if (acpar.hotdrop)
return NF_DROP;
else
return verdict;
}
Commit Message: netfilter: add back stackpointer size checks
The rationale for removing the check is only correct for rulesets
generated by ip(6)tables.
In iptables, a jump can only occur to a user-defined chain, i.e.
because we size the stack based on number of user-defined chains we
cannot exceed stack size.
However, the underlying binary format has no such restriction,
and the validation step only ensures that the jump target is a
valid rule start point.
IOW, its possible to build a rule blob that has no user-defined
chains but does contain a jump.
If this happens, no jump stack gets allocated and crash occurs
because no jumpstack was allocated.
Fixes: 7814b6ec6d0d6 ("netfilter: xtables: don't save/restore jumpstack offset")
Reported-by: [email protected]
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-476
Target: 1
Example 2:
Code: std::string GetResponseHeaderLines(const net::HttpResponseHeaders& headers) {
std::string raw_headers = headers.raw_headers();
const char* null_separated_headers = raw_headers.c_str();
const char* header_line = null_separated_headers;
std::string cr_separated_headers;
while (header_line[0] != 0) {
cr_separated_headers += header_line;
cr_separated_headers += "\n";
header_line += strlen(header_line) + 1;
}
return cr_separated_headers;
}
Commit Message: net: don't process truncated headers on HTTPS connections.
This change causes us to not process any headers unless they are correctly
terminated with a \r\n\r\n sequence.
BUG=244260
Review URL: https://chromiumcodereview.appspot.com/15688012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@202927 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int unix_stream_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size,
int flags)
{
struct sock_iocb *siocb = kiocb_to_siocb(iocb);
struct scm_cookie tmp_scm;
struct sock *sk = sock->sk;
struct unix_sock *u = unix_sk(sk);
struct sockaddr_un *sunaddr = msg->msg_name;
int copied = 0;
int check_creds = 0;
int target;
int err = 0;
long timeo;
int skip;
err = -EINVAL;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
err = -EOPNOTSUPP;
if (flags&MSG_OOB)
goto out;
target = sock_rcvlowat(sk, flags&MSG_WAITALL, size);
timeo = sock_rcvtimeo(sk, flags&MSG_DONTWAIT);
msg->msg_namelen = 0;
/* Lock the socket to prevent queue disordering
* while sleeps in memcpy_tomsg
*/
if (!siocb->scm) {
siocb->scm = &tmp_scm;
memset(&tmp_scm, 0, sizeof(tmp_scm));
}
err = mutex_lock_interruptible(&u->readlock);
if (err) {
err = sock_intr_errno(timeo);
goto out;
}
do {
int chunk;
struct sk_buff *skb, *last;
unix_state_lock(sk);
last = skb = skb_peek(&sk->sk_receive_queue);
again:
if (skb == NULL) {
unix_sk(sk)->recursion_level = 0;
if (copied >= target)
goto unlock;
/*
* POSIX 1003.1g mandates this order.
*/
err = sock_error(sk);
if (err)
goto unlock;
if (sk->sk_shutdown & RCV_SHUTDOWN)
goto unlock;
unix_state_unlock(sk);
err = -EAGAIN;
if (!timeo)
break;
mutex_unlock(&u->readlock);
timeo = unix_stream_data_wait(sk, timeo, last);
if (signal_pending(current)
|| mutex_lock_interruptible(&u->readlock)) {
err = sock_intr_errno(timeo);
goto out;
}
continue;
unlock:
unix_state_unlock(sk);
break;
}
skip = sk_peek_offset(sk, flags);
while (skip >= unix_skb_len(skb)) {
skip -= unix_skb_len(skb);
last = skb;
skb = skb_peek_next(skb, &sk->sk_receive_queue);
if (!skb)
goto again;
}
unix_state_unlock(sk);
if (check_creds) {
/* Never glue messages from different writers */
if ((UNIXCB(skb).pid != siocb->scm->pid) ||
!uid_eq(UNIXCB(skb).uid, siocb->scm->creds.uid) ||
!gid_eq(UNIXCB(skb).gid, siocb->scm->creds.gid))
break;
} else if (test_bit(SOCK_PASSCRED, &sock->flags)) {
/* Copy credentials */
scm_set_cred(siocb->scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid);
check_creds = 1;
}
/* Copy address just once */
if (sunaddr) {
unix_copy_addr(msg, skb->sk);
sunaddr = NULL;
}
chunk = min_t(unsigned int, unix_skb_len(skb) - skip, size);
if (skb_copy_datagram_iovec(skb, UNIXCB(skb).consumed + skip,
msg->msg_iov, chunk)) {
if (copied == 0)
copied = -EFAULT;
break;
}
copied += chunk;
size -= chunk;
/* Mark read part of skb as used */
if (!(flags & MSG_PEEK)) {
UNIXCB(skb).consumed += chunk;
sk_peek_offset_bwd(sk, chunk);
if (UNIXCB(skb).fp)
unix_detach_fds(siocb->scm, skb);
if (unix_skb_len(skb))
break;
skb_unlink(skb, &sk->sk_receive_queue);
consume_skb(skb);
if (siocb->scm->fp)
break;
} else {
/* It is questionable, see note in unix_dgram_recvmsg.
*/
if (UNIXCB(skb).fp)
siocb->scm->fp = scm_fp_dup(UNIXCB(skb).fp);
sk_peek_offset_fwd(sk, chunk);
break;
}
} while (size);
mutex_unlock(&u->readlock);
scm_recv(sock, msg, siocb->scm, flags);
out:
return copied ? : err;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int br_multicast_add_group(struct net_bridge *br,
struct net_bridge_port *port,
struct br_ip *group)
{
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
unsigned long now = jiffies;
int err;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) ||
(port && port->state == BR_STATE_DISABLED))
goto out;
mp = br_multicast_new_group(br, port, group);
err = PTR_ERR(mp);
if (IS_ERR(mp))
goto err;
if (!port) {
hlist_add_head(&mp->mglist, &br->mglist);
mod_timer(&mp->timer, now + br->multicast_membership_interval);
goto out;
}
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (p->port == port)
goto found;
if ((unsigned long)p->port < (unsigned long)port)
break;
}
p = kzalloc(sizeof(*p), GFP_ATOMIC);
err = -ENOMEM;
if (unlikely(!p))
goto err;
p->addr = *group;
p->port = port;
p->next = *pp;
hlist_add_head(&p->mglist, &port->mglist);
setup_timer(&p->timer, br_multicast_port_group_expired,
(unsigned long)p);
setup_timer(&p->query_timer, br_multicast_port_group_query_expired,
(unsigned long)p);
rcu_assign_pointer(*pp, p);
found:
mod_timer(&p->timer, now + br->multicast_membership_interval);
out:
err = 0;
err:
spin_unlock(&br->multicast_lock);
return err;
}
Commit Message: bridge: Fix mglist corruption that leads to memory corruption
The list mp->mglist is used to indicate whether a multicast group
is active on the bridge interface itself as opposed to one of the
constituent interfaces in the bridge.
Unfortunately the operation that adds the mp->mglist node to the
list neglected to check whether it has already been added. This
leads to list corruption in the form of nodes pointing to itself.
Normally this would be quite obvious as it would cause an infinite
loop when walking the list. However, as this list is never actually
walked (which means that we don't really need it, I'll get rid of
it in a subsequent patch), this instead is hidden until we perform
a delete operation on the affected nodes.
As the same node may now be pointed to by more than one node, the
delete operations can then cause modification of freed memory.
This was observed in practice to cause corruption in 512-byte slabs,
most commonly leading to crashes in jbd2.
Thanks to Josef Bacik for pointing me in the right direction.
Reported-by: Ian Page Hands <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: do_sigbus(struct pt_regs *regs, unsigned long error_code, unsigned long address,
unsigned int fault)
{
struct task_struct *tsk = current;
struct mm_struct *mm = tsk->mm;
int code = BUS_ADRERR;
up_read(&mm->mmap_sem);
/* Kernel mode? Handle exceptions or die: */
if (!(error_code & PF_USER)) {
no_context(regs, error_code, address);
return;
}
/* User-space => ok to do another page fault: */
if (is_prefetch(regs, error_code, address))
return;
tsk->thread.cr2 = address;
tsk->thread.error_code = error_code;
tsk->thread.trap_no = 14;
#ifdef CONFIG_MEMORY_FAILURE
if (fault & (VM_FAULT_HWPOISON|VM_FAULT_HWPOISON_LARGE)) {
printk(KERN_ERR
"MCE: Killing %s:%d due to hardware memory corruption fault at %lx\n",
tsk->comm, tsk->pid, address);
code = BUS_MCEERR_AR;
}
#endif
force_sig_info_fault(SIGBUS, code, address, tsk, fault);
}
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
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static noinline int btrfs_mksubvol(struct path *parent,
char *name, int namelen,
struct btrfs_root *snap_src,
u64 *async_transid, bool readonly,
struct btrfs_qgroup_inherit **inherit)
{
struct inode *dir = parent->dentry->d_inode;
struct dentry *dentry;
int error;
mutex_lock_nested(&dir->i_mutex, I_MUTEX_PARENT);
dentry = lookup_one_len(name, parent->dentry, namelen);
error = PTR_ERR(dentry);
if (IS_ERR(dentry))
goto out_unlock;
error = -EEXIST;
if (dentry->d_inode)
goto out_dput;
error = btrfs_may_create(dir, dentry);
if (error)
goto out_dput;
down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
goto out_up_read;
if (snap_src) {
error = create_snapshot(snap_src, dentry, name, namelen,
async_transid, readonly, inherit);
} else {
error = create_subvol(BTRFS_I(dir)->root, dentry,
name, namelen, async_transid, inherit);
}
if (!error)
fsnotify_mkdir(dir, dentry);
out_up_read:
up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
out_dput:
dput(dentry);
out_unlock:
mutex_unlock(&dir->i_mutex);
return error;
}
Commit Message: Btrfs: fix hash overflow handling
The handling for directory crc hash overflows was fairly obscure,
split_leaf returns EOVERFLOW when we try to extend the item and that is
supposed to bubble up to userland. For a while it did so, but along the
way we added better handling of errors and forced the FS readonly if we
hit IO errors during the directory insertion.
Along the way, we started testing only for EEXIST and the EOVERFLOW case
was dropped. The end result is that we may force the FS readonly if we
catch a directory hash bucket overflow.
This fixes a few problem spots. First I add tests for EOVERFLOW in the
places where we can safely just return the error up the chain.
btrfs_rename is harder though, because it tries to insert the new
directory item only after it has already unlinked anything the rename
was going to overwrite. Rather than adding very complex logic, I added
a helper to test for the hash overflow case early while it is still safe
to bail out.
Snapshot and subvolume creation had a similar problem, so they are using
the new helper now too.
Signed-off-by: Chris Mason <[email protected]>
Reported-by: Pascal Junod <[email protected]>
CWE ID: CWE-310
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithUnsignedLongArray(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
Vector<unsigned long> unsignedLongArray(jsUnsignedLongArrayToVector(exec, MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->methodWithUnsignedLongArray(unsignedLongArray);
return JSValue::encode(jsUndefined());
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Target: 1
Example 2:
Code: int test_lshift1(BIO *bp)
{
BIGNUM *a,*b,*c;
int i;
a=BN_new();
b=BN_new();
c=BN_new();
BN_bntest_rand(a,200,0,0); /**/
a->neg=rand_neg();
for (i=0; i<num0; i++)
{
BN_lshift1(b,a);
if (bp != NULL)
{
if (!results)
{
BN_print(bp,a);
BIO_puts(bp," * 2");
BIO_puts(bp," - ");
}
BN_print(bp,b);
BIO_puts(bp,"\n");
}
BN_add(c,a,a);
BN_sub(a,b,c);
if(!BN_is_zero(a))
{
fprintf(stderr,"Left shift one test failed!\n");
return 0;
}
BN_copy(a,b);
}
BN_free(a);
BN_free(b);
BN_free(c);
return(1);
}
Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp).
Reviewed-by: Emilia Kasper <[email protected]>
CWE ID: CWE-310
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool PrintDialogGtk::UpdateSettings(const DictionaryValue& settings,
const printing::PageRanges& ranges) {
bool collate;
int color;
bool landscape;
bool print_to_pdf;
int copies;
int duplex_mode;
std::string device_name;
if (!settings.GetBoolean(printing::kSettingLandscape, &landscape) ||
!settings.GetBoolean(printing::kSettingCollate, &collate) ||
!settings.GetInteger(printing::kSettingColor, &color) ||
!settings.GetBoolean(printing::kSettingPrintToPDF, &print_to_pdf) ||
!settings.GetInteger(printing::kSettingDuplexMode, &duplex_mode) ||
!settings.GetInteger(printing::kSettingCopies, &copies) ||
!settings.GetString(printing::kSettingDeviceName, &device_name)) {
return false;
}
if (!print_to_pdf) {
scoped_ptr<GtkPrinterList> printer_list(new GtkPrinterList);
printer_ = printer_list->GetPrinterWithName(device_name.c_str());
if (printer_) {
g_object_ref(printer_);
gtk_print_settings_set_printer(gtk_settings_,
gtk_printer_get_name(printer_));
}
gtk_print_settings_set_n_copies(gtk_settings_, copies);
gtk_print_settings_set_collate(gtk_settings_, collate);
const char* color_mode;
switch (color) {
case printing::COLOR:
color_mode = kColor;
break;
case printing::CMYK:
color_mode = kCMYK;
break;
default:
color_mode = kGrayscale;
break;
}
gtk_print_settings_set(gtk_settings_, kCUPSColorModel, color_mode);
if (duplex_mode != printing::UNKNOWN_DUPLEX_MODE) {
const char* cups_duplex_mode = NULL;
switch (duplex_mode) {
case printing::LONG_EDGE:
cups_duplex_mode = kDuplexNoTumble;
break;
case printing::SHORT_EDGE:
cups_duplex_mode = kDuplexTumble;
break;
case printing::SIMPLEX:
cups_duplex_mode = kDuplexNone;
break;
default: // UNKNOWN_DUPLEX_MODE
NOTREACHED();
break;
}
gtk_print_settings_set(gtk_settings_, kCUPSDuplex, cups_duplex_mode);
}
}
gtk_print_settings_set_orientation(
gtk_settings_,
landscape ? GTK_PAGE_ORIENTATION_LANDSCAPE :
GTK_PAGE_ORIENTATION_PORTRAIT);
InitPrintSettings(ranges);
return true;
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: crm_client_new(qb_ipcs_connection_t * c, uid_t uid_client, gid_t gid_client)
{
static uid_t uid_server = 0;
static gid_t gid_cluster = 0;
crm_client_t *client = NULL;
CRM_LOG_ASSERT(c);
if (c == NULL) {
return NULL;
}
if (gid_cluster == 0) {
uid_server = getuid();
if(crm_user_lookup(CRM_DAEMON_USER, NULL, &gid_cluster) < 0) {
static bool have_error = FALSE;
if(have_error == FALSE) {
crm_warn("Could not find group for user %s", CRM_DAEMON_USER);
have_error = TRUE;
}
}
}
if(gid_cluster != 0 && gid_client != 0) {
uid_t best_uid = -1; /* Passing -1 to chown(2) means don't change */
if(uid_client == 0 || uid_server == 0) { /* Someone is priveliged, but the other may not be */
best_uid = QB_MAX(uid_client, uid_server);
crm_trace("Allowing user %u to clean up after disconnect", best_uid);
}
crm_trace("Giving access to group %u", gid_cluster);
qb_ipcs_connection_auth_set(c, best_uid, gid_cluster, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
}
crm_client_init();
/* TODO: Do our own auth checking, return NULL if unauthorized */
client = calloc(1, sizeof(crm_client_t));
client->ipcs = c;
client->kind = CRM_CLIENT_IPC;
client->pid = crm_ipcs_client_pid(c);
client->id = crm_generate_uuid();
crm_debug("Connecting %p for uid=%d gid=%d pid=%u id=%s", c, uid_client, gid_client, client->pid, client->id);
#if ENABLE_ACL
client->user = uid2username(uid_client);
#endif
g_hash_table_insert(client_connections, c, client);
return client;
}
Commit Message: High: libcrmcommon: fix CVE-2016-7035 (improper IPC guarding)
It was discovered that at some not so uncommon circumstances, some
pacemaker daemons could be talked to, via libqb-facilitated IPC, by
unprivileged clients due to flawed authorization decision. Depending
on the capabilities of affected daemons, this might equip unauthorized
user with local privilege escalation or up to cluster-wide remote
execution of possibly arbitrary commands when such user happens to
reside at standard or remote/guest cluster node, respectively.
The original vulnerability was introduced in an attempt to allow
unprivileged IPC clients to clean up the file system materialized
leftovers in case the server (otherwise responsible for the lifecycle
of these files) crashes. While the intended part of such behavior is
now effectively voided (along with the unintended one), a best-effort
fix to address this corner case systemically at libqb is coming along
(https://github.com/ClusterLabs/libqb/pull/231).
Affected versions: 1.1.10-rc1 (2013-04-17) - 1.1.15 (2016-06-21)
Impact: Important
CVSSv3 ranking: 8.8 : AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H
Credits for independent findings, in chronological order:
Jan "poki" Pokorný, of Red Hat
Alain Moulle, of ATOS/BULL
CWE ID: CWE-285
Target: 1
Example 2:
Code: ui::TextInputType OmniboxViewViews::GetTextInputType() const {
ui::TextInputType input_type = views::Textfield::GetTextInputType();
#if defined(OS_WIN)
if (input_type != ui::TEXT_INPUT_TYPE_NONE && location_bar_view_) {
ui::InputMethod* input_method =
location_bar_view_->GetWidget()->GetInputMethod();
if (input_method && input_method->IsInputLocaleCJK())
return ui::TEXT_INPUT_TYPE_SEARCH;
}
#endif
return input_type;
}
Commit Message: omnibox: experiment with restoring placeholder when caret shows
Shows the "Search Google or type a URL" omnibox placeholder even when
the caret (text edit cursor) is showing / when focused. views::Textfield
works this way, as does <input placeholder="">. Omnibox and the NTP's
"fakebox" are exceptions in this regard and this experiment makes this
more consistent.
[email protected]
BUG=955585
Change-Id: I23c299c0973f2feb43f7a2be3bd3425a80b06c2d
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1582315
Commit-Queue: Dan Beam <[email protected]>
Reviewed-by: Tommy Li <[email protected]>
Cr-Commit-Position: refs/heads/master@{#654279}
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void libxsmm_sparse_csr_reader( libxsmm_generated_code* io_generated_code,
const char* i_csr_file_in,
unsigned int** o_row_idx,
unsigned int** o_column_idx,
double** o_values,
unsigned int* o_row_count,
unsigned int* o_column_count,
unsigned int* o_element_count ) {
FILE *l_csr_file_handle;
const unsigned int l_line_length = 512;
char l_line[512/*l_line_length*/+1];
unsigned int l_header_read = 0;
unsigned int* l_row_idx_id = NULL;
unsigned int l_i = 0;
l_csr_file_handle = fopen( i_csr_file_in, "r" );
if ( l_csr_file_handle == NULL ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_INPUT );
return;
}
while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) {
if ( strlen(l_line) == l_line_length ) {
free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id);
*o_row_idx = 0; *o_column_idx = 0; *o_values = 0;
fclose(l_csr_file_handle); /* close mtx file */
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_LEN );
return;
}
/* check if we are still reading comments header */
if ( l_line[0] == '%' ) {
continue;
} else {
/* if we are the first line after comment header, we allocate our data structures */
if ( l_header_read == 0 ) {
if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) {
/* allocate CSC data-structure matching mtx file */
*o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count));
*o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * ((size_t)(*o_row_count) + 1));
*o_values = (double*) malloc(sizeof(double) * (*o_element_count));
l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count));
/* check if mallocs were successful */
if ( ( *o_row_idx == NULL ) ||
( *o_column_idx == NULL ) ||
( *o_values == NULL ) ||
( l_row_idx_id == NULL ) ) {
free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id);
*o_row_idx = 0; *o_column_idx = 0; *o_values = 0;
fclose(l_csr_file_handle); /* close mtx file */
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_ALLOC_DATA );
return;
}
/* set everything to zero for init */
memset(*o_row_idx, 0, sizeof(unsigned int) * ((size_t)(*o_row_count) + 1));
memset(*o_column_idx, 0, sizeof(unsigned int) * (*o_element_count));
memset(*o_values, 0, sizeof(double) * (*o_element_count));
memset(l_row_idx_id, 0, sizeof(unsigned int) * (*o_row_count));
/* init column idx */
for ( l_i = 0; l_i <= *o_row_count; ++l_i )
(*o_row_idx)[l_i] = (*o_element_count);
/* init */
(*o_row_idx)[0] = 0;
l_i = 0;
l_header_read = 1;
} else {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_DESC );
fclose( l_csr_file_handle ); /* close mtx file */
return;
}
/* now we read the actual content */
} else {
unsigned int l_row = 0, l_column = 0;
double l_value = 0;
/* read a line of content */
if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) {
free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id);
*o_row_idx = 0; *o_column_idx = 0; *o_values = 0;
fclose(l_csr_file_handle); /* close mtx file */
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_ELEMS );
return;
}
/* adjust numbers to zero termination */
l_row--;
l_column--;
/* add these values to row and value structure */
(*o_column_idx)[l_i] = l_column;
(*o_values)[l_i] = l_value;
l_i++;
/* handle columns, set id to own for this column, yeah we need to handle empty columns */
l_row_idx_id[l_row] = 1;
(*o_row_idx)[l_row+1] = l_i;
}
}
}
/* close mtx file */
fclose( l_csr_file_handle );
/* check if we read a file which was consistent */
if ( l_i != (*o_element_count) ) {
free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id);
*o_row_idx = 0; *o_column_idx = 0; *o_values = 0;
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_LEN );
return;
}
if ( l_row_idx_id != NULL ) {
/* let's handle empty rows */
for ( l_i = 0; l_i < (*o_row_count); l_i++) {
if ( l_row_idx_id[l_i] == 0 ) {
(*o_row_idx)[l_i+1] = (*o_row_idx)[l_i];
}
}
/* free helper data structure */
free( l_row_idx_id );
}
}
Commit Message: Issue #287: made CSR/CSC readers more robust against invalid input (case #1).
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: DownloadCoreServiceImpl::GetDownloadManagerDelegate() {
DownloadManager* manager = BrowserContext::GetDownloadManager(profile_);
if (download_manager_created_) {
DCHECK(static_cast<DownloadManagerDelegate*>(manager_delegate_.get()) ==
manager->GetDelegate());
return manager_delegate_.get();
}
download_manager_created_ = true;
if (!manager_delegate_.get())
manager_delegate_.reset(new ChromeDownloadManagerDelegate(profile_));
manager_delegate_->SetDownloadManager(manager);
#if BUILDFLAG(ENABLE_EXTENSIONS)
extension_event_router_.reset(
new extensions::ExtensionDownloadsEventRouter(profile_, manager));
#endif
if (!profile_->IsOffTheRecord()) {
history::HistoryService* history = HistoryServiceFactory::GetForProfile(
profile_, ServiceAccessType::EXPLICIT_ACCESS);
history->GetNextDownloadId(
manager_delegate_->GetDownloadIdReceiverCallback());
download_history_.reset(new DownloadHistory(
manager, std::unique_ptr<DownloadHistory::HistoryAdapter>(
new DownloadHistory::HistoryAdapter(history))));
}
download_ui_.reset(new DownloadUIController(
manager, std::unique_ptr<DownloadUIController::Delegate>()));
g_browser_process->download_status_updater()->AddManager(manager);
return manager_delegate_.get();
}
Commit Message: Don't downcast DownloadManagerDelegate to ChromeDownloadManagerDelegate.
DownloadManager has public SetDelegate method and tests and or other subsystems
can install their own implementations of the delegate.
Bug: 805905
Change-Id: Iecf1e0aceada0e1048bed1e2d2ceb29ca64295b8
TBR: tests updated to follow the API change.
Reviewed-on: https://chromium-review.googlesource.com/894702
Reviewed-by: David Vallet <[email protected]>
Reviewed-by: Min Qin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533515}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void igmp_group_dropped(struct ip_mc_list *im)
{
struct in_device *in_dev = im->interface;
#ifdef CONFIG_IP_MULTICAST
int reporter;
#endif
if (im->loaded) {
im->loaded = 0;
ip_mc_filter_del(in_dev, im->multiaddr);
}
#ifdef CONFIG_IP_MULTICAST
if (im->multiaddr == IGMP_ALL_HOSTS)
return;
reporter = im->reporter;
igmp_stop_timer(im);
if (!in_dev->dead) {
if (IGMP_V1_SEEN(in_dev))
return;
if (IGMP_V2_SEEN(in_dev)) {
if (reporter)
igmp_send_report(in_dev, im, IGMP_HOST_LEAVE_MESSAGE);
return;
}
/* IGMPv3 */
igmpv3_add_delrec(in_dev, im);
igmp_ifc_event(in_dev);
}
#endif
}
Commit Message: igmp: Avoid zero delay when receiving odd mixture of IGMP queries
Commit 5b7c84066733c5dfb0e4016d939757b38de189e4 ('ipv4: correct IGMP
behavior on v3 query during v2-compatibility mode') added yet another
case for query parsing, which can result in max_delay = 0. Substitute
a value of 1, as in the usual v3 case.
Reported-by: Simon McVittie <[email protected]>
References: http://bugs.debian.org/654876
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void *bpf_any_get(void *raw, enum bpf_type type)
{
switch (type) {
case BPF_TYPE_PROG:
atomic_inc(&((struct bpf_prog *)raw)->aux->refcnt);
break;
case BPF_TYPE_MAP:
bpf_map_inc(raw, true);
break;
default:
WARN_ON_ONCE(1);
break;
}
return raw;
}
Commit Message: bpf: fix refcnt overflow
On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK,
the malicious application may overflow 32-bit bpf program refcnt.
It's also possible to overflow map refcnt on 1Tb system.
Impose 32k hard limit which means that the same bpf program or
map cannot be shared by more than 32k processes.
Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Acked-by: Daniel Borkmann <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n)
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0,
additional_code_len, sign, mismatch;
VLC *cur_vlc = &ctx->studio_intra_tab[0];
uint8_t *const scantable = s->intra_scantable.permutated;
const uint16_t *quant_matrix;
uint32_t flc;
const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6));
const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1);
mismatch = 1;
memset(block, 0, 64 * sizeof(int32_t));
if (n < 4) {
cc = 0;
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->intra_matrix;
} else {
cc = (n & 1) + 1;
if (ctx->rgb)
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
else
dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->chroma_intra_matrix;
}
if (dct_dc_size < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n");
return AVERROR_INVALIDDATA;
} else if (dct_dc_size == 0) {
dct_diff = 0;
} else {
dct_diff = get_xbits(&s->gb, dct_dc_size);
if (dct_dc_size > 8) {
if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8"))
return AVERROR_INVALIDDATA;
}
}
s->last_dc[cc] += dct_diff;
if (s->mpeg_quant)
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision);
else
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision);
/* TODO: support mpeg_quant for AC coefficients */
block[0] = av_clip(block[0], min, max);
mismatch ^= block[0];
/* AC Coefficients */
while (1) {
group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2);
if (group < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n");
return AVERROR_INVALIDDATA;
}
additional_code_len = ac_state_tab[group][0];
cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]];
if (group == 0) {
/* End of Block */
break;
} else if (group >= 1 && group <= 6) {
/* Zero run length (Table B.47) */
run = 1 << additional_code_len;
if (additional_code_len)
run += get_bits(&s->gb, additional_code_len);
idx += run;
continue;
} else if (group >= 7 && group <= 12) {
/* Zero run length and +/-1 level (Table B.48) */
code = get_bits(&s->gb, additional_code_len);
sign = code & 1;
code >>= 1;
run = (1 << (additional_code_len - 1)) + code;
idx += run;
j = scantable[idx++];
block[j] = sign ? 1 : -1;
} else if (group >= 13 && group <= 20) {
/* Level value (Table B.49) */
j = scantable[idx++];
block[j] = get_xbits(&s->gb, additional_code_len);
} else if (group == 21) {
/* Escape */
j = scantable[idx++];
additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4;
flc = get_bits(&s->gb, additional_code_len);
if (flc >> (additional_code_len-1))
block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1);
else
block[j] = flc;
}
block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32;
block[j] = av_clip(block[j], min, max);
mismatch ^= block[j];
}
block[63] ^= mismatch & 1;
return 0;
}
Commit Message: avcodec/mpeg4videodec: Check idx in mpeg4_decode_studio_block()
Fixes: Out of array access
Fixes: 13500/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_MPEG4_fuzzer-5769760178962432
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg
Reviewed-by: Kieran Kunhya <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-125
Target: 1
Example 2:
Code: ftp_do_pasv (int csock, ip_address *addr, int *port)
{
if (!opt.server_response)
logputs (LOG_VERBOSE, "==> PASV ... ");
return ftp_pasv (csock, addr, port);
}
Commit Message:
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void AppShortcutManager::OnceOffCreateShortcuts() {
bool was_enabled = prefs_->GetBoolean(prefs::kAppShortcutsHaveBeenCreated);
#if defined(OS_MACOSX)
bool is_now_enabled = apps::IsAppShimsEnabled();
#else
bool is_now_enabled = true;
#endif // defined(OS_MACOSX)
if (was_enabled != is_now_enabled)
prefs_->SetBoolean(prefs::kAppShortcutsHaveBeenCreated, is_now_enabled);
if (was_enabled || !is_now_enabled)
return;
extensions::ExtensionSystem* extension_system;
ExtensionServiceInterface* extension_service;
if (!(extension_system = extensions::ExtensionSystem::Get(profile_)) ||
!(extension_service = extension_system->extension_service()))
return;
const extensions::ExtensionSet* apps = extension_service->extensions();
for (extensions::ExtensionSet::const_iterator it = apps->begin();
it != apps->end(); ++it) {
if (ShouldCreateShortcutFor(profile_, it->get()))
CreateShortcutsInApplicationsMenu(profile_, it->get());
}
}
Commit Message: Remove --disable-app-shims.
App shims have been enabled by default for 3 milestones
(since r242711).
BUG=350161
Review URL: https://codereview.chromium.org/298953002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272786 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SoftAVC::drainAllOutputBuffers(bool eos) {
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
H264SwDecPicture decodedPicture;
if (mHeadersDecoded) {
while (!outQueue.empty()
&& H264SWDEC_PIC_RDY == H264SwDecNextPicture(
mHandle, &decodedPicture, eos /* flush */)) {
int32_t picId = decodedPicture.picId;
uint8_t *data = (uint8_t *) decodedPicture.pOutputPicture;
drainOneOutputBuffer(picId, data);
}
}
if (!eos) {
return;
}
while (!outQueue.empty()) {
BufferInfo *outInfo = *outQueue.begin();
outQueue.erase(outQueue.begin());
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nTimeStamp = 0;
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
mEOSStatus = OUTPUT_FRAMES_FLUSHED;
}
}
Commit Message: codecs: check OMX buffer size before use in (h263|h264)dec
Bug: 27833616
Change-Id: I0fd599b3da431425d89236ffdd9df423c11947c0
CWE ID: CWE-20
Target: 1
Example 2:
Code: CompositedLayerRasterInvalidatorTest& RasterInvalidationCount(int count) {
size_t size = data_.chunks.size();
DCHECK_GT(size, 0u);
data_.raster_invalidation_rects.resize(size);
data_.raster_invalidation_trackings.resize(size);
int index = static_cast<int>(size - 1);
for (int i = 0; i < count; ++i) {
IntRect rect(index * 11, index * 22, index * 22 + 100 + i,
index * 11 + 100 + i);
data_.raster_invalidation_rects.back().push_back(FloatRect(rect));
data_.raster_invalidation_trackings.back().push_back(
RasterInvalidationInfo{
&data_.chunks.back().id.client, "Test", rect,
static_cast<PaintInvalidationReason>(
static_cast<int>(PaintInvalidationReason::kFull) + index +
i)});
}
return *this;
}
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:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: rdpdr_handle_ok(uint32 device, RD_NTHANDLE handle)
{
switch (g_rdpdr_device[device].device_type)
{
case DEVICE_TYPE_PARALLEL:
case DEVICE_TYPE_SERIAL:
case DEVICE_TYPE_PRINTER:
case DEVICE_TYPE_SCARD:
if (g_rdpdr_device[device].handle != handle)
return False;
break;
case DEVICE_TYPE_DISK:
if (g_fileinfo[handle].device_id != device)
return False;
break;
}
return True;
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: iakerb_gss_delete_sec_context(OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_buffer_t output_token)
{
OM_uint32 major_status = GSS_S_COMPLETE;
if (output_token != GSS_C_NO_BUFFER) {
output_token->length = 0;
output_token->value = NULL;
}
*minor_status = 0;
if (*context_handle != GSS_C_NO_CONTEXT) {
iakerb_ctx_id_t iakerb_ctx = (iakerb_ctx_id_t)*context_handle;
if (iakerb_ctx->magic == KG_IAKERB_CONTEXT) {
iakerb_release_context(iakerb_ctx);
*context_handle = GSS_C_NO_CONTEXT;
} else {
assert(iakerb_ctx->magic == KG_CONTEXT);
major_status = krb5_gss_delete_sec_context(minor_status,
context_handle,
output_token);
}
}
return major_status;
}
Commit Message: Fix IAKERB context aliasing bugs [CVE-2015-2696]
The IAKERB mechanism currently replaces its context handle with the
krb5 mechanism handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the IAKERB context structure after context
establishment and add new IAKERB entry points to refer to it with that
type. Add initiate and established flags to the IAKERB context
structure for use in gss_inquire_context() prior to context
establishment.
CVE-2015-2696:
In MIT krb5 1.9 and later, applications which call
gss_inquire_context() on a partially-established IAKERB context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. Java server applications using the
native JGSS provider are vulnerable to this bug. A carefully crafted
IAKERB packet might allow the gss_inquire_context() call to succeed
with attacker-determined results, but applications should not make
access control decisions based on gss_inquire_context() results prior
to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18
Target: 1
Example 2:
Code: int usb_hub_claim_port(struct usb_device *hdev, unsigned port1,
struct usb_dev_state *owner)
{
int rc;
struct usb_dev_state **powner;
rc = find_port_owner(hdev, port1, &powner);
if (rc)
return rc;
if (*powner)
return -EBUSY;
*powner = owner;
return rc;
}
Commit Message: USB: fix invalid memory access in hub_activate()
Commit 8520f38099cc ("USB: change hub initialization sleeps to
delayed_work") changed the hub_activate() routine to make part of it
run in a workqueue. However, the commit failed to take a reference to
the usb_hub structure or to lock the hub interface while doing so. As
a result, if a hub is plugged in and quickly unplugged before the work
routine can run, the routine will try to access memory that has been
deallocated. Or, if the hub is unplugged while the routine is
running, the memory may be deallocated while it is in active use.
This patch fixes the problem by taking a reference to the usb_hub at
the start of hub_activate() and releasing it at the end (when the work
is finished), and by locking the hub interface while the work routine
is running. It also adds a check at the start of the routine to see
if the hub has already been disconnected, in which nothing should be
done.
Signed-off-by: Alan Stern <[email protected]>
Reported-by: Alexandru Cornea <[email protected]>
Tested-by: Alexandru Cornea <[email protected]>
Fixes: 8520f38099cc ("USB: change hub initialization sleeps to delayed_work")
CC: <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Browser::TabMoved(TabContents* contents,
int from_index,
int to_index) {
DCHECK(from_index >= 0 && to_index >= 0);
SyncHistoryWithTabs(std::min(from_index, to_index));
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void AppShortcutManager::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_EXTENSIONS_READY: {
OnceOffCreateShortcuts();
break;
}
case chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED: {
#if defined(OS_MACOSX)
if (!apps::IsAppShimsEnabled())
break;
#endif // defined(OS_MACOSX)
const extensions::InstalledExtensionInfo* installed_info =
content::Details<const extensions::InstalledExtensionInfo>(details)
.ptr();
const Extension* extension = installed_info->extension;
if (installed_info->is_update) {
web_app::UpdateAllShortcuts(
base::UTF8ToUTF16(installed_info->old_name), profile_, extension);
} else if (ShouldCreateShortcutFor(profile_, extension)) {
CreateShortcutsInApplicationsMenu(profile_, extension);
}
break;
}
case chrome::NOTIFICATION_EXTENSION_UNINSTALLED: {
const Extension* extension = content::Details<const Extension>(
details).ptr();
web_app::DeleteAllShortcuts(profile_, extension);
break;
}
default:
NOTREACHED();
}
}
Commit Message: Remove --disable-app-shims.
App shims have been enabled by default for 3 milestones
(since r242711).
BUG=350161
Review URL: https://codereview.chromium.org/298953002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272786 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int nfc_genl_dev_down(struct sk_buff *skb, struct genl_info *info)
{
struct nfc_dev *dev;
int rc;
u32 idx;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX])
return -EINVAL;
idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(idx);
if (!dev)
return -ENODEV;
rc = nfc_dev_down(dev);
nfc_put_device(dev);
return rc;
}
Commit Message: nfc: Ensure presence of required attributes in the deactivate_target handler
Check that the NFC_ATTR_TARGET_INDEX attributes (in addition to
NFC_ATTR_DEVICE_INDEX) are provided by the netlink client prior to
accessing them. This prevents potential unhandled NULL pointer dereference
exceptions which can be triggered by malicious user-mode programs,
if they omit one or both of these attributes.
Signed-off-by: Young Xiao <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-476
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: XineramaXvShmPutImage(ClientPtr client)
{
REQUEST(xvShmPutImageReq);
PanoramiXRes *draw, *gc, *port;
Bool send_event = stuff->send_event;
Bool isRoot;
int result, i, x, y;
REQUEST_SIZE_MATCH(xvShmPutImageReq);
result = dixLookupResourceByClass((void **) &draw, stuff->drawable,
XRC_DRAWABLE, client, DixWriteAccess);
if (result != Success)
result = dixLookupResourceByType((void **) &gc, stuff->gc,
XRT_GC, client, DixReadAccess);
if (result != Success)
return result;
result = dixLookupResourceByType((void **) &port, stuff->port,
XvXRTPort, client, DixReadAccess);
if (result != Success)
return result;
isRoot = (draw->type == XRT_WINDOW) && draw->u.win.root;
x = stuff->drw_x;
y = stuff->drw_y;
FOR_NSCREENS_BACKWARD(i) {
if (port->info[i].id) {
stuff->drawable = draw->info[i].id;
stuff->port = port->info[i].id;
stuff->gc = gc->info[i].id;
stuff->drw_x = x;
stuff->drw_y = y;
if (isRoot) {
stuff->drw_x -= screenInfo.screens[i]->x;
stuff->drw_y -= screenInfo.screens[i]->y;
}
stuff->send_event = (send_event && !i) ? 1 : 0;
result = ProcXvShmPutImage(client);
}
}
return result;
}
Commit Message:
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int verify_compat_iovec(struct msghdr *kern_msg, struct iovec *kern_iov,
struct sockaddr_storage *kern_address, int mode)
{
int tot_len;
if (kern_msg->msg_namelen) {
if (mode == VERIFY_READ) {
int err = move_addr_to_kernel(kern_msg->msg_name,
kern_msg->msg_namelen,
kern_address);
if (err < 0)
return err;
}
kern_msg->msg_name = kern_address;
} else
kern_msg->msg_name = NULL;
tot_len = iov_from_user_compat_to_kern(kern_iov,
(struct compat_iovec __user *)kern_msg->msg_iov,
kern_msg->msg_iovlen);
if (tot_len >= 0)
kern_msg->msg_iov = kern_iov;
return tot_len;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void pcnet_poll_timer(void *opaque)
{
PCNetState *s = opaque;
timer_del(s->poll_timer);
if (CSR_TDMD(s)) {
pcnet_transmit(s);
}
pcnet_update_irq(s);
if (!CSR_STOP(s) && !CSR_SPND(s) && !CSR_DPOLL(s)) {
uint64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) * 33;
if (!s->timer || !now)
s->timer = now;
else {
uint64_t t = now - s->timer + CSR_POLL(s);
if (t > 0xffffLL) {
pcnet_poll(s);
CSR_POLL(s) = CSR_PINT(s);
} else
CSR_POLL(s) = t;
}
timer_mod(s->poll_timer,
pcnet_get_next_poll_time(s,qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)));
}
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: standard_info_part2(standard_display *dp, png_const_structp pp,
png_const_infop pi, int nImages)
{
/* Record cbRow now that it can be found. */
dp->pixel_size = bit_size(pp, png_get_color_type(pp, pi),
png_get_bit_depth(pp, pi));
dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size;
dp->cbRow = png_get_rowbytes(pp, pi);
/* Validate the rowbytes here again. */
if (dp->cbRow != (dp->bit_width+7)/8)
png_error(pp, "bad png_get_rowbytes calculation");
/* Then ensure there is enough space for the output image(s). */
store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)
{
int lastBorder;
/* Seek left */
int leftLimit = -1, rightLimit;
int i, restoreAlphaBlending = 0;
if (border < 0) {
/* Refuse to fill to a non-solid border */
return;
}
if (!im->trueColor) {
if ((color > (im->colorsTotal - 1)) || (border > (im->colorsTotal - 1)) || (color < 0)) {
return;
}
}
restoreAlphaBlending = im->alphaBlendingFlag;
im->alphaBlendingFlag = 0;
if (x >= im->sx) {
x = im->sx - 1;
} else if (x < 0) {
x = 0;
}
if (y >= im->sy) {
y = im->sy - 1;
} else if (y < 0) {
y = 0;
}
for (i = x; i >= 0; i--) {
if (gdImageGetPixel(im, i, y) == border) {
break;
}
gdImageSetPixel(im, i, y, color);
leftLimit = i;
}
if (leftLimit == -1) {
im->alphaBlendingFlag = restoreAlphaBlending;
return;
}
/* Seek right */
rightLimit = x;
for (i = (x + 1); i < im->sx; i++) {
if (gdImageGetPixel(im, i, y) == border) {
break;
}
gdImageSetPixel(im, i, y, color);
rightLimit = i;
}
/* Look at lines above and below and start paints */
/* Above */
if (y > 0) {
lastBorder = 1;
for (i = leftLimit; i <= rightLimit; i++) {
int c = gdImageGetPixel(im, i, y - 1);
if (lastBorder) {
if ((c != border) && (c != color)) {
gdImageFillToBorder(im, i, y - 1, border, color);
lastBorder = 0;
}
} else if ((c == border) || (c == color)) {
lastBorder = 1;
}
}
}
/* Below */
if (y < ((im->sy) - 1)) {
lastBorder = 1;
for (i = leftLimit; i <= rightLimit; i++) {
int c = gdImageGetPixel(im, i, y + 1);
if (lastBorder) {
if ((c != border) && (c != color)) {
gdImageFillToBorder(im, i, y + 1, border, color);
lastBorder = 0;
}
} else if ((c == border) || (c == color)) {
lastBorder = 1;
}
}
}
im->alphaBlendingFlag = restoreAlphaBlending;
}
Commit Message: Fix #72696: imagefilltoborder stackoverflow on truecolor images
We must not allow negative color values be passed to
gdImageFillToBorder(), because that can lead to infinite recursion
since the recursion termination condition will not necessarily be met.
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int crc32c_sparc64_finup(struct shash_desc *desc, const u8 *data,
unsigned int len, u8 *out)
{
return __crc32c_sparc64_finup(shash_desc_ctx(desc), data, len, out);
}
Commit Message: crypto: prefix module autoloading with "crypto-"
This prefixes all crypto module loading with "crypto-" so we never run
the risk of exposing module auto-loading to userspace via a crypto API,
as demonstrated by Mathias Krause:
https://lkml.org/lkml/2013/3/4/70
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: entry_guards_expand_sample(guard_selection_t *gs)
{
tor_assert(gs);
const or_options_t *options = get_options();
if (live_consensus_is_missing(gs)) {
log_info(LD_GUARD, "Not expanding the sample guard set; we have "
"no live consensus.");
return NULL;
}
int n_sampled = smartlist_len(gs->sampled_entry_guards);
entry_guard_t *added_guard = NULL;
int n_usable_filtered_guards = num_reachable_filtered_guards(gs, NULL);
int n_guards = 0;
smartlist_t *eligible_guards = get_eligible_guards(options, gs, &n_guards);
const int max_sample = get_max_sample_size(gs, n_guards);
const int min_filtered_sample = get_min_filtered_sample_size();
log_info(LD_GUARD, "Expanding the sample guard set. We have %d guards "
"in the sample, and %d eligible guards to extend it with.",
n_sampled, smartlist_len(eligible_guards));
while (n_usable_filtered_guards < min_filtered_sample) {
/* Has our sample grown too large to expand? */
if (n_sampled >= max_sample) {
log_info(LD_GUARD, "Not expanding the guard sample any further; "
"just hit the maximum sample threshold of %d",
max_sample);
goto done;
}
/* Did we run out of guards? */
if (smartlist_len(eligible_guards) == 0) {
/* LCOV_EXCL_START
As long as MAX_SAMPLE_THRESHOLD makes can't be adjusted to
allow all guards to be sampled, this can't be reached.
*/
log_info(LD_GUARD, "Not expanding the guard sample any further; "
"just ran out of eligible guards");
goto done;
/* LCOV_EXCL_STOP */
}
/* Otherwise we can add at least one new guard. */
added_guard = select_and_add_guard_item_for_sample(gs, eligible_guards);
if (!added_guard)
goto done; // LCOV_EXCL_LINE -- only fails on BUG.
++n_sampled;
if (added_guard->is_usable_filtered_guard)
++n_usable_filtered_guards;
}
done:
smartlist_free(eligible_guards);
return added_guard;
}
Commit Message: Consider the exit family when applying guard restrictions.
When the new path selection logic went into place, I accidentally
dropped the code that considered the _family_ of the exit node when
deciding if the guard was usable, and we didn't catch that during
code review.
This patch makes the guard_restriction_t code consider the exit
family as well, and adds some (hopefully redundant) checks for the
case where we lack a node_t for a guard but we have a bridge_info_t
for it.
Fixes bug 22753; bugfix on 0.3.0.1-alpha. Tracked as TROVE-2016-006
and CVE-2017-0377.
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int copy_creds(struct task_struct *p, unsigned long clone_flags)
{
#ifdef CONFIG_KEYS
struct thread_group_cred *tgcred;
#endif
struct cred *new;
int ret;
if (
#ifdef CONFIG_KEYS
!p->cred->thread_keyring &&
#endif
clone_flags & CLONE_THREAD
) {
p->real_cred = get_cred(p->cred);
get_cred(p->cred);
alter_cred_subscribers(p->cred, 2);
kdebug("share_creds(%p{%d,%d})",
p->cred, atomic_read(&p->cred->usage),
read_cred_subscribers(p->cred));
atomic_inc(&p->cred->user->processes);
return 0;
}
new = prepare_creds();
if (!new)
return -ENOMEM;
if (clone_flags & CLONE_NEWUSER) {
ret = create_user_ns(new);
if (ret < 0)
goto error_put;
}
/* cache user_ns in cred. Doesn't need a refcount because it will
* stay pinned by cred->user
*/
new->user_ns = new->user->user_ns;
#ifdef CONFIG_KEYS
/* new threads get their own thread keyrings if their parent already
* had one */
if (new->thread_keyring) {
key_put(new->thread_keyring);
new->thread_keyring = NULL;
if (clone_flags & CLONE_THREAD)
install_thread_keyring_to_cred(new);
}
/* we share the process and session keyrings between all the threads in
* a process - this is slightly icky as we violate COW credentials a
* bit */
if (!(clone_flags & CLONE_THREAD)) {
tgcred = kmalloc(sizeof(*tgcred), GFP_KERNEL);
if (!tgcred) {
ret = -ENOMEM;
goto error_put;
}
atomic_set(&tgcred->usage, 1);
spin_lock_init(&tgcred->lock);
tgcred->process_keyring = NULL;
tgcred->session_keyring = key_get(new->tgcred->session_keyring);
release_tgcred(new);
new->tgcred = tgcred;
}
#endif
atomic_inc(&new->user->processes);
p->cred = p->real_cred = get_cred(new);
alter_cred_subscribers(new, 2);
validate_creds(new);
return 0;
error_put:
put_cred(new);
return ret;
}
Commit Message: cred: copy_process() should clear child->replacement_session_keyring
keyctl_session_to_parent(task) sets ->replacement_session_keyring,
it should be processed and cleared by key_replace_session_keyring().
However, this task can fork before it notices TIF_NOTIFY_RESUME and
the new child gets the bogus ->replacement_session_keyring copied by
dup_task_struct(). This is obviously wrong and, if nothing else, this
leads to put_cred(already_freed_cred).
change copy_creds() to clear this member. If copy_process() fails
before this point the wrong ->replacement_session_keyring doesn't
matter, exit_creds() won't be called.
Cc: <[email protected]>
Signed-off-by: Oleg Nesterov <[email protected]>
Acked-by: David Howells <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: void CopyDebuggee(Debuggee* dst, const Debuggee& src) {
if (src.tab_id)
dst->tab_id.reset(new int(*src.tab_id));
if (src.extension_id)
dst->extension_id.reset(new std::string(*src.extension_id));
if (src.target_id)
dst->target_id.reset(new std::string(*src.target_id));
}
Commit Message: Have the Debugger extension api check that it has access to the tab
Check PermissionsData::CanAccessTab() prior to attaching the debugger.
BUG=367567
Review URL: https://codereview.chromium.org/352523003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@280354 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: xfs_attr_leaf_addname(xfs_da_args_t *args)
{
xfs_inode_t *dp;
struct xfs_buf *bp;
int retval, error, committed, forkoff;
trace_xfs_attr_leaf_addname(args);
/*
* Read the (only) block in the attribute list in.
*/
dp = args->dp;
args->blkno = 0;
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp);
if (error)
return error;
/*
* Look up the given attribute in the leaf block. Figure out if
* the given flags produce an error or call for an atomic rename.
*/
retval = xfs_attr3_leaf_lookup_int(bp, args);
if ((args->flags & ATTR_REPLACE) && (retval == ENOATTR)) {
xfs_trans_brelse(args->trans, bp);
return retval;
} else if (retval == EEXIST) {
if (args->flags & ATTR_CREATE) { /* pure create op */
xfs_trans_brelse(args->trans, bp);
return retval;
}
trace_xfs_attr_leaf_replace(args);
args->op_flags |= XFS_DA_OP_RENAME; /* an atomic rename */
args->blkno2 = args->blkno; /* set 2nd entry info*/
args->index2 = args->index;
args->rmtblkno2 = args->rmtblkno;
args->rmtblkcnt2 = args->rmtblkcnt;
}
/*
* Add the attribute to the leaf block, transitioning to a Btree
* if required.
*/
retval = xfs_attr3_leaf_add(bp, args);
if (retval == ENOSPC) {
/*
* Promote the attribute list to the Btree format, then
* Commit that transaction so that the node_addname() call
* can manage its own transactions.
*/
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_attr3_leaf_to_node(args);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
/*
* Commit the current trans (including the inode) and start
* a new one.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
return (error);
/*
* Fob the whole rest of the problem off on the Btree code.
*/
error = xfs_attr_node_addname(args);
return(error);
}
/*
* Commit the transaction that added the attr name so that
* later routines can manage their own transactions.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
return (error);
/*
* If there was an out-of-line value, allocate the blocks we
* identified for its storage and copy the value. This is done
* after we create the attribute so that we don't overflow the
* maximum size of a transaction and/or hit a deadlock.
*/
if (args->rmtblkno > 0) {
error = xfs_attr_rmtval_set(args);
if (error)
return(error);
}
/*
* If this is an atomic rename operation, we must "flip" the
* incomplete flags on the "new" and "old" attribute/value pairs
* so that one disappears and one appears atomically. Then we
* must remove the "old" attribute/value pair.
*/
if (args->op_flags & XFS_DA_OP_RENAME) {
/*
* In a separate transaction, set the incomplete flag on the
* "old" attr and clear the incomplete flag on the "new" attr.
*/
error = xfs_attr3_leaf_flipflags(args);
if (error)
return(error);
/*
* Dismantle the "old" attribute/value pair by removing
* a "remote" value (if it exists).
*/
args->index = args->index2;
args->blkno = args->blkno2;
args->rmtblkno = args->rmtblkno2;
args->rmtblkcnt = args->rmtblkcnt2;
if (args->rmtblkno) {
error = xfs_attr_rmtval_remove(args);
if (error)
return(error);
}
/*
* Read in the block containing the "old" attr, then
* remove the "old" attr from that block (neat, huh!)
*/
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno,
-1, &bp);
if (error)
return error;
xfs_attr3_leaf_remove(bp, args);
/*
* If the result is small enough, shrink it all into the inode.
*/
if ((forkoff = xfs_attr_shortform_allfit(bp, dp))) {
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_attr3_leaf_to_shortform(bp, args, forkoff);
/* bp is gone due to xfs_da_shrink_inode */
if (!error) {
error = xfs_bmap_finish(&args->trans,
args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans
* and started a new one. We need the inode to be
* in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
}
/*
* Commit the remove and start the next trans in series.
*/
error = xfs_trans_roll(&args->trans, dp);
} else if (args->rmtblkno > 0) {
/*
* Added a "remote" value, just clear the incomplete flag.
*/
error = xfs_attr3_leaf_clearflag(args);
}
return error;
}
Commit Message: xfs: remote attribute overwrite causes transaction overrun
Commit e461fcb ("xfs: remote attribute lookups require the value
length") passes the remote attribute length in the xfs_da_args
structure on lookup so that CRC calculations and validity checking
can be performed correctly by related code. This, unfortunately has
the side effect of changing the args->valuelen parameter in cases
where it shouldn't.
That is, when we replace a remote attribute, the incoming
replacement stores the value and length in args->value and
args->valuelen, but then the lookup which finds the existing remote
attribute overwrites args->valuelen with the length of the remote
attribute being replaced. Hence when we go to create the new
attribute, we create it of the size of the existing remote
attribute, not the size it is supposed to be. When the new attribute
is much smaller than the old attribute, this results in a
transaction overrun and an ASSERT() failure on a debug kernel:
XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331
Fix this by keeping the remote attribute value length separate to
the attribute value length in the xfs_da_args structure. The enables
us to pass the length of the remote attribute to be removed without
overwriting the new attribute's length.
Also, ensure that when we save remote block contexts for a later
rename we zero the original state variables so that we don't confuse
the state of the attribute to be removes with the state of the new
attribute that we just added. [Spotted by Brain Foster.]
Signed-off-by: Dave Chinner <[email protected]>
Reviewed-by: Brian Foster <[email protected]>
Signed-off-by: Dave Chinner <[email protected]>
CWE ID: CWE-19
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RemoveProcessIdFromGlobalMap(int32_t process_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
GetProcessIdToFilterMap()->erase(process_id);
}
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155}
CWE ID: CWE-362
Target: 1
Example 2:
Code: void Browser::RendererResponsive(WebContents* source) {
chrome::HideHungRendererDialog(source);
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int mailimf_group_parse(const char * message, size_t length,
size_t * indx,
struct mailimf_group ** result)
{
size_t cur_token;
char * display_name;
struct mailimf_mailbox_list * mailbox_list;
struct mailimf_group * group;
int r;
int res;
cur_token = * indx;
mailbox_list = NULL;
r = mailimf_display_name_parse(message, length, &cur_token, &display_name);
if (r != MAILIMF_NO_ERROR) {
res = r;
goto err;
}
r = mailimf_colon_parse(message, length, &cur_token);
if (r != MAILIMF_NO_ERROR) {
res = r;
goto free_display_name;
}
r = mailimf_mailbox_list_parse(message, length, &cur_token, &mailbox_list);
switch (r) {
case MAILIMF_NO_ERROR:
break;
case MAILIMF_ERROR_PARSE:
r = mailimf_cfws_parse(message, length, &cur_token);
if ((r != MAILIMF_NO_ERROR) && (r != MAILIMF_ERROR_PARSE)) {
res = r;
goto free_display_name;
}
break;
default:
res = r;
goto free_display_name;
}
r = mailimf_semi_colon_parse(message, length, &cur_token);
if (r != MAILIMF_NO_ERROR) {
res = r;
goto free_mailbox_list;
}
group = mailimf_group_new(display_name, mailbox_list);
if (group == NULL) {
res = MAILIMF_ERROR_MEMORY;
goto free_mailbox_list;
}
* indx = cur_token;
* result = group;
return MAILIMF_NO_ERROR;
free_mailbox_list:
if (mailbox_list != NULL) {
mailimf_mailbox_list_free(mailbox_list);
}
free_display_name:
mailimf_display_name_free(display_name);
err:
return res;
}
Commit Message: Fixed crash #274
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static boolean ReadIPTCProfile(j_decompress_ptr jpeg_info)
{
char
magick[MagickPathExtent];
ErrorManager
*error_manager;
ExceptionInfo
*exception;
Image
*image;
MagickBooleanType
status;
register ssize_t
i;
register unsigned char
*p;
size_t
length;
StringInfo
*iptc_profile,
*profile;
/*
Determine length of binary data stored here.
*/
length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8);
length+=(size_t) GetCharacter(jpeg_info);
length-=2;
if (length <= 14)
{
while (length-- > 0)
if (GetCharacter(jpeg_info) == EOF)
break;
return(TRUE);
}
/*
Validate that this was written as a Photoshop resource format slug.
*/
for (i=0; i < 10; i++)
magick[i]=(char) GetCharacter(jpeg_info);
magick[10]='\0';
length-=10;
if (length <= 10)
return(TRUE);
if (LocaleCompare(magick,"Photoshop ") != 0)
{
/*
Not a IPTC profile, return.
*/
for (i=0; i < (ssize_t) length; i++)
if (GetCharacter(jpeg_info) == EOF)
break;
return(TRUE);
}
/*
Remove the version number.
*/
for (i=0; i < 4; i++)
if (GetCharacter(jpeg_info) == EOF)
break;
if (length <= 11)
return(TRUE);
length-=4;
error_manager=(ErrorManager *) jpeg_info->client_data;
exception=error_manager->exception;
image=error_manager->image;
profile=BlobToStringInfo((const void *) NULL,length);
if (profile == (StringInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
error_manager->profile=profile;
p=GetStringInfoDatum(profile);
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=GetCharacter(jpeg_info);
if (c == EOF)
break;
*p++=(unsigned char) c;
}
error_manager->profile=NULL;
if (i != (ssize_t) length)
{
profile=DestroyStringInfo(profile);
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"InsufficientImageDataInFile","`%s'",
image->filename);
return(FALSE);
}
/* The IPTC profile is actually an 8bim */
iptc_profile=(StringInfo *) GetImageProfile(image,"8bim");
if (iptc_profile != (StringInfo *) NULL)
{
ConcatenateStringInfo(iptc_profile,profile);
profile=DestroyStringInfo(profile);
}
else
{
status=SetImageProfile(image,"8bim",profile,exception);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Profile: iptc, %.20g bytes",(double) length);
return(TRUE);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1641
CWE ID:
Target: 1
Example 2:
Code: static inline unsigned char *read_buf_addr(struct n_tty_data *ldata, size_t i)
{
return &ldata->read_buf[i & (N_TTY_BUF_SIZE - 1)];
}
Commit Message: n_tty: Fix n_tty_write crash when echoing in raw mode
The tty atomic_write_lock does not provide an exclusion guarantee for
the tty driver if the termios settings are LECHO & !OPOST. And since
it is unexpected and not allowed to call TTY buffer helpers like
tty_insert_flip_string concurrently, this may lead to crashes when
concurrect writers call pty_write. In that case the following two
writers:
* the ECHOing from a workqueue and
* pty_write from the process
race and can overflow the corresponding TTY buffer like follows.
If we look into tty_insert_flip_string_fixed_flag, there is:
int space = __tty_buffer_request_room(port, goal, flags);
struct tty_buffer *tb = port->buf.tail;
...
memcpy(char_buf_ptr(tb, tb->used), chars, space);
...
tb->used += space;
so the race of the two can result in something like this:
A B
__tty_buffer_request_room
__tty_buffer_request_room
memcpy(buf(tb->used), ...)
tb->used += space;
memcpy(buf(tb->used), ...) ->BOOM
B's memcpy is past the tty_buffer due to the previous A's tb->used
increment.
Since the N_TTY line discipline input processing can output
concurrently with a tty write, obtain the N_TTY ldisc output_lock to
serialize echo output with normal tty writes. This ensures the tty
buffer helper tty_insert_flip_string is not called concurrently and
everything is fine.
Note that this is nicely reproducible by an ordinary user using
forkpty and some setup around that (raw termios + ECHO). And it is
present in kernels at least after commit
d945cb9cce20ac7143c2de8d88b187f62db99bdc (pty: Rework the pty layer to
use the normal buffering logic) in 2.6.31-rc3.
js: add more info to the commit log
js: switch to bool
js: lock unconditionally
js: lock only the tty->ops->write call
References: CVE-2014-0196
Reported-and-tested-by: Jiri Slaby <[email protected]>
Signed-off-by: Peter Hurley <[email protected]>
Signed-off-by: Jiri Slaby <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Alan Cox <[email protected]>
Cc: <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebContentsImpl::OnFrameDetached(int64 parent_frame_id, int64 frame_id) {
FOR_EACH_OBSERVER(WebContentsObserver, observers_,
FrameDetached(message_source_, frame_id));
FrameTreeNode* parent = FindFrameTreeNodeByID(parent_frame_id);
if (!parent)
return;
parent->RemoveChild(frame_id);
}
Commit Message: Cancel JavaScript dialogs when an interstitial appears.
BUG=295695
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/24360011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@225026 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: char *cJSON_Print( cJSON *item )
{
return print_value( item, 0, 1 );
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: acpi_ns_externalize_name(u32 internal_name_length,
const char *internal_name,
u32 * converted_name_length, char **converted_name)
{
u32 names_index = 0;
u32 num_segments = 0;
u32 required_length;
u32 prefix_length = 0;
u32 i = 0;
u32 j = 0;
ACPI_FUNCTION_TRACE(ns_externalize_name);
if (!internal_name_length || !internal_name || !converted_name) {
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
/* Check for a prefix (one '\' | one or more '^') */
switch (internal_name[0]) {
case AML_ROOT_PREFIX:
prefix_length = 1;
break;
case AML_PARENT_PREFIX:
for (i = 0; i < internal_name_length; i++) {
if (ACPI_IS_PARENT_PREFIX(internal_name[i])) {
prefix_length = i + 1;
} else {
break;
}
}
if (i == internal_name_length) {
prefix_length = i;
}
break;
default:
break;
}
/*
* Check for object names. Note that there could be 0-255 of these
* 4-byte elements.
*/
if (prefix_length < internal_name_length) {
switch (internal_name[prefix_length]) {
case AML_MULTI_NAME_PREFIX_OP:
/* <count> 4-byte names */
names_index = prefix_length + 2;
num_segments = (u8)
internal_name[(acpi_size)prefix_length + 1];
break;
case AML_DUAL_NAME_PREFIX:
/* Two 4-byte names */
names_index = prefix_length + 1;
num_segments = 2;
break;
case 0:
/* null_name */
names_index = 0;
num_segments = 0;
break;
default:
/* one 4-byte name */
names_index = prefix_length;
num_segments = 1;
break;
}
}
/*
* Calculate the length of converted_name, which equals the length
* of the prefix, length of all object names, length of any required
* punctuation ('.') between object names, plus the NULL terminator.
*/
required_length = prefix_length + (4 * num_segments) +
((num_segments > 0) ? (num_segments - 1) : 0) + 1;
/*
* Check to see if we're still in bounds. If not, there's a problem
* with internal_name (invalid format).
*/
if (required_length > internal_name_length) {
ACPI_ERROR((AE_INFO, "Invalid internal name"));
return_ACPI_STATUS(AE_BAD_PATHNAME);
}
/* Build the converted_name */
*converted_name = ACPI_ALLOCATE_ZEROED(required_length);
if (!(*converted_name)) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
j = 0;
for (i = 0; i < prefix_length; i++) {
(*converted_name)[j++] = internal_name[i];
}
if (num_segments > 0) {
for (i = 0; i < num_segments; i++) {
if (i > 0) {
(*converted_name)[j++] = '.';
}
/* Copy and validate the 4-char name segment */
ACPI_MOVE_NAME(&(*converted_name)[j],
&internal_name[names_index]);
acpi_ut_repair_name(&(*converted_name)[j]);
j += ACPI_NAME_SIZE;
names_index += ACPI_NAME_SIZE;
}
}
if (converted_name_length) {
*converted_name_length = (u32) required_length;
}
return_ACPI_STATUS(AE_OK);
}
Commit Message: ACPICA: Namespace: fix operand cache leak
ACPICA commit a23325b2e583556eae88ed3f764e457786bf4df6
I found some ACPI operand cache leaks in ACPI early abort cases.
Boot log of ACPI operand cache leak is as follows:
>[ 0.174332] ACPI: Added _OSI(Module Device)
>[ 0.175504] ACPI: Added _OSI(Processor Device)
>[ 0.176010] ACPI: Added _OSI(3.0 _SCP Extensions)
>[ 0.177032] ACPI: Added _OSI(Processor Aggregator Device)
>[ 0.178284] ACPI: SCI (IRQ16705) allocation failed
>[ 0.179352] ACPI Exception: AE_NOT_ACQUIRED, Unable to install
System Control Interrupt handler (20160930/evevent-131)
>[ 0.180008] ACPI: Unable to start the ACPI Interpreter
>[ 0.181125] ACPI Error: Could not remove SCI handler
(20160930/evmisc-281)
>[ 0.184068] kmem_cache_destroy Acpi-Operand: Slab cache still has
objects
>[ 0.185358] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.10.0-rc3 #2
>[ 0.186820] Hardware name: innotek gmb_h virtual_box/virtual_box, BIOS
virtual_box 12/01/2006
>[ 0.188000] Call Trace:
>[ 0.188000] ? dump_stack+0x5c/0x7d
>[ 0.188000] ? kmem_cache_destroy+0x224/0x230
>[ 0.188000] ? acpi_sleep_proc_init+0x22/0x22
>[ 0.188000] ? acpi_os_delete_cache+0xa/0xd
>[ 0.188000] ? acpi_ut_delete_caches+0x3f/0x7b
>[ 0.188000] ? acpi_terminate+0x5/0xf
>[ 0.188000] ? acpi_init+0x288/0x32e
>[ 0.188000] ? __class_create+0x4c/0x80
>[ 0.188000] ? video_setup+0x7a/0x7a
>[ 0.188000] ? do_one_initcall+0x4e/0x1b0
>[ 0.188000] ? kernel_init_freeable+0x194/0x21a
>[ 0.188000] ? rest_init+0x80/0x80
>[ 0.188000] ? kernel_init+0xa/0x100
>[ 0.188000] ? ret_from_fork+0x25/0x30
When early abort is occurred due to invalid ACPI information, Linux kernel
terminates ACPI by calling acpi_terminate() function. The function calls
acpi_ns_terminate() function to delete namespace data and ACPI operand cache
(acpi_gbl_module_code_list).
But the deletion code in acpi_ns_terminate() function is wrapped in
ACPI_EXEC_APP definition, therefore the code is only executed when the
definition exists. If the define doesn't exist, ACPI operand cache
(acpi_gbl_module_code_list) is leaked, and stack dump is shown in kernel log.
This causes a security threat because the old kernel (<= 4.9) shows memory
locations of kernel functions in stack dump, therefore kernel ASLR can be
neutralized.
To fix ACPI operand leak for enhancing security, I made a patch which
removes the ACPI_EXEC_APP define in acpi_ns_terminate() function for
executing the deletion code unconditionally.
Link: https://github.com/acpica/acpica/commit/a23325b2
Signed-off-by: Seunghun Han <[email protected]>
Signed-off-by: Lv Zheng <[email protected]>
Signed-off-by: Bob Moore <[email protected]>
Signed-off-by: Rafael J. Wysocki <[email protected]>
CWE ID: CWE-755
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: BGD_DECLARE(void) gdImageSaveAlpha (gdImagePtr im, int saveAlphaArg)
{
im->saveAlphaFlag = saveAlphaArg;
}
Commit Message: Fix #340: System frozen
gdImageCreate() doesn't check for oversized images and as such is prone
to DoS vulnerabilities. We fix that by applying the same overflow check
that is already in place for gdImageCreateTrueColor().
CVE-2016-9317
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SocketStreamDispatcherHost::OnSSLCertificateError(
net::SocketStream* socket, const net::SSLInfo& ssl_info, bool fatal) {
int socket_id = SocketStreamHost::SocketIdFromSocketStream(socket);
DVLOG(1) << "SocketStreamDispatcherHost::OnSSLCertificateError socket_id="
<< socket_id;
if (socket_id == content::kNoSocketId) {
LOG(ERROR) << "NoSocketId in OnSSLCertificateError";
return;
}
SocketStreamHost* socket_stream_host = hosts_.Lookup(socket_id);
DCHECK(socket_stream_host);
content::GlobalRequestID request_id(-1, socket_id);
SSLManager::OnSSLCertificateError(ssl_delegate_weak_factory_.GetWeakPtr(),
request_id, ResourceType::SUB_RESOURCE, socket->url(),
render_process_id_, socket_stream_host->render_view_id(), ssl_info,
fatal);
}
Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T>
This change refines r137676.
BUG=122654
TEST=browser_test
Review URL: https://chromiumcodereview.appspot.com/10332233
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: void PushMessagingServiceImpl::OnSendAcknowledged(
const std::string& app_id,
const std::string& message_id) {
NOTREACHED() << "The Push API shouldn't have sent messages upstream";
}
Commit Message: Remove some senseless indirection from the Push API code
Four files to call one Java function. Let's just call it directly.
BUG=
Change-Id: I6e988e9a000051dd7e3dd2b517a33a09afc2fff6
Reviewed-on: https://chromium-review.googlesource.com/749147
Reviewed-by: Anita Woodruff <[email protected]>
Commit-Queue: Peter Beverloo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#513464}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void snd_timer_user_ccallback(struct snd_timer_instance *timeri,
int event,
struct timespec *tstamp,
unsigned long resolution)
{
struct snd_timer_user *tu = timeri->callback_data;
struct snd_timer_tread r1;
unsigned long flags;
if (event >= SNDRV_TIMER_EVENT_START &&
event <= SNDRV_TIMER_EVENT_PAUSE)
tu->tstamp = *tstamp;
if ((tu->filter & (1 << event)) == 0 || !tu->tread)
return;
r1.event = event;
r1.tstamp = *tstamp;
r1.val = resolution;
spin_lock_irqsave(&tu->qlock, flags);
snd_timer_user_append_to_tqueue(tu, &r1);
spin_unlock_irqrestore(&tu->qlock, flags);
kill_fasync(&tu->fasync, SIGIO, POLL_IN);
wake_up(&tu->qchange_sleep);
}
Commit Message: ALSA: timer: Fix leak in events via snd_timer_user_ccallback
The stack object “r1” has a total size of 32 bytes. Its field
“event” and “val” both contain 4 bytes padding. These 8 bytes
padding bytes are sent to user without being initialized.
Signed-off-by: Kangjie Lu <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void TestingPlatformSupport::cryptographicallyRandomValues(unsigned char* buffer, size_t length)
{
}
Commit Message: Add assertions that the empty Platform::cryptographicallyRandomValues() overrides are not being used.
These implementations are not safe and look scary if not accompanied by an assertion. Also one of the comments was incorrect.
BUG=552749
Review URL: https://codereview.chromium.org/1419293005
Cr-Commit-Position: refs/heads/master@{#359229}
CWE ID: CWE-310
Target: 1
Example 2:
Code: static int macvlan_broadcast_one(struct sk_buff *skb,
const struct macvlan_dev *vlan,
const struct ethhdr *eth, bool local)
{
struct net_device *dev = vlan->dev;
if (!skb)
return NET_RX_DROP;
if (local)
return vlan->forward(dev, skb);
skb->dev = dev;
if (!compare_ether_addr_64bits(eth->h_dest,
dev->broadcast))
skb->pkt_type = PACKET_BROADCAST;
else
skb->pkt_type = PACKET_MULTICAST;
return vlan->receive(skb);
}
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
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virtual void SetUp() {
InitializeConfig();
SetMode(GET_PARAM(1));
set_cpu_used_ = GET_PARAM(2);
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SoftAMR::onQueueFilled(OMX_U32 /* portIndex */) {
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
while (!inQueue.empty() && !outQueue.empty()) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
return;
}
if (inHeader->nOffset == 0) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumSamplesOutput = 0;
}
const uint8_t *inputPtr = inHeader->pBuffer + inHeader->nOffset;
int32_t numBytesRead;
if (mMode == MODE_NARROW) {
numBytesRead =
AMRDecode(mState,
(Frame_Type_3GPP)((inputPtr[0] >> 3) & 0x0f),
(UWord8 *)&inputPtr[1],
reinterpret_cast<int16_t *>(outHeader->pBuffer),
MIME_IETF);
if (numBytesRead == -1) {
ALOGE("PV AMR decoder AMRDecode() call failed");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
++numBytesRead; // Include the frame type header byte.
if (static_cast<size_t>(numBytesRead) > inHeader->nFilledLen) {
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
} else {
int16 mode = ((inputPtr[0] >> 3) & 0x0f);
if (mode >= 10 && mode <= 13) {
ALOGE("encountered illegal frame type %d in AMR WB content.",
mode);
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
size_t frameSize = getFrameSize(mode);
CHECK_GE(inHeader->nFilledLen, frameSize);
int16_t *outPtr = (int16_t *)outHeader->pBuffer;
if (mode >= 9) {
memset(outPtr, 0, kNumSamplesPerFrameWB * sizeof(int16_t));
} else if (mode < 9) {
int16 frameType;
RX_State_wb rx_state;
mime_unsorting(
const_cast<uint8_t *>(&inputPtr[1]),
mInputSampleBuffer,
&frameType, &mode, 1, &rx_state);
int16_t numSamplesOutput;
pvDecoder_AmrWb(
mode, mInputSampleBuffer,
outPtr,
&numSamplesOutput,
mDecoderBuf, frameType, mDecoderCookie);
CHECK_EQ((int)numSamplesOutput, (int)kNumSamplesPerFrameWB);
for (int i = 0; i < kNumSamplesPerFrameWB; ++i) {
/* Delete the 2 LSBs (14-bit output) */
outPtr[i] &= 0xfffC;
}
}
numBytesRead = frameSize;
}
inHeader->nOffset += numBytesRead;
inHeader->nFilledLen -= numBytesRead;
outHeader->nFlags = 0;
outHeader->nOffset = 0;
if (mMode == MODE_NARROW) {
outHeader->nFilledLen = kNumSamplesPerFrameNB * sizeof(int16_t);
outHeader->nTimeStamp =
mAnchorTimeUs
+ (mNumSamplesOutput * 1000000ll) / kSampleRateNB;
mNumSamplesOutput += kNumSamplesPerFrameNB;
} else {
outHeader->nFilledLen = kNumSamplesPerFrameWB * sizeof(int16_t);
outHeader->nTimeStamp =
mAnchorTimeUs
+ (mNumSamplesOutput * 1000000ll) / kSampleRateWB;
mNumSamplesOutput += kNumSamplesPerFrameWB;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
++mInputBufferCount;
}
}
Commit Message: SoftAMR: check output buffer size to avoid overflow.
Bug: 27662364
Change-Id: I7b26892c41d6f2e690e77478ab855c2fed1ff6b0
CWE ID: CWE-264
Target: 1
Example 2:
Code: void RenderFrameHostImpl::ProcessBeforeUnloadACK(
bool proceed,
bool treat_as_final_ack,
const base::TimeTicks& renderer_before_unload_start_time,
const base::TimeTicks& renderer_before_unload_end_time) {
TRACE_EVENT_ASYNC_END1("navigation", "RenderFrameHostImpl BeforeUnload", this,
"FrameTreeNode id",
frame_tree_node_->frame_tree_node_id());
RenderFrameHostImpl* initiator = GetBeforeUnloadInitiator();
if (!initiator)
return;
initiator->ProcessBeforeUnloadACKFromFrame(
proceed, treat_as_final_ack, this, false /* is_frame_being_destroyed */,
renderer_before_unload_start_time, renderer_before_unload_end_time);
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#653137}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info,
NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception)
{
MagickOffsetType
count,
offset;
MagickSizeType
extent,
length;
register const PixelPacket
*magick_restrict p;
register ssize_t
y;
size_t
rows;
if (nexus_info->authentic_pixel_cache != MagickFalse)
return(MagickTrue);
offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+
nexus_info->region.x;
length=(MagickSizeType) nexus_info->region.width*sizeof(PixelPacket);
rows=nexus_info->region.height;
extent=length*rows;
p=nexus_info->pixels;
y=0;
switch (cache_info->type)
{
case MemoryCache:
case MapCache:
{
register PixelPacket
*magick_restrict q;
/*
Write pixels to memory.
*/
if ((cache_info->columns == nexus_info->region.width) &&
(extent == (MagickSizeType) ((size_t) extent)))
{
length=extent;
rows=1UL;
}
q=cache_info->pixels+offset;
for (y=0; y < (ssize_t) rows; y++)
{
(void) memcpy(q,p,(size_t) length);
p+=nexus_info->region.width;
q+=cache_info->columns;
}
break;
}
case DiskCache:
{
/*
Write pixels to disk.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
cache_info->cache_filename);
UnlockSemaphoreInfo(cache_info->file_semaphore);
return(MagickFalse);
}
if ((cache_info->columns == nexus_info->region.width) &&
(extent <= MagickMaxBufferExtent))
{
length=extent;
rows=1UL;
}
for (y=0; y < (ssize_t) rows; y++)
{
count=WritePixelCacheRegion(cache_info,cache_info->offset+offset*
sizeof(*p),length,(const unsigned char *) p);
if ((MagickSizeType) count < length)
break;
p+=nexus_info->region.width;
offset+=cache_info->columns;
}
if (IsFileDescriptorLimitExceeded() != MagickFalse)
(void) ClosePixelCacheOnDisk(cache_info);
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
case DistributedCache:
{
RectangleInfo
region;
/*
Write pixels to distributed cache.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
region=nexus_info->region;
if ((cache_info->columns != nexus_info->region.width) ||
(extent > MagickMaxBufferExtent))
region.height=1UL;
else
{
length=extent;
rows=1UL;
}
for (y=0; y < (ssize_t) rows; y++)
{
count=WriteDistributePixelCachePixels((DistributeCacheInfo *)
cache_info->server_info,®ion,length,(const unsigned char *) p);
if (count != (MagickOffsetType) length)
break;
p+=nexus_info->region.width;
region.y++;
}
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
default:
break;
}
if (y < (ssize_t) rows)
{
ThrowFileException(exception,CacheError,"UnableToWritePixelCache",
cache_info->cache_filename);
return(MagickFalse);
}
if ((cache_info->debug != MagickFalse) &&
(CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse))
(void) LogMagickEvent(CacheEvent,GetMagickModule(),
"%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double)
nexus_info->region.width,(double) nexus_info->region.height,(double)
nexus_info->region.x,(double) nexus_info->region.y);
return(MagickTrue);
}
Commit Message: http://www.imagemagick.org/discourse-server/viewtopic.php?f=2&t=28946
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void FrameLoader::StartNavigation(const FrameLoadRequest& passed_request,
WebFrameLoadType frame_load_type,
NavigationPolicy policy) {
CHECK(!IsBackForwardLoadType(frame_load_type));
DCHECK(passed_request.TriggeringEventInfo() !=
WebTriggeringEventInfo::kUnknown);
DCHECK(frame_->GetDocument());
if (HTMLFrameOwnerElement* element = frame_->DeprecatedLocalOwner())
element->CancelPendingLazyLoad();
if (in_stop_all_loaders_)
return;
FrameLoadRequest request(passed_request);
ResourceRequest& resource_request = request.GetResourceRequest();
const KURL& url = resource_request.Url();
Document* origin_document = request.OriginDocument();
resource_request.SetHasUserGesture(
LocalFrame::HasTransientUserActivation(frame_));
if (!PrepareRequestForThisFrame(request))
return;
Frame* target_frame =
request.Form() ? nullptr
: frame_->FindFrameForNavigation(
AtomicString(request.FrameName()), *frame_, url);
bool should_navigate_target_frame = policy == kNavigationPolicyCurrentTab;
if (target_frame && target_frame != frame_ && should_navigate_target_frame) {
if (target_frame->IsLocalFrame() &&
!ToLocalFrame(target_frame)->IsNavigationAllowed()) {
return;
}
bool was_in_same_page = target_frame->GetPage() == frame_->GetPage();
request.SetFrameName("_self");
target_frame->Navigate(request, frame_load_type);
Page* page = target_frame->GetPage();
if (!was_in_same_page && page)
page->GetChromeClient().Focus(frame_);
return;
}
SetReferrerForFrameRequest(request);
if (!target_frame && !request.FrameName().IsEmpty()) {
if (policy == kNavigationPolicyDownload) {
Client()->DownloadURL(resource_request,
DownloadCrossOriginRedirects::kFollow);
return; // Navigation/download will be handled by the client.
} else if (should_navigate_target_frame) {
resource_request.SetFrameType(
network::mojom::RequestContextFrameType::kAuxiliary);
CreateWindowForRequest(request, *frame_);
return; // Navigation will be handled by the new frame/window.
}
}
if (!frame_->IsNavigationAllowed() ||
frame_->GetDocument()->PageDismissalEventBeingDispatched() !=
Document::kNoDismissal) {
return;
}
frame_load_type = DetermineFrameLoadType(resource_request, origin_document,
KURL(), frame_load_type);
bool same_document_navigation =
policy == kNavigationPolicyCurrentTab &&
ShouldPerformFragmentNavigation(
request.Form(), resource_request.HttpMethod(), frame_load_type, url);
if (same_document_navigation) {
CommitSameDocumentNavigation(
url, frame_load_type, nullptr, request.ClientRedirect(),
origin_document,
request.TriggeringEventInfo() != WebTriggeringEventInfo::kNotFromEvent,
nullptr /* extra_data */);
return;
}
WebNavigationType navigation_type = DetermineNavigationType(
frame_load_type, resource_request.HttpBody() || request.Form(),
request.TriggeringEventInfo() != WebTriggeringEventInfo::kNotFromEvent);
resource_request.SetRequestContext(
DetermineRequestContextFromNavigationType(navigation_type));
resource_request.SetFrameType(
frame_->IsMainFrame() ? network::mojom::RequestContextFrameType::kTopLevel
: network::mojom::RequestContextFrameType::kNested);
mojom::blink::NavigationInitiatorPtr navigation_initiator;
if (origin_document && origin_document->GetContentSecurityPolicy()
->ExperimentalFeaturesEnabled()) {
WebContentSecurityPolicyList initiator_csp =
origin_document->GetContentSecurityPolicy()
->ExposeForNavigationalChecks();
resource_request.SetInitiatorCSP(initiator_csp);
auto request = mojo::MakeRequest(&navigation_initiator);
origin_document->BindNavigationInitiatorRequest(std::move(request));
}
RecordLatestRequiredCSP();
ModifyRequestForCSP(resource_request, origin_document);
DCHECK(Client()->HasWebView());
if (url.PotentiallyDanglingMarkup() && url.ProtocolIsInHTTPFamily()) {
Deprecation::CountDeprecation(
frame_, WebFeature::kCanRequestURLHTTPContainingNewline);
return;
}
bool has_transient_activation =
LocalFrame::HasTransientUserActivation(frame_);
if (frame_->IsMainFrame() && origin_document &&
frame_->GetPage() == origin_document->GetPage()) {
LocalFrame::ConsumeTransientUserActivation(frame_);
}
Client()->BeginNavigation(
resource_request, origin_document, nullptr /* document_loader */,
navigation_type, policy, has_transient_activation, frame_load_type,
request.ClientRedirect() == ClientRedirectPolicy::kClientRedirect,
request.TriggeringEventInfo(), request.Form(),
request.ShouldCheckMainWorldContentSecurityPolicy(),
request.GetBlobURLToken(), request.GetInputStartTime(),
request.HrefTranslate().GetString(), std::move(navigation_initiator));
}
Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener
Spec PR: https://github.com/w3c/webappsec-csp/pull/358
Bug: 905301, 894228, 836148
Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a
Reviewed-on: https://chromium-review.googlesource.com/c/1314633
Commit-Queue: Andy Paicu <[email protected]>
Reviewed-by: Mike West <[email protected]>
Cr-Commit-Position: refs/heads/master@{#610850}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int usb_parse_endpoint(struct device *ddev, int cfgno, int inum,
int asnum, struct usb_host_interface *ifp, int num_ep,
unsigned char *buffer, int size)
{
unsigned char *buffer0 = buffer;
struct usb_endpoint_descriptor *d;
struct usb_host_endpoint *endpoint;
int n, i, j, retval;
unsigned int maxp;
const unsigned short *maxpacket_maxes;
d = (struct usb_endpoint_descriptor *) buffer;
buffer += d->bLength;
size -= d->bLength;
if (d->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE)
n = USB_DT_ENDPOINT_AUDIO_SIZE;
else if (d->bLength >= USB_DT_ENDPOINT_SIZE)
n = USB_DT_ENDPOINT_SIZE;
else {
dev_warn(ddev, "config %d interface %d altsetting %d has an "
"invalid endpoint descriptor of length %d, skipping\n",
cfgno, inum, asnum, d->bLength);
goto skip_to_next_endpoint_or_interface_descriptor;
}
i = d->bEndpointAddress & ~USB_ENDPOINT_DIR_MASK;
if (i >= 16 || i == 0) {
dev_warn(ddev, "config %d interface %d altsetting %d has an "
"invalid endpoint with address 0x%X, skipping\n",
cfgno, inum, asnum, d->bEndpointAddress);
goto skip_to_next_endpoint_or_interface_descriptor;
}
/* Only store as many endpoints as we have room for */
if (ifp->desc.bNumEndpoints >= num_ep)
goto skip_to_next_endpoint_or_interface_descriptor;
/* Check for duplicate endpoint addresses */
for (i = 0; i < ifp->desc.bNumEndpoints; ++i) {
if (ifp->endpoint[i].desc.bEndpointAddress ==
d->bEndpointAddress) {
dev_warn(ddev, "config %d interface %d altsetting %d has a duplicate endpoint with address 0x%X, skipping\n",
cfgno, inum, asnum, d->bEndpointAddress);
goto skip_to_next_endpoint_or_interface_descriptor;
}
}
endpoint = &ifp->endpoint[ifp->desc.bNumEndpoints];
++ifp->desc.bNumEndpoints;
memcpy(&endpoint->desc, d, n);
INIT_LIST_HEAD(&endpoint->urb_list);
/*
* Fix up bInterval values outside the legal range.
* Use 10 or 8 ms if no proper value can be guessed.
*/
i = 0; /* i = min, j = max, n = default */
j = 255;
if (usb_endpoint_xfer_int(d)) {
i = 1;
switch (to_usb_device(ddev)->speed) {
case USB_SPEED_SUPER_PLUS:
case USB_SPEED_SUPER:
case USB_SPEED_HIGH:
/*
* Many device manufacturers are using full-speed
* bInterval values in high-speed interrupt endpoint
* descriptors. Try to fix those and fall back to an
* 8-ms default value otherwise.
*/
n = fls(d->bInterval*8);
if (n == 0)
n = 7; /* 8 ms = 2^(7-1) uframes */
j = 16;
/*
* Adjust bInterval for quirked devices.
*/
/*
* This quirk fixes bIntervals reported in ms.
*/
if (to_usb_device(ddev)->quirks &
USB_QUIRK_LINEAR_FRAME_INTR_BINTERVAL) {
n = clamp(fls(d->bInterval) + 3, i, j);
i = j = n;
}
/*
* This quirk fixes bIntervals reported in
* linear microframes.
*/
if (to_usb_device(ddev)->quirks &
USB_QUIRK_LINEAR_UFRAME_INTR_BINTERVAL) {
n = clamp(fls(d->bInterval), i, j);
i = j = n;
}
break;
default: /* USB_SPEED_FULL or _LOW */
/*
* For low-speed, 10 ms is the official minimum.
* But some "overclocked" devices might want faster
* polling so we'll allow it.
*/
n = 10;
break;
}
} else if (usb_endpoint_xfer_isoc(d)) {
i = 1;
j = 16;
switch (to_usb_device(ddev)->speed) {
case USB_SPEED_HIGH:
n = 7; /* 8 ms = 2^(7-1) uframes */
break;
default: /* USB_SPEED_FULL */
n = 4; /* 8 ms = 2^(4-1) frames */
break;
}
}
if (d->bInterval < i || d->bInterval > j) {
dev_warn(ddev, "config %d interface %d altsetting %d "
"endpoint 0x%X has an invalid bInterval %d, "
"changing to %d\n",
cfgno, inum, asnum,
d->bEndpointAddress, d->bInterval, n);
endpoint->desc.bInterval = n;
}
/* Some buggy low-speed devices have Bulk endpoints, which is
* explicitly forbidden by the USB spec. In an attempt to make
* them usable, we will try treating them as Interrupt endpoints.
*/
if (to_usb_device(ddev)->speed == USB_SPEED_LOW &&
usb_endpoint_xfer_bulk(d)) {
dev_warn(ddev, "config %d interface %d altsetting %d "
"endpoint 0x%X is Bulk; changing to Interrupt\n",
cfgno, inum, asnum, d->bEndpointAddress);
endpoint->desc.bmAttributes = USB_ENDPOINT_XFER_INT;
endpoint->desc.bInterval = 1;
if (usb_endpoint_maxp(&endpoint->desc) > 8)
endpoint->desc.wMaxPacketSize = cpu_to_le16(8);
}
/* Validate the wMaxPacketSize field */
maxp = usb_endpoint_maxp(&endpoint->desc);
/* Find the highest legal maxpacket size for this endpoint */
i = 0; /* additional transactions per microframe */
switch (to_usb_device(ddev)->speed) {
case USB_SPEED_LOW:
maxpacket_maxes = low_speed_maxpacket_maxes;
break;
case USB_SPEED_FULL:
maxpacket_maxes = full_speed_maxpacket_maxes;
break;
case USB_SPEED_HIGH:
/* Bits 12..11 are allowed only for HS periodic endpoints */
if (usb_endpoint_xfer_int(d) || usb_endpoint_xfer_isoc(d)) {
i = maxp & (BIT(12) | BIT(11));
maxp &= ~i;
}
/* fallthrough */
default:
maxpacket_maxes = high_speed_maxpacket_maxes;
break;
case USB_SPEED_SUPER:
case USB_SPEED_SUPER_PLUS:
maxpacket_maxes = super_speed_maxpacket_maxes;
break;
}
j = maxpacket_maxes[usb_endpoint_type(&endpoint->desc)];
if (maxp > j) {
dev_warn(ddev, "config %d interface %d altsetting %d endpoint 0x%X has invalid maxpacket %d, setting to %d\n",
cfgno, inum, asnum, d->bEndpointAddress, maxp, j);
maxp = j;
endpoint->desc.wMaxPacketSize = cpu_to_le16(i | maxp);
}
/*
* Some buggy high speed devices have bulk endpoints using
* maxpacket sizes other than 512. High speed HCDs may not
* be able to handle that particular bug, so let's warn...
*/
if (to_usb_device(ddev)->speed == USB_SPEED_HIGH
&& usb_endpoint_xfer_bulk(d)) {
if (maxp != 512)
dev_warn(ddev, "config %d interface %d altsetting %d "
"bulk endpoint 0x%X has invalid maxpacket %d\n",
cfgno, inum, asnum, d->bEndpointAddress,
maxp);
}
/* Parse a possible SuperSpeed endpoint companion descriptor */
if (to_usb_device(ddev)->speed >= USB_SPEED_SUPER)
usb_parse_ss_endpoint_companion(ddev, cfgno,
inum, asnum, endpoint, buffer, size);
/* Skip over any Class Specific or Vendor Specific descriptors;
* find the next endpoint or interface descriptor */
endpoint->extra = buffer;
i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
USB_DT_INTERFACE, &n);
endpoint->extralen = i;
retval = buffer - buffer0 + i;
if (n > 0)
dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
n, plural(n), "endpoint");
return retval;
skip_to_next_endpoint_or_interface_descriptor:
i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
USB_DT_INTERFACE, NULL);
return buffer - buffer0 + i;
}
Commit Message: USB: core: fix out-of-bounds access bug in usb_get_bos_descriptor()
Andrey used the syzkaller fuzzer to find an out-of-bounds memory
access in usb_get_bos_descriptor(). The code wasn't checking that the
next usb_dev_cap_header structure could fit into the remaining buffer
space.
This patch fixes the error and also reduces the bNumDeviceCaps field
in the header to match the actual number of capabilities found, in
cases where there are fewer than expected.
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: Alan Stern <[email protected]>
Tested-by: Andrey Konovalov <[email protected]>
CC: <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int key_unlink(struct key *keyring, struct key *key)
{
struct assoc_array_edit *edit;
int ret;
key_check(keyring);
key_check(key);
if (keyring->type != &key_type_keyring)
return -ENOTDIR;
down_write(&keyring->sem);
edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops,
&key->index_key);
if (IS_ERR(edit)) {
ret = PTR_ERR(edit);
goto error;
}
ret = -ENOENT;
if (edit == NULL)
goto error;
assoc_array_apply_edit(edit);
key_payload_reserve(keyring, keyring->datalen - KEYQUOTA_LINK_BYTES);
ret = 0;
error:
up_write(&keyring->sem);
return ret;
}
Commit Message: KEYS: ensure we free the assoc array edit if edit is valid
__key_link_end is not freeing the associated array edit structure
and this leads to a 512 byte memory leak each time an identical
existing key is added with add_key().
The reason the add_key() system call returns okay is that
key_create_or_update() calls __key_link_begin() before checking to see
whether it can update a key directly rather than adding/replacing - which
it turns out it can. Thus __key_link() is not called through
__key_instantiate_and_link() and __key_link_end() must cancel the edit.
CVE-2015-1333
Signed-off-by: Colin Ian King <[email protected]>
Signed-off-by: David Howells <[email protected]>
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ResourceDispatcherHostImpl::ResourceDispatcherHostImpl()
: download_file_manager_(new DownloadFileManager(NULL)),
save_file_manager_(new SaveFileManager()),
request_id_(-1),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(ssl_delegate_weak_factory_(this)),
is_shutdown_(false),
max_outstanding_requests_cost_per_process_(
kMaxOutstandingRequestsCostPerProcess),
filter_(NULL),
delegate_(NULL),
allow_cross_origin_auth_prompt_(false) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!g_resource_dispatcher_host);
g_resource_dispatcher_host = this;
GetContentClient()->browser()->ResourceDispatcherHostCreated();
ANNOTATE_BENIGN_RACE(
&last_user_gesture_time_,
"We don't care about the precise value, see http://crbug.com/92889");
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&appcache::AppCacheInterceptor::EnsureRegistered));
update_load_states_timer_.reset(
new base::RepeatingTimer<ResourceDispatcherHostImpl>());
}
Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T>
This change refines r137676.
BUG=122654
TEST=browser_test
Review URL: https://chromiumcodereview.appspot.com/10332233
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool ExecuteScriptWithoutUserGestureAndExtractString(
const ToRenderFrameHost& adapter,
const std::string& script,
std::string* result) {
DCHECK(result);
std::unique_ptr<base::Value> value;
return ExecuteScriptHelper(adapter.render_frame_host(), script, false,
&value) &&
value && value->GetAsString(result);
}
Commit Message: Apply ExtensionNavigationThrottle filesystem/blob checks to all frames.
BUG=836858
Change-Id: I34333a72501129fd40b5a9aa6378c9f35f1e7fc2
Reviewed-on: https://chromium-review.googlesource.com/1028511
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Alex Moshchuk <[email protected]>
Reviewed-by: Nick Carter <[email protected]>
Commit-Queue: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#553867}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: chpass_principal_2_svc(chpass_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) {
ret.code = chpass_principal_wrapper_3((void *)handle, arg->princ,
FALSE, 0, NULL, arg->pass);
} else if (!(CHANGEPW_SERVICE(rqstp)) &&
kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_CHANGEPW, arg->princ, NULL)) {
ret.code = kadm5_chpass_principal((void *)handle, arg->princ,
arg->pass);
} else {
log_unauth("kadm5_chpass_principal", prime_arg,
&client_name, &service_name, rqstp);
ret.code = KADM5_AUTH_CHANGEPW;
}
if (ret.code != KADM5_AUTH_CHANGEPW) {
if (ret.code != 0)
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_chpass_principal", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: decode_bundle(bool load, const struct nx_action_bundle *nab,
const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap,
struct ofpbuf *ofpacts)
{
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
struct ofpact_bundle *bundle;
uint32_t slave_type;
size_t slaves_size, i;
enum ofperr error;
bundle = ofpact_put_BUNDLE(ofpacts);
bundle->n_slaves = ntohs(nab->n_slaves);
bundle->basis = ntohs(nab->basis);
bundle->fields = ntohs(nab->fields);
bundle->algorithm = ntohs(nab->algorithm);
slave_type = ntohl(nab->slave_type);
slaves_size = ntohs(nab->len) - sizeof *nab;
error = OFPERR_OFPBAC_BAD_ARGUMENT;
if (!flow_hash_fields_valid(bundle->fields)) {
VLOG_WARN_RL(&rl, "unsupported fields %d", (int) bundle->fields);
} else if (bundle->n_slaves > BUNDLE_MAX_SLAVES) {
VLOG_WARN_RL(&rl, "too many slaves");
} else if (bundle->algorithm != NX_BD_ALG_HRW
&& bundle->algorithm != NX_BD_ALG_ACTIVE_BACKUP) {
VLOG_WARN_RL(&rl, "unsupported algorithm %d", (int) bundle->algorithm);
} else if (slave_type != mf_nxm_header(MFF_IN_PORT)) {
VLOG_WARN_RL(&rl, "unsupported slave type %"PRIu16, slave_type);
} else {
error = 0;
}
if (!is_all_zeros(nab->zero, sizeof nab->zero)) {
VLOG_WARN_RL(&rl, "reserved field is nonzero");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
if (load) {
bundle->dst.ofs = nxm_decode_ofs(nab->ofs_nbits);
bundle->dst.n_bits = nxm_decode_n_bits(nab->ofs_nbits);
error = mf_vl_mff_mf_from_nxm_header(ntohl(nab->dst), vl_mff_map,
&bundle->dst.field, tlv_bitmap);
if (error) {
return error;
}
if (bundle->dst.n_bits < 16) {
VLOG_WARN_RL(&rl, "bundle_load action requires at least 16 bit "
"destination.");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
} else {
if (nab->ofs_nbits || nab->dst) {
VLOG_WARN_RL(&rl, "bundle action has nonzero reserved fields");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
}
if (slaves_size < bundle->n_slaves * sizeof(ovs_be16)) {
VLOG_WARN_RL(&rl, "Nicira action %s only has %"PRIuSIZE" bytes "
"allocated for slaves. %"PRIuSIZE" bytes are required "
"for %"PRIu16" slaves.",
load ? "bundle_load" : "bundle", slaves_size,
bundle->n_slaves * sizeof(ovs_be16), bundle->n_slaves);
error = OFPERR_OFPBAC_BAD_LEN;
}
for (i = 0; i < bundle->n_slaves; i++) {
ofp_port_t ofp_port = u16_to_ofp(ntohs(((ovs_be16 *)(nab + 1))[i]));
ofpbuf_put(ofpacts, &ofp_port, sizeof ofp_port);
bundle = ofpacts->header;
}
ofpact_finish_BUNDLE(ofpacts, &bundle);
if (!error) {
error = bundle_check(bundle, OFPP_MAX, NULL);
}
return error;
}
Commit Message: ofp-actions: Avoid buffer overread in BUNDLE action decoding.
Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9052
Signed-off-by: Ben Pfaff <[email protected]>
Acked-by: Justin Pettit <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: ChromeContentBrowserClient::ChromeContentBrowserClient(
ChromeFeatureListCreator* chrome_feature_list_creator)
: chrome_feature_list_creator_(chrome_feature_list_creator),
weak_factory_(this) {
#if BUILDFLAG(ENABLE_PLUGINS)
for (size_t i = 0; i < base::size(kPredefinedAllowedDevChannelOrigins); ++i)
allowed_dev_channel_origins_.insert(kPredefinedAllowedDevChannelOrigins[i]);
for (size_t i = 0; i < base::size(kPredefinedAllowedFileHandleOrigins); ++i)
allowed_file_handle_origins_.insert(kPredefinedAllowedFileHandleOrigins[i]);
for (size_t i = 0; i < base::size(kPredefinedAllowedSocketOrigins); ++i)
allowed_socket_origins_.insert(kPredefinedAllowedSocketOrigins[i]);
extra_parts_.push_back(new ChromeContentBrowserClientPluginsPart);
#endif
#if defined(OS_CHROMEOS)
extra_parts_.push_back(new ChromeContentBrowserClientChromeOsPart);
#endif // defined(OS_CHROMEOS)
#if BUILDFLAG(ENABLE_EXTENSIONS)
extra_parts_.push_back(new ChromeContentBrowserClientExtensionsPart);
#endif
gpu_binder_registry_.AddInterface(
base::Bind(&metrics::CallStackProfileCollector::Create));
}
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155}
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void __ip_vs_del_service(struct ip_vs_service *svc)
{
struct ip_vs_dest *dest, *nxt;
struct ip_vs_scheduler *old_sched;
struct ip_vs_pe *old_pe;
struct netns_ipvs *ipvs = net_ipvs(svc->net);
pr_info("%s: enter\n", __func__);
/* Count only IPv4 services for old get/setsockopt interface */
if (svc->af == AF_INET)
ipvs->num_services--;
ip_vs_stop_estimator(svc->net, &svc->stats);
/* Unbind scheduler */
old_sched = svc->scheduler;
ip_vs_unbind_scheduler(svc);
ip_vs_scheduler_put(old_sched);
/* Unbind persistence engine */
old_pe = svc->pe;
ip_vs_unbind_pe(svc);
ip_vs_pe_put(old_pe);
/* Unbind app inc */
if (svc->inc) {
ip_vs_app_inc_put(svc->inc);
svc->inc = NULL;
}
/*
* Unlink the whole destination list
*/
list_for_each_entry_safe(dest, nxt, &svc->destinations, n_list) {
__ip_vs_unlink_dest(svc, dest, 0);
__ip_vs_del_dest(svc->net, dest);
}
/*
* Update the virtual service counters
*/
if (svc->port == FTPPORT)
atomic_dec(&ipvs->ftpsvc_counter);
else if (svc->port == 0)
atomic_dec(&ipvs->nullsvc_counter);
/*
* Free the service if nobody refers to it
*/
if (atomic_read(&svc->refcnt) == 0) {
IP_VS_DBG_BUF(3, "Removing service %u/%s:%u usecnt=%d\n",
svc->fwmark,
IP_VS_DBG_ADDR(svc->af, &svc->addr),
ntohs(svc->port), atomic_read(&svc->usecnt));
free_percpu(svc->stats.cpustats);
kfree(svc);
}
/* decrease the module use count */
ip_vs_use_count_dec();
}
Commit Message: ipvs: fix info leak in getsockopt(IP_VS_SO_GET_TIMEOUT)
If at least one of CONFIG_IP_VS_PROTO_TCP or CONFIG_IP_VS_PROTO_UDP is
not set, __ip_vs_get_timeouts() does not fully initialize the structure
that gets copied to userland and that for leaks up to 12 bytes of kernel
stack. Add an explicit memset(0) before passing the structure to
__ip_vs_get_timeouts() to avoid the info leak.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Wensong Zhang <[email protected]>
Cc: Simon Horman <[email protected]>
Cc: Julian Anastasov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static size_t optsize (lua_State *L, char opt, const char **fmt) {
switch (opt) {
case 'B': case 'b': return sizeof(char);
case 'H': case 'h': return sizeof(short);
case 'L': case 'l': return sizeof(long);
case 'T': return sizeof(size_t);
case 'f': return sizeof(float);
case 'd': return sizeof(double);
case 'x': return 1;
case 'c': return getnum(L, fmt, 1);
case 'i': case 'I': {
int sz = getnum(L, fmt, sizeof(int));
if (sz > MAXINTSIZE)
luaL_error(L, "integral size %d is larger than limit of %d",
sz, MAXINTSIZE);
return sz;
}
default: return 0; /* other cases do not need alignment */
}
}
Commit Message: Security: update Lua struct package for security.
During an auditing Apple found that the "struct" Lua package
we ship with Redis (http://www.inf.puc-rio.br/~roberto/struct/) contains
a security problem. A bound-checking statement fails because of integer
overflow. The bug exists since we initially integrated this package with
Lua, when scripting was introduced, so every version of Redis with
EVAL/EVALSHA capabilities exposed is affected.
Instead of just fixing the bug, the library was updated to the latest
version shipped by the author.
CWE ID: CWE-190
Target: 1
Example 2:
Code: static int ap_init_queue(ap_qid_t qid)
{
struct ap_queue_status status;
int rc, dummy, i;
rc = -ENODEV;
status = ap_reset_queue(qid);
for (i = 0; i < AP_MAX_RESET; i++) {
switch (status.response_code) {
case AP_RESPONSE_NORMAL:
if (status.queue_empty)
rc = 0;
break;
case AP_RESPONSE_Q_NOT_AVAIL:
case AP_RESPONSE_DECONFIGURED:
case AP_RESPONSE_CHECKSTOPPED:
i = AP_MAX_RESET; /* return with -ENODEV */
break;
case AP_RESPONSE_RESET_IN_PROGRESS:
rc = -EBUSY;
case AP_RESPONSE_BUSY:
default:
break;
}
if (rc != -ENODEV && rc != -EBUSY)
break;
if (i < AP_MAX_RESET - 1) {
/* Time we are waiting until we give up (0.7sec * 90).
* Since the actual request (in progress) will not
* interrupted immediately for the reset command,
* we have to be patient. In worst case we have to
* wait 60sec + reset time (some msec).
*/
schedule_timeout(AP_RESET_TIMEOUT);
status = ap_test_queue(qid, &dummy, &dummy);
}
}
if (rc == 0 && ap_using_interrupts()) {
rc = ap_queue_enable_interruption(qid, ap_airq.lsi_ptr);
/* If interruption mode is supported by the machine,
* but an AP can not be enabled for interruption then
* the AP will be discarded. */
if (rc)
pr_err("Registering adapter interrupts for "
"AP %d failed\n", AP_QID_DEVICE(qid));
}
return rc;
}
Commit Message: crypto: prefix module autoloading with "crypto-"
This prefixes all crypto module loading with "crypto-" so we never run
the risk of exposing module auto-loading to userspace via a crypto API,
as demonstrated by Mathias Krause:
https://lkml.org/lkml/2013/3/4/70
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int pgx_getuint32(jas_stream_t *in, uint_fast32_t *val)
{
int c;
uint_fast32_t v;
do {
if ((c = pgx_getc(in)) == EOF) {
return -1;
}
} while (isspace(c));
v = 0;
while (isdigit(c)) {
v = 10 * v + c - '0';
if ((c = pgx_getc(in)) < 0) {
return -1;
}
}
if (!isspace(c)) {
return -1;
}
*val = v;
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
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: _fep_open_control_socket (Fep *fep)
{
struct sockaddr_un sun;
char *path;
int fd;
ssize_t sun_len;
fd = socket (AF_UNIX, SOCK_STREAM, 0);
if (fd < 0)
{
perror ("socket");
return -1;
}
path = create_socket_name ("fep-XXXXXX/control");
if (strlen (path) + 1 >= sizeof(sun.sun_path))
{
fep_log (FEP_LOG_LEVEL_WARNING,
"unix domain socket path too long: %d + 1 >= %d",
strlen (path),
sizeof (sun.sun_path));
free (path);
return -1;
}
memset (&sun, 0, sizeof(sun));
sun.sun_family = AF_UNIX;
#ifdef __linux__
sun.sun_path[0] = '\0';
memcpy (sun.sun_path + 1, path, strlen (path));
sun_len = offsetof (struct sockaddr_un, sun_path) + strlen (path) + 1;
remove_control_socket (path);
#else
memcpy (sun.sun_path, path, strlen (path));
sun_len = sizeof (struct sockaddr_un);
#endif
if (bind (fd, (const struct sockaddr *) &sun, sun_len) < 0)
{
perror ("bind");
free (path);
close (fd);
return -1;
}
if (listen (fd, 5) < 0)
{
perror ("listen");
free (path);
close (fd);
return -1;
}
fep->server = fd;
fep->control_socket_path = path;
return 0;
}
Commit Message: Don't use abstract Unix domain sockets
CWE ID: CWE-264
Target: 1
Example 2:
Code: ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
struct shash *info)
{
connmgr_get_controller_info(ofproto->connmgr, info);
}
Commit Message: ofproto: Fix OVS crash when reverting old flows in bundle commit
During bundle commit flows which are added in bundle are applied
to ofproto in-order. In case if a flow cannot be added (e.g. flow
action is go-to group id which does not exist), OVS tries to
revert back all previous flows which were successfully applied
from the same bundle. This is possible since OVS maintains list
of old flows which were replaced by flows from the bundle.
While reinserting old flows ovs asserts due to check on rule
state != RULE_INITIALIZED. This will work only for new flows, but
for old flow the rule state will be RULE_REMOVED. This is causing
an assert and OVS crash.
The ovs assert check should be modified to != RULE_INSERTED to prevent
any existing rule being re-inserted and allow new rules and old rules
(in case of revert) to get inserted.
Here is an example to trigger the assert:
$ ovs-vsctl add-br br-test -- set Bridge br-test datapath_type=netdev
$ cat flows.txt
flow add table=1,priority=0,in_port=2,actions=NORMAL
flow add table=1,priority=0,in_port=3,actions=NORMAL
$ ovs-ofctl dump-flows -OOpenflow13 br-test
cookie=0x0, duration=2.465s, table=1, n_packets=0, n_bytes=0, priority=0,in_port=2 actions=NORMAL
cookie=0x0, duration=2.465s, table=1, n_packets=0, n_bytes=0, priority=0,in_port=3 actions=NORMAL
$ cat flow-modify.txt
flow modify table=1,priority=0,in_port=2,actions=drop
flow modify table=1,priority=0,in_port=3,actions=group:10
$ ovs-ofctl bundle br-test flow-modify.txt -OOpenflow13
First flow rule will be modified since it is a valid rule. However second
rule is invalid since no group with id 10 exists. Bundle commit tries to
revert (insert) the first rule to old flow which results in ovs_assert at
ofproto_rule_insert__() since old rule->state = RULE_REMOVED.
Signed-off-by: Vishal Deep Ajmera <[email protected]>
Signed-off-by: Ben Pfaff <[email protected]>
CWE ID: CWE-617
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void fill_tso_desc(struct hnae_ring *ring, void *priv,
int size, dma_addr_t dma, int frag_end,
int buf_num, enum hns_desc_type type, int mtu)
{
int frag_buf_num;
int sizeoflast;
int k;
frag_buf_num = (size + BD_MAX_SEND_SIZE - 1) / BD_MAX_SEND_SIZE;
sizeoflast = size % BD_MAX_SEND_SIZE;
sizeoflast = sizeoflast ? sizeoflast : BD_MAX_SEND_SIZE;
/* when the frag size is bigger than hardware, split this frag */
for (k = 0; k < frag_buf_num; k++)
fill_v2_desc(ring, priv,
(k == frag_buf_num - 1) ?
sizeoflast : BD_MAX_SEND_SIZE,
dma + BD_MAX_SEND_SIZE * k,
frag_end && (k == frag_buf_num - 1) ? 1 : 0,
buf_num,
(type == DESC_TYPE_SKB && !k) ?
DESC_TYPE_SKB : DESC_TYPE_PAGE,
mtu);
}
Commit Message: net: hns: Fix a skb used after free bug
skb maybe freed in hns_nic_net_xmit_hw() and return NETDEV_TX_OK,
which cause hns_nic_net_xmit to use a freed skb.
BUG: KASAN: use-after-free in hns_nic_net_xmit_hw+0x62c/0x940...
[17659.112635] alloc_debug_processing+0x18c/0x1a0
[17659.117208] __slab_alloc+0x52c/0x560
[17659.120909] kmem_cache_alloc_node+0xac/0x2c0
[17659.125309] __alloc_skb+0x6c/0x260
[17659.128837] tcp_send_ack+0x8c/0x280
[17659.132449] __tcp_ack_snd_check+0x9c/0xf0
[17659.136587] tcp_rcv_established+0x5a4/0xa70
[17659.140899] tcp_v4_do_rcv+0x27c/0x620
[17659.144687] tcp_prequeue_process+0x108/0x170
[17659.149085] tcp_recvmsg+0x940/0x1020
[17659.152787] inet_recvmsg+0x124/0x180
[17659.156488] sock_recvmsg+0x64/0x80
[17659.160012] SyS_recvfrom+0xd8/0x180
[17659.163626] __sys_trace_return+0x0/0x4
[17659.167506] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=23 cpu=1 pid=13
[17659.174000] free_debug_processing+0x1d4/0x2c0
[17659.178486] __slab_free+0x240/0x390
[17659.182100] kmem_cache_free+0x24c/0x270
[17659.186062] kfree_skbmem+0xa0/0xb0
[17659.189587] __kfree_skb+0x28/0x40
[17659.193025] napi_gro_receive+0x168/0x1c0
[17659.197074] hns_nic_rx_up_pro+0x58/0x90
[17659.201038] hns_nic_rx_poll_one+0x518/0xbc0
[17659.205352] hns_nic_common_poll+0x94/0x140
[17659.209576] net_rx_action+0x458/0x5e0
[17659.213363] __do_softirq+0x1b8/0x480
[17659.217062] run_ksoftirqd+0x64/0x80
[17659.220679] smpboot_thread_fn+0x224/0x310
[17659.224821] kthread+0x150/0x170
[17659.228084] ret_from_fork+0x10/0x40
BUG: KASAN: use-after-free in hns_nic_net_xmit+0x8c/0xc0...
[17751.080490] __slab_alloc+0x52c/0x560
[17751.084188] kmem_cache_alloc+0x244/0x280
[17751.088238] __build_skb+0x40/0x150
[17751.091764] build_skb+0x28/0x100
[17751.095115] __alloc_rx_skb+0x94/0x150
[17751.098900] __napi_alloc_skb+0x34/0x90
[17751.102776] hns_nic_rx_poll_one+0x180/0xbc0
[17751.107097] hns_nic_common_poll+0x94/0x140
[17751.111333] net_rx_action+0x458/0x5e0
[17751.115123] __do_softirq+0x1b8/0x480
[17751.118823] run_ksoftirqd+0x64/0x80
[17751.122437] smpboot_thread_fn+0x224/0x310
[17751.126575] kthread+0x150/0x170
[17751.129838] ret_from_fork+0x10/0x40
[17751.133454] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=19 cpu=7 pid=43
[17751.139951] free_debug_processing+0x1d4/0x2c0
[17751.144436] __slab_free+0x240/0x390
[17751.148051] kmem_cache_free+0x24c/0x270
[17751.152014] kfree_skbmem+0xa0/0xb0
[17751.155543] __kfree_skb+0x28/0x40
[17751.159022] napi_gro_receive+0x168/0x1c0
[17751.163074] hns_nic_rx_up_pro+0x58/0x90
[17751.167041] hns_nic_rx_poll_one+0x518/0xbc0
[17751.171358] hns_nic_common_poll+0x94/0x140
[17751.175585] net_rx_action+0x458/0x5e0
[17751.179373] __do_softirq+0x1b8/0x480
[17751.183076] run_ksoftirqd+0x64/0x80
[17751.186691] smpboot_thread_fn+0x224/0x310
[17751.190826] kthread+0x150/0x170
[17751.194093] ret_from_fork+0x10/0x40
Fixes: 13ac695e7ea1 ("net:hns: Add support of Hip06 SoC to the Hislicon Network Subsystem")
Signed-off-by: Yunsheng Lin <[email protected]>
Signed-off-by: lipeng <[email protected]>
Reported-by: Jun He <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: GURL SanitizeFrontendURL(const GURL& url,
const std::string& scheme,
const std::string& host,
const std::string& path,
bool allow_query_and_fragment) {
std::vector<std::string> query_parts;
std::string fragment;
if (allow_query_and_fragment) {
for (net::QueryIterator it(url); !it.IsAtEnd(); it.Advance()) {
std::string value = SanitizeFrontendQueryParam(it.GetKey(),
it.GetValue());
if (!value.empty()) {
query_parts.push_back(
base::StringPrintf("%s=%s", it.GetKey().c_str(), value.c_str()));
}
}
if (url.has_ref())
fragment = '#' + url.ref();
}
std::string query =
query_parts.empty() ? "" : "?" + base::JoinString(query_parts, "&");
std::string constructed =
base::StringPrintf("%s://%s%s%s%s", scheme.c_str(), host.c_str(),
path.c_str(), query.c_str(), fragment.c_str());
GURL result = GURL(constructed);
if (!result.is_valid())
return GURL();
return result;
}
Commit Message: Improve sanitization of remoteFrontendUrl in DevTools
This change ensures that the decoded remoteFrontendUrl parameter cannot
contain any single quote in its value. As of this commit, none of the
permitted query params in SanitizeFrontendQueryParam can contain single
quotes.
Note that the existing SanitizeEndpoint function does not explicitly
check for single quotes. This is fine since single quotes in the query
string are already URL-encoded and the values validated by
SanitizeEndpoint are not url-decoded elsewhere.
BUG=798163
TEST=Manually, see https://crbug.com/798163#c1
TEST=./unit_tests --gtest_filter=DevToolsUIBindingsTest.SanitizeFrontendURL
Change-Id: I5a08e8ce6f1abc2c8d2a0983fef63e1e194cd242
Reviewed-on: https://chromium-review.googlesource.com/846979
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Rob Wu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#527250}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static const struct sys_reg_desc *find_reg(const struct sys_reg_params *params,
const struct sys_reg_desc table[],
unsigned int num)
{
unsigned long pval = reg_to_match_value(params);
return bsearch((void *)pval, table, num, sizeof(table[0]), match_sys_reg);
}
Commit Message: arm64: KVM: pmu: Fix AArch32 cycle counter access
We're missing the handling code for the cycle counter accessed
from a 32bit guest, leading to unexpected results.
Cc: [email protected] # 4.6+
Signed-off-by: Wei Huang <[email protected]>
Signed-off-by: Marc Zyngier <[email protected]>
CWE ID: CWE-617
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void usbip_pad_iso(struct usbip_device *ud, struct urb *urb)
{
int np = urb->number_of_packets;
int i;
int actualoffset = urb->actual_length;
if (!usb_pipeisoc(urb->pipe))
return;
/* if no packets or length of data is 0, then nothing to unpack */
if (np == 0 || urb->actual_length == 0)
return;
/*
* if actual_length is transfer_buffer_length then no padding is
* present.
*/
if (urb->actual_length == urb->transfer_buffer_length)
return;
/*
* loop over all packets from last to first (to prevent overwritting
* memory when padding) and move them into the proper place
*/
for (i = np-1; i > 0; i--) {
actualoffset -= urb->iso_frame_desc[i].actual_length;
memmove(urb->transfer_buffer + urb->iso_frame_desc[i].offset,
urb->transfer_buffer + actualoffset,
urb->iso_frame_desc[i].actual_length);
}
}
Commit Message: USB: usbip: fix potential out-of-bounds write
Fix potential out-of-bounds write to urb->transfer_buffer
usbip handles network communication directly in the kernel. When receiving a
packet from its peer, usbip code parses headers according to protocol. As
part of this parsing urb->actual_length is filled. Since the input for
urb->actual_length comes from the network, it should be treated as untrusted.
Any entity controlling the network may put any value in the input and the
preallocated urb->transfer_buffer may not be large enough to hold the data.
Thus, the malicious entity is able to write arbitrary data to kernel memory.
Signed-off-by: Ignat Korchagin <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int fpm_unix_resolve_socket_premissions(struct fpm_worker_pool_s *wp) /* {{{ */
{
struct fpm_worker_pool_config_s *c = wp->config;
/* uninitialized */
wp->socket_uid = -1;
wp->socket_gid = -1;
wp->socket_mode = 0666;
if (!c) {
return 0;
}
if (c->listen_owner && *c->listen_owner) {
struct passwd *pwd;
pwd = getpwnam(c->listen_owner);
if (!pwd) {
zlog(ZLOG_SYSERROR, "[pool %s] cannot get uid for user '%s'", wp->config->name, c->listen_owner);
return -1;
}
wp->socket_uid = pwd->pw_uid;
wp->socket_gid = pwd->pw_gid;
}
if (c->listen_group && *c->listen_group) {
struct group *grp;
grp = getgrnam(c->listen_group);
if (!grp) {
zlog(ZLOG_SYSERROR, "[pool %s] cannot get gid for group '%s'", wp->config->name, c->listen_group);
return -1;
}
wp->socket_gid = grp->gr_gid;
}
if (c->listen_mode && *c->listen_mode) {
wp->socket_mode = strtoul(c->listen_mode, 0, 8);
}
return 0;
}
/* }}} */
Commit Message: Fix bug #67060: use default mode of 660
CWE ID: CWE-264
Target: 1
Example 2:
Code: tt_cmap12_char_next( TT_CMap cmap,
FT_UInt32 *pchar_code )
{
TT_CMap12 cmap12 = (TT_CMap12)cmap;
FT_UInt gindex;
/* no need to search */
if ( cmap12->valid && cmap12->cur_charcode == *pchar_code )
{
tt_cmap12_next( cmap12 );
if ( cmap12->valid )
{
gindex = cmap12->cur_gindex;
*pchar_code = (FT_UInt32)cmap12->cur_charcode;
}
else
gindex = 0;
}
else
gindex = tt_cmap12_char_map_binary( cmap, pchar_code, 1 );
return gindex;
}
Commit Message:
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void set_user_nice(struct task_struct *p, long nice)
{
int old_prio, delta, queued;
struct rq_flags rf;
struct rq *rq;
if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
return;
/*
* We have to be careful, if called from sys_setpriority(),
* the task might be in the middle of scheduling on another CPU.
*/
rq = task_rq_lock(p, &rf);
/*
* The RT priorities are set via sched_setscheduler(), but we still
* allow the 'normal' nice value to be set - but as expected
* it wont have any effect on scheduling until the task is
* SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
*/
if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
p->static_prio = NICE_TO_PRIO(nice);
goto out_unlock;
}
queued = task_on_rq_queued(p);
if (queued)
dequeue_task(rq, p, DEQUEUE_SAVE);
p->static_prio = NICE_TO_PRIO(nice);
set_load_weight(p);
old_prio = p->prio;
p->prio = effective_prio(p);
delta = p->prio - old_prio;
if (queued) {
enqueue_task(rq, p, ENQUEUE_RESTORE);
/*
* If the task increased its priority or is running and
* lowered its priority, then reschedule its CPU:
*/
if (delta < 0 || (delta > 0 && task_running(rq, p)))
resched_curr(rq);
}
out_unlock:
task_rq_unlock(rq, p, &rf);
}
Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann)
Merge filesystem stacking fixes from Jann Horn.
* emailed patches from Jann Horn <[email protected]>:
sched: panic on corrupted stack end
ecryptfs: forbid opening files without mmap handler
proc: prevent stacking filesystems on top
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static ssize_t aio_setup_single_vector(struct kiocb *kiocb,
int rw, char __user *buf,
unsigned long *nr_segs,
struct iovec *iovec)
{
if (unlikely(!access_ok(!rw, buf, kiocb->ki_nbytes)))
return -EFAULT;
iovec->iov_base = buf;
iovec->iov_len = kiocb->ki_nbytes;
*nr_segs = 1;
return 0;
}
Commit Message: AIO: properly check iovec sizes
In Linus's tree, the iovec code has been reworked massively, but in
older kernels the AIO layer should be checking this before passing the
request on to other layers.
Many thanks to Ben Hawkes of Google Project Zero for pointing out the
issue.
Reported-by: Ben Hawkes <[email protected]>
Acked-by: Benjamin LaHaise <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: bool Document::importContainerNodeChildren(ContainerNode* oldContainerNode, PassRefPtrWillBeRawPtr<ContainerNode> newContainerNode, ExceptionState& exceptionState)
{
for (Node& oldChild : NodeTraversal::childrenOf(*oldContainerNode)) {
RefPtrWillBeRawPtr<Node> newChild = importNode(&oldChild, true, exceptionState);
if (exceptionState.hadException())
return false;
newContainerNode->appendChild(newChild.release(), exceptionState);
if (exceptionState.hadException())
return false;
}
return true;
}
Commit Message: Change Document::detach() to RELEASE_ASSERT all subframes are gone.
BUG=556724,577105
Review URL: https://codereview.chromium.org/1667573002
Cr-Commit-Position: refs/heads/master@{#373642}
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: asmlinkage void kernel_unaligned_trap(struct pt_regs *regs, unsigned int insn)
{
enum direction dir = decode_direction(insn);
int size = decode_access_size(insn);
if(!ok_for_kernel(insn) || dir == both) {
printk("Unsupported unaligned load/store trap for kernel at <%08lx>.\n",
regs->pc);
unaligned_panic("Wheee. Kernel does fpu/atomic unaligned load/store.");
} else {
unsigned long addr = compute_effective_address(regs, insn);
int err;
perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, addr);
switch (dir) {
case load:
err = do_int_load(fetch_reg_addr(((insn>>25)&0x1f),
regs),
size, (unsigned long *) addr,
decode_signedness(insn));
break;
case store:
err = do_int_store(((insn>>25)&0x1f), size,
(unsigned long *) addr, regs);
break;
default:
panic("Impossible kernel unaligned trap.");
/* Not reached... */
}
if (err)
kernel_mna_trap_fault(regs, insn);
else
advance(regs);
}
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RenderWidgetHostViewGuest::AcceleratedSurfaceNew(int32 width_in_pixel,
int32 height_in_pixel,
uint64 surface_handle) {
NOTIMPLEMENTED();
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: static av_cold int decode_init(AVCodecContext *avctx)
{
SCPRContext *s = avctx->priv_data;
switch (avctx->bits_per_coded_sample) {
case 16: avctx->pix_fmt = AV_PIX_FMT_RGB0; break;
case 24:
case 32: avctx->pix_fmt = AV_PIX_FMT_BGR0; break;
default:
av_log(avctx, AV_LOG_ERROR, "Unsupported bitdepth %i\n", avctx->bits_per_coded_sample);
return AVERROR_INVALIDDATA;
}
s->get_freq = get_freq0;
s->decode = decode0;
s->cxshift = avctx->bits_per_coded_sample == 16 ? 0 : 2;
s->cbits = avctx->bits_per_coded_sample == 16 ? 0x1F : 0xFF;
s->nbx = (avctx->width + 15) / 16;
s->nby = (avctx->height + 15) / 16;
s->nbcount = s->nbx * s->nby;
s->blocks = av_malloc_array(s->nbcount, sizeof(*s->blocks));
if (!s->blocks)
return AVERROR(ENOMEM);
s->last_frame = av_frame_alloc();
s->current_frame = av_frame_alloc();
if (!s->last_frame || !s->current_frame)
return AVERROR(ENOMEM);
return 0;
}
Commit Message: avcodec/scpr: Check y in first line loop in decompress_i()
Fixes: out of array access
Fixes: 1478/clusterfuzz-testcase-minimized-5285486908145664
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int l2tp_ip_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len)
{
struct sk_buff *skb;
int rc;
struct l2tp_ip_sock *lsa = l2tp_ip_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct ip_options *opt = inet->opt;
struct rtable *rt = NULL;
int connected = 0;
__be32 daddr;
if (sock_flag(sk, SOCK_DEAD))
return -ENOTCONN;
/* Get and verify the address. */
if (msg->msg_name) {
struct sockaddr_l2tpip *lip = (struct sockaddr_l2tpip *) msg->msg_name;
if (msg->msg_namelen < sizeof(*lip))
return -EINVAL;
if (lip->l2tp_family != AF_INET) {
if (lip->l2tp_family != AF_UNSPEC)
return -EAFNOSUPPORT;
}
daddr = lip->l2tp_addr.s_addr;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
daddr = inet->inet_daddr;
connected = 1;
}
/* Allocate a socket buffer */
rc = -ENOMEM;
skb = sock_wmalloc(sk, 2 + NET_SKB_PAD + sizeof(struct iphdr) +
4 + len, 0, GFP_KERNEL);
if (!skb)
goto error;
/* Reserve space for headers, putting IP header on 4-byte boundary. */
skb_reserve(skb, 2 + NET_SKB_PAD);
skb_reset_network_header(skb);
skb_reserve(skb, sizeof(struct iphdr));
skb_reset_transport_header(skb);
/* Insert 0 session_id */
*((__be32 *) skb_put(skb, 4)) = 0;
/* Copy user data into skb */
rc = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len);
if (rc < 0) {
kfree_skb(skb);
goto error;
}
if (connected)
rt = (struct rtable *) __sk_dst_check(sk, 0);
if (rt == NULL) {
/* Use correct destination address if we have options. */
if (opt && opt->srr)
daddr = opt->faddr;
/* If this fails, retransmit mechanism of transport layer will
* keep trying until route appears or the connection times
* itself out.
*/
rt = ip_route_output_ports(sock_net(sk), sk,
daddr, inet->inet_saddr,
inet->inet_dport, inet->inet_sport,
sk->sk_protocol, RT_CONN_FLAGS(sk),
sk->sk_bound_dev_if);
if (IS_ERR(rt))
goto no_route;
sk_setup_caps(sk, &rt->dst);
}
skb_dst_set(skb, dst_clone(&rt->dst));
/* Queue the packet to IP for output */
rc = ip_queue_xmit(skb);
error:
/* Update stats */
if (rc >= 0) {
lsa->tx_packets++;
lsa->tx_bytes += len;
rc = len;
} else {
lsa->tx_errors++;
}
return rc;
no_route:
IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTNOROUTES);
kfree_skb(skb);
return -EHOSTUNREACH;
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: xmlParsePEReference(xmlParserCtxtPtr ctxt)
{
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%')
return;
NEXT;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParsePEReference: no name\n");
return;
}
if (RAW != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
return;
}
NEXT;
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Request the entity from SAX
*/
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (ctxt->instate == XML_PARSER_EOF)
return;
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must
* precede any reference to it...
*/
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
xmlParserEntityCheck(ctxt, 0, NULL, 0);
} else {
/*
* Internal checking in case the entity quest barfed
*/
if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Internal: %%%s; is not a parameter entity\n",
name, NULL);
} else if (ctxt->input->free != deallocblankswrapper) {
input = xmlNewBlanksWrapperInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
} else {
/*
* TODO !!!
* handle the extra spaces added before and after
* c.f. http://www.w3.org/TR/REC-xml#as-PE
*/
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
(CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
if (ctxt->errNo ==
XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing
* right here
*/
xmlHaltParser(ctxt);
return;
}
}
}
}
ctxt->hasPErefs = 1;
}
Commit Message: DO NOT MERGE: Add validation for eternal enities
https://bugzilla.gnome.org/show_bug.cgi?id=780691
Bug: 36556310
Change-Id: I9450743e167c3c73af5e4071f3fc85e81d061648
(cherry picked from commit bef9af3d89d241bcb518c20cba6da2a2fd9ba049)
CWE ID: CWE-611
Target: 1
Example 2:
Code: static int hls_close(AVFormatContext *s)
{
HLSContext *c = s->priv_data;
free_playlist_list(c);
free_variant_list(c);
free_rendition_list(c);
av_dict_free(&c->avio_opts);
return 0;
}
Commit Message: avformat/hls: Fix DoS due to infinite loop
Fixes: loop.m3u
The default max iteration count of 1000 is arbitrary and ideas for a better solution are welcome
Found-by: Xiaohei and Wangchu from Alibaba Security Team
Previous version reviewed-by: Steven Liu <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-835
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int xmlrpc_set_options(int type, const char *value)
{
if (type == XMLRPC_HTTP_HEADER)
{
if (!stricmp(value, XMLRPC_ON))
{
xmlrpc.httpheader = 1;
}
if (!stricmp(value, XMLRPC_OFF))
{
xmlrpc.httpheader = 0;
}
}
if (type == XMLRPC_ENCODE)
{
if (value)
{
xmlrpc.encode = sstrdup(value);
}
}
if (type == XMLRPC_INTTAG)
{
if (!stricmp(value, XMLRPC_I4))
{
xmlrpc.inttagstart = sstrdup("<i4>");
xmlrpc.inttagend = sstrdup("</i4>");
}
if (!stricmp(value, XMLRPC_INT))
{
xmlrpc.inttagstart = sstrdup("<int>");
xmlrpc.inttagend = sstrdup("</int>");
}
}
return 1;
}
Commit Message: Do not copy more bytes than were allocated
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: status_t BnOMX::onTransact(
uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
switch (code) {
case LIVES_LOCALLY:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
pid_t pid = (pid_t)data.readInt32();
reply->writeInt32(livesLocally(node, pid));
return OK;
}
case LIST_NODES:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
List<ComponentInfo> list;
listNodes(&list);
reply->writeInt32(list.size());
for (List<ComponentInfo>::iterator it = list.begin();
it != list.end(); ++it) {
ComponentInfo &cur = *it;
reply->writeString8(cur.mName);
reply->writeInt32(cur.mRoles.size());
for (List<String8>::iterator role_it = cur.mRoles.begin();
role_it != cur.mRoles.end(); ++role_it) {
reply->writeString8(*role_it);
}
}
return NO_ERROR;
}
case ALLOCATE_NODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
const char *name = data.readCString();
sp<IOMXObserver> observer =
interface_cast<IOMXObserver>(data.readStrongBinder());
node_id node;
status_t err = allocateNode(name, observer, &node);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)node);
}
return NO_ERROR;
}
case FREE_NODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
reply->writeInt32(freeNode(node));
return NO_ERROR;
}
case SEND_COMMAND:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_COMMANDTYPE cmd =
static_cast<OMX_COMMANDTYPE>(data.readInt32());
OMX_S32 param = data.readInt32();
reply->writeInt32(sendCommand(node, cmd, param));
return NO_ERROR;
}
case GET_PARAMETER:
case SET_PARAMETER:
case GET_CONFIG:
case SET_CONFIG:
case SET_INTERNAL_OPTION:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32());
size_t size = data.readInt64();
status_t err = NOT_ENOUGH_DATA;
void *params = NULL;
size_t pageSize = 0;
size_t allocSize = 0;
if ((index == (OMX_INDEXTYPE) OMX_IndexParamConsumerUsageBits && size < 4) ||
(code != SET_INTERNAL_OPTION && size < 8)) {
ALOGE("b/27207275 (%zu)", size);
android_errorWriteLog(0x534e4554, "27207275");
} else {
err = NO_MEMORY;
pageSize = (size_t) sysconf(_SC_PAGE_SIZE);
if (size > SIZE_MAX - (pageSize * 2)) {
ALOGE("requested param size too big");
} else {
allocSize = (size + pageSize * 2) & ~(pageSize - 1);
params = mmap(NULL, allocSize, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1 /* fd */, 0 /* offset */);
}
if (params != MAP_FAILED) {
err = data.read(params, size);
if (err != OK) {
android_errorWriteLog(0x534e4554, "26914474");
} else {
err = NOT_ENOUGH_DATA;
OMX_U32 declaredSize = *(OMX_U32*)params;
if (code != SET_INTERNAL_OPTION &&
index != (OMX_INDEXTYPE) OMX_IndexParamConsumerUsageBits &&
declaredSize > size) {
ALOGE("b/27207275 (%u/%zu)", declaredSize, size);
android_errorWriteLog(0x534e4554, "27207275");
} else {
mprotect((char*)params + allocSize - pageSize, pageSize, PROT_NONE);
switch (code) {
case GET_PARAMETER:
err = getParameter(node, index, params, size);
break;
case SET_PARAMETER:
err = setParameter(node, index, params, size);
break;
case GET_CONFIG:
err = getConfig(node, index, params, size);
break;
case SET_CONFIG:
err = setConfig(node, index, params, size);
break;
case SET_INTERNAL_OPTION:
{
InternalOptionType type =
(InternalOptionType)data.readInt32();
err = setInternalOption(node, index, type, params, size);
break;
}
default:
TRESPASS();
}
}
}
} else {
ALOGE("couldn't map: %s", strerror(errno));
}
}
reply->writeInt32(err);
if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) {
reply->write(params, size);
}
if (params) {
munmap(params, allocSize);
}
params = NULL;
return NO_ERROR;
}
case GET_STATE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_STATETYPE state = OMX_StateInvalid;
status_t err = getState(node, &state);
reply->writeInt32(state);
reply->writeInt32(err);
return NO_ERROR;
}
case ENABLE_GRAPHIC_BUFFERS:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
status_t err = enableGraphicBuffers(node, port_index, enable);
reply->writeInt32(err);
return NO_ERROR;
}
case GET_GRAPHIC_BUFFER_USAGE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_U32 usage = 0;
status_t err = getGraphicBufferUsage(node, port_index, &usage);
reply->writeInt32(err);
reply->writeInt32(usage);
return NO_ERROR;
}
case USE_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IMemory> params =
interface_cast<IMemory>(data.readStrongBinder());
OMX_U32 allottedSize = data.readInt32();
buffer_id buffer;
status_t err = useBuffer(node, port_index, params, &buffer, allottedSize);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case USE_GRAPHIC_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
buffer_id buffer;
status_t err = useGraphicBuffer(
node, port_index, graphicBuffer, &buffer);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case UPDATE_GRAPHIC_BUFFER_IN_META:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
buffer_id buffer = (buffer_id)data.readInt32();
status_t err = updateGraphicBufferInMeta(
node, port_index, graphicBuffer, buffer);
reply->writeInt32(err);
return NO_ERROR;
}
case CREATE_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IGraphicBufferProducer> bufferProducer;
MetadataBufferType type = kMetadataBufferTypeInvalid;
status_t err = createInputSurface(node, port_index, &bufferProducer, &type);
if ((err != OK) && (type == kMetadataBufferTypeInvalid)) {
android_errorWriteLog(0x534e4554, "26324358");
}
reply->writeInt32(type);
reply->writeInt32(err);
if (err == OK) {
reply->writeStrongBinder(IInterface::asBinder(bufferProducer));
}
return NO_ERROR;
}
case CREATE_PERSISTENT_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
sp<IGraphicBufferProducer> bufferProducer;
sp<IGraphicBufferConsumer> bufferConsumer;
status_t err = createPersistentInputSurface(
&bufferProducer, &bufferConsumer);
reply->writeInt32(err);
if (err == OK) {
reply->writeStrongBinder(IInterface::asBinder(bufferProducer));
reply->writeStrongBinder(IInterface::asBinder(bufferConsumer));
}
return NO_ERROR;
}
case SET_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IGraphicBufferConsumer> bufferConsumer =
interface_cast<IGraphicBufferConsumer>(data.readStrongBinder());
MetadataBufferType type = kMetadataBufferTypeInvalid;
status_t err = setInputSurface(node, port_index, bufferConsumer, &type);
if ((err != OK) && (type == kMetadataBufferTypeInvalid)) {
android_errorWriteLog(0x534e4554, "26324358");
}
reply->writeInt32(type);
reply->writeInt32(err);
return NO_ERROR;
}
case SIGNAL_END_OF_INPUT_STREAM:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
status_t err = signalEndOfInputStream(node);
reply->writeInt32(err);
return NO_ERROR;
}
case STORE_META_DATA_IN_BUFFERS:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
MetadataBufferType type = kMetadataBufferTypeInvalid;
status_t err = storeMetaDataInBuffers(node, port_index, enable, &type);
reply->writeInt32(type);
reply->writeInt32(err);
return NO_ERROR;
}
case PREPARE_FOR_ADAPTIVE_PLAYBACK:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
OMX_U32 max_width = data.readInt32();
OMX_U32 max_height = data.readInt32();
status_t err = prepareForAdaptivePlayback(
node, port_index, enable, max_width, max_height);
reply->writeInt32(err);
return NO_ERROR;
}
case CONFIGURE_VIDEO_TUNNEL_MODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL tunneled = (OMX_BOOL)data.readInt32();
OMX_U32 audio_hw_sync = data.readInt32();
native_handle_t *sideband_handle = NULL;
status_t err = configureVideoTunnelMode(
node, port_index, tunneled, audio_hw_sync, &sideband_handle);
reply->writeInt32(err);
if(err == OK){
reply->writeNativeHandle(sideband_handle);
}
return NO_ERROR;
}
case ALLOC_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) {
ALOGE("b/24310423");
reply->writeInt32(INVALID_OPERATION);
return NO_ERROR;
}
size_t size = data.readInt64();
buffer_id buffer;
void *buffer_data;
status_t err = allocateBuffer(
node, port_index, size, &buffer, &buffer_data);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
reply->writeInt64((uintptr_t)buffer_data);
}
return NO_ERROR;
}
case ALLOC_BUFFER_WITH_BACKUP:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IMemory> params =
interface_cast<IMemory>(data.readStrongBinder());
OMX_U32 allottedSize = data.readInt32();
buffer_id buffer;
status_t err = allocateBufferWithBackup(
node, port_index, params, &buffer, allottedSize);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case FREE_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
reply->writeInt32(freeBuffer(node, port_index, buffer));
return NO_ERROR;
}
case FILL_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
bool haveFence = data.readInt32();
int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1;
reply->writeInt32(fillBuffer(node, buffer, fenceFd));
return NO_ERROR;
}
case EMPTY_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
OMX_U32 range_offset = data.readInt32();
OMX_U32 range_length = data.readInt32();
OMX_U32 flags = data.readInt32();
OMX_TICKS timestamp = data.readInt64();
bool haveFence = data.readInt32();
int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1;
reply->writeInt32(emptyBuffer(
node, buffer, range_offset, range_length, flags, timestamp, fenceFd));
return NO_ERROR;
}
case GET_EXTENSION_INDEX:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
const char *parameter_name = data.readCString();
OMX_INDEXTYPE index;
status_t err = getExtensionIndex(node, parameter_name, &index);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32(index);
}
return OK;
}
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
Commit Message: Fix OMX_IndexParamConsumerUsageBits size check
Bug: 27207275
Change-Id: I9a7c9fb22a0e84a490ff09c151bd2f88141fdbc0
CWE ID: CWE-119
Target: 1
Example 2:
Code: int _yr_emit_inst_arg_uint16(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint16_t argument,
uint8_t** instruction_addr,
uint16_t** argument_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(uint16_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(uint16_t);
return ERROR_SUCCESS;
}
Commit Message: Fix buffer overrun (issue #678). Add assert for detecting this kind of issues earlier.
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: IPV6DefragReverseSimpleTest(void)
{
DefragContext *dc = NULL;
Packet *p1 = NULL, *p2 = NULL, *p3 = NULL;
Packet *reassembled = NULL;
int id = 12;
int i;
int ret = 0;
DefragInit();
dc = DefragContextNew();
if (dc == NULL)
goto end;
p1 = IPV6BuildTestPacket(id, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = IPV6BuildTestPacket(id, 1, 1, 'B', 8);
if (p2 == NULL)
goto end;
p3 = IPV6BuildTestPacket(id, 2, 0, 'C', 3);
if (p3 == NULL)
goto end;
if (Defrag(NULL, NULL, p3, NULL) != NULL)
goto end;
if (Defrag(NULL, NULL, p2, NULL) != NULL)
goto end;
reassembled = Defrag(NULL, NULL, p1, NULL);
if (reassembled == NULL)
goto end;
/* 40 bytes in we should find 8 bytes of A. */
for (i = 40; i < 40 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'A')
goto end;
}
/* 28 bytes in we should find 8 bytes of B. */
for (i = 48; i < 48 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'B')
goto end;
}
/* And 36 bytes in we should find 3 bytes of C. */
for (i = 56; i < 56 + 3; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'C')
goto end;
}
ret = 1;
end:
if (dc != NULL)
DefragContextDestroy(dc);
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
if (p3 != NULL)
SCFree(p3);
if (reassembled != NULL)
SCFree(reassembled);
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: AudioOutputAuthorizationHandlerTest() {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kUseFakeDeviceForMediaStream);
thread_bundle_ = base::MakeUnique<TestBrowserThreadBundle>(
TestBrowserThreadBundle::Options::REAL_IO_THREAD);
audio_thread_ = base::MakeUnique<AudioManagerThread>();
audio_manager_.reset(new media::FakeAudioManager(
audio_thread_->task_runner(), audio_thread_->worker_task_runner(),
&log_factory_));
media_stream_manager_ =
base::MakeUnique<MediaStreamManager>(audio_manager_.get());
SyncWithAllThreads();
}
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:
Target: 1
Example 2:
Code: PassRefPtr<RenderStyle> StyleResolver::defaultStyleForElement()
{
StyleResolverState state(document(), 0);
state.setStyle(RenderStyle::create());
state.fontBuilder().initForStyleResolve(document(), state.style(), state.useSVGZoomRules());
state.style()->setLineHeight(RenderStyle::initialLineHeight());
state.setLineHeightValue(0);
state.fontBuilder().setInitial(state.style()->effectiveZoom());
state.style()->font().update(fontSelector());
return state.takeStyle();
}
Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun.
We've been bitten by the Simple Default Stylesheet being out
of sync with the real html.css twice this week.
The Simple Default Stylesheet was invented years ago for Mac:
http://trac.webkit.org/changeset/36135
It nicely handles the case where you just want to create
a single WebView and parse some simple HTML either without
styling said HTML, or only to display a small string, etc.
Note that this optimization/complexity *only* helps for the
very first document, since the default stylesheets are
all static (process-global) variables. Since any real page
on the internet uses a tag not covered by the simple default
stylesheet, not real load benefits from this optimization.
Only uses of WebView which were just rendering small bits
of text might have benefited from this. about:blank would
also have used this sheet.
This was a common application for some uses of WebView back
in those days. These days, even with WebView on Android,
there are likely much larger overheads than parsing the
html.css stylesheet, so making it required seems like the
right tradeoff of code-simplicity for this case.
BUG=319556
Review URL: https://codereview.chromium.org/73723005
git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Strremovefirstspaces(Str s)
{
int i;
STR_LENGTH_CHECK(s);
for (i = 0; i < s->length && IS_SPACE(s->ptr[i]); i++) ;
if (i == 0)
return;
Strdelete(s, 0, i);
}
Commit Message: Merge pull request #27 from kcwu/fix-strgrow
Fix potential heap buffer corruption due to Strgrow
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DocumentThreadableLoader::loadRequest(const ResourceRequest& request, ResourceLoaderOptions resourceLoaderOptions)
{
const KURL& requestURL = request.url();
ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
if (m_forceDoNotAllowStoredCredentials)
resourceLoaderOptions.allowCredentials = DoNotAllowStoredCredentials;
resourceLoaderOptions.securityOrigin = m_securityOrigin;
if (m_async) {
if (!m_actualRequest.isNull())
resourceLoaderOptions.dataBufferingPolicy = BufferData;
if (m_options.timeoutMilliseconds > 0)
m_timeoutTimer.startOneShot(m_options.timeoutMilliseconds / 1000.0, BLINK_FROM_HERE);
FetchRequest newRequest(request, m_options.initiator, resourceLoaderOptions);
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
newRequest.setOriginRestriction(FetchRequest::NoOriginRestriction);
ASSERT(!resource());
if (request.requestContext() == WebURLRequest::RequestContextVideo || request.requestContext() == WebURLRequest::RequestContextAudio)
setResource(RawResource::fetchMedia(newRequest, document().fetcher()));
else if (request.requestContext() == WebURLRequest::RequestContextManifest)
setResource(RawResource::fetchManifest(newRequest, document().fetcher()));
else
setResource(RawResource::fetch(newRequest, document().fetcher()));
if (!resource()) {
InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client);
ThreadableLoaderClient* client = m_client;
clear();
client->didFail(ResourceError(errorDomainBlinkInternal, 0, requestURL.getString(), "Failed to start loading."));
return;
}
if (resource()->loader()) {
unsigned long identifier = resource()->identifier();
InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
} else {
InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client);
}
return;
}
FetchRequest fetchRequest(request, m_options.initiator, resourceLoaderOptions);
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
fetchRequest.setOriginRestriction(FetchRequest::NoOriginRestriction);
Resource* resource = RawResource::fetchSynchronously(fetchRequest, document().fetcher());
ResourceResponse response = resource ? resource->response() : ResourceResponse();
unsigned long identifier = resource ? resource->identifier() : std::numeric_limits<unsigned long>::max();
ResourceError error = resource ? resource->resourceError() : ResourceError();
InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
if (!resource) {
m_client->didFail(error);
return;
}
if (!error.isNull() && !requestURL.isLocalFile() && response.httpStatusCode() <= 0) {
m_client->didFail(error);
return;
}
if (requestURL != response.url() && !isAllowedRedirect(response.url())) {
m_client->didFailRedirectCheck();
return;
}
handleResponse(identifier, response, nullptr);
if (!m_client)
return;
SharedBuffer* data = resource->resourceBuffer();
if (data)
handleReceivedData(data->data(), data->size());
if (!m_client)
return;
handleSuccessfulFinish(identifier, 0.0);
}
Commit Message: DocumentThreadableLoader: Add guards for sync notifyFinished() in setResource()
In loadRequest(), setResource() can call clear() synchronously:
DocumentThreadableLoader::clear()
DocumentThreadableLoader::handleError()
Resource::didAddClient()
RawResource::didAddClient()
and thus |m_client| can be null while resource() isn't null after setResource(),
causing crashes (Issue 595964).
This CL checks whether |*this| is destructed and
whether |m_client| is null after setResource().
BUG=595964
Review-Url: https://codereview.chromium.org/1902683002
Cr-Commit-Position: refs/heads/master@{#391001}
CWE ID: CWE-189
Target: 1
Example 2:
Code: ZEND_API int zend_declare_property_ex(zend_class_entry *ce, const char *name, int name_length, zval *property, int access_type, const char *doc_comment, int doc_comment_len TSRMLS_DC) /* {{{ */
{
zend_property_info property_info, *property_info_ptr;
const char *interned_name;
ulong h = zend_get_hash_value(name, name_length+1);
if (!(access_type & ZEND_ACC_PPP_MASK)) {
access_type |= ZEND_ACC_PUBLIC;
}
if (access_type & ZEND_ACC_STATIC) {
if (zend_hash_quick_find(&ce->properties_info, name, name_length + 1, h, (void**)&property_info_ptr) == SUCCESS &&
(property_info_ptr->flags & ZEND_ACC_STATIC) != 0) {
property_info.offset = property_info_ptr->offset;
zval_ptr_dtor(&ce->default_static_members_table[property_info.offset]);
zend_hash_quick_del(&ce->properties_info, name, name_length + 1, h);
} else {
property_info.offset = ce->default_static_members_count++;
ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(zval*) * ce->default_static_members_count, ce->type == ZEND_INTERNAL_CLASS);
}
ce->default_static_members_table[property_info.offset] = property;
if (ce->type == ZEND_USER_CLASS) {
ce->static_members_table = ce->default_static_members_table;
}
} else {
if (zend_hash_quick_find(&ce->properties_info, name, name_length + 1, h, (void**)&property_info_ptr) == SUCCESS &&
(property_info_ptr->flags & ZEND_ACC_STATIC) == 0) {
property_info.offset = property_info_ptr->offset;
zval_ptr_dtor(&ce->default_properties_table[property_info.offset]);
zend_hash_quick_del(&ce->properties_info, name, name_length + 1, h);
} else {
property_info.offset = ce->default_properties_count++;
ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(zval*) * ce->default_properties_count, ce->type == ZEND_INTERNAL_CLASS);
}
ce->default_properties_table[property_info.offset] = property;
}
if (ce->type & ZEND_INTERNAL_CLASS) {
switch(Z_TYPE_P(property)) {
case IS_ARRAY:
case IS_OBJECT:
case IS_RESOURCE:
zend_error(E_CORE_ERROR, "Internal zval's can't be arrays, objects or resources");
break;
default:
break;
}
}
switch (access_type & ZEND_ACC_PPP_MASK) {
case ZEND_ACC_PRIVATE: {
char *priv_name;
int priv_name_length;
zend_mangle_property_name(&priv_name, &priv_name_length, ce->name, ce->name_length, name, name_length, ce->type & ZEND_INTERNAL_CLASS);
property_info.name = priv_name;
property_info.name_length = priv_name_length;
}
break;
case ZEND_ACC_PROTECTED: {
char *prot_name;
int prot_name_length;
zend_mangle_property_name(&prot_name, &prot_name_length, "*", 1, name, name_length, ce->type & ZEND_INTERNAL_CLASS);
property_info.name = prot_name;
property_info.name_length = prot_name_length;
}
break;
case ZEND_ACC_PUBLIC:
if (IS_INTERNED(name)) {
property_info.name = (char*)name;
} else {
property_info.name = ce->type & ZEND_INTERNAL_CLASS ? zend_strndup(name, name_length) : estrndup(name, name_length);
}
property_info.name_length = name_length;
break;
}
interned_name = zend_new_interned_string(property_info.name, property_info.name_length+1, 0 TSRMLS_CC);
if (interned_name != property_info.name) {
if (ce->type == ZEND_USER_CLASS) {
efree((char*)property_info.name);
} else {
free((char*)property_info.name);
}
property_info.name = interned_name;
}
property_info.flags = access_type;
property_info.h = (access_type & ZEND_ACC_PUBLIC) ? h : zend_get_hash_value(property_info.name, property_info.name_length+1);
property_info.doc_comment = doc_comment;
property_info.doc_comment_len = doc_comment_len;
property_info.ce = ce;
zend_hash_quick_update(&ce->properties_info, name, name_length+1, h, &property_info, sizeof(zend_property_info), NULL);
return SUCCESS;
}
/* }}} */
Commit Message:
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ExtensionFunction::ResponseAction UsbInterruptTransferFunction::Run() {
scoped_ptr<extensions::core_api::usb::InterruptTransfer::Params> parameters =
InterruptTransfer::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(parameters.get());
scoped_refptr<UsbDeviceHandle> device_handle =
GetDeviceHandle(parameters->handle);
if (!device_handle.get()) {
return RespondNow(Error(kErrorNoConnection));
}
const GenericTransferInfo& transfer = parameters->transfer_info;
UsbEndpointDirection direction;
size_t size = 0;
if (!ConvertDirectionFromApi(transfer.direction, &direction)) {
return RespondNow(Error(kErrorConvertDirection));
}
if (!GetTransferSize(transfer, &size)) {
return RespondNow(Error(kErrorInvalidTransferLength));
}
scoped_refptr<net::IOBuffer> buffer =
CreateBufferForTransfer(transfer, direction, size);
if (!buffer.get()) {
return RespondNow(Error(kErrorMalformedParameters));
}
int timeout = transfer.timeout ? *transfer.timeout : 0;
if (timeout < 0) {
return RespondNow(Error(kErrorInvalidTimeout));
}
device_handle->InterruptTransfer(
direction, transfer.endpoint, buffer.get(), size, timeout,
base::Bind(&UsbInterruptTransferFunction::OnCompleted, this));
return RespondLater();
}
Commit Message: Remove fallback when requesting a single USB interface.
This reverts commit 2d475d0ed37bf8f19385537ad31e361f1b21624b. The
permission broker now supports opening devices that are partially
claimed through the OpenPath method and RequestPathAccess will always
fail for these devices so the fallback path from RequestPathAccess to
OpenPath is always taken.
BUG=500057
Review URL: https://codereview.chromium.org/1227313003
Cr-Commit-Position: refs/heads/master@{#338354}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void CrosLibrary::TestApi::SetSpeechSynthesisLibrary(
SpeechSynthesisLibrary* library, bool own) {
library_->speech_synthesis_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
Target: 1
Example 2:
Code: void AudioRendererHost::OnError(media::AudioOutputController* controller,
int error_code) {
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&AudioRendererHost::DoHandleError,
this, make_scoped_refptr(controller), error_code));
}
Commit Message: Improve validation when creating audio streams.
BUG=166795
Review URL: https://codereview.chromium.org/11647012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173981 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void BooleanOrNullAttributeAttributeSetter(
v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
ALLOW_UNUSED_LOCAL(isolate);
v8::Local<v8::Object> holder = info.Holder();
ALLOW_UNUSED_LOCAL(holder);
TestObject* impl = V8TestObject::ToImpl(holder);
ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "TestObject", "booleanOrNullAttribute");
bool cpp_value = NativeValueTraits<IDLBoolean>::NativeValue(info.GetIsolate(), v8_value, exception_state);
if (exception_state.HadException())
return;
bool is_null = IsUndefinedOrNull(v8_value);
impl->setBooleanOrNullAttribute(cpp_value, is_null);
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_FUNCTION(mcrypt_module_is_block_algorithm)
{
MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
if (mcrypt_module_is_block_algorithm(module, dir) == 1) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
Target: 1
Example 2:
Code: static bool tcp_time_to_recover(struct sock *sk, int flag)
{
struct tcp_sock *tp = tcp_sk(sk);
__u32 packets_out;
int tcp_reordering = sock_net(sk)->ipv4.sysctl_tcp_reordering;
/* Trick#1: The loss is proven. */
if (tp->lost_out)
return true;
/* Not-A-Trick#2 : Classic rule... */
if (tcp_dupack_heuristics(tp) > tp->reordering)
return true;
/* Trick#4: It is still not OK... But will it be useful to delay
* recovery more?
*/
packets_out = tp->packets_out;
if (packets_out <= tp->reordering &&
tp->sacked_out >= max_t(__u32, packets_out/2, tcp_reordering) &&
!tcp_may_send_now(sk)) {
/* We have nothing to send. This connection is limited
* either by receiver window or by application.
*/
return true;
}
/* If a thin stream is detected, retransmit after first
* received dupack. Employ only if SACK is supported in order
* to avoid possible corner-case series of spurious retransmissions
* Use only if there are no unsent data.
*/
if ((tp->thin_dupack || sysctl_tcp_thin_dupack) &&
tcp_stream_is_thin(tp) && tcp_dupack_heuristics(tp) > 1 &&
tcp_is_sack(tp) && !tcp_send_head(sk))
return true;
/* Trick#6: TCP early retransmit, per RFC5827. To avoid spurious
* retransmissions due to small network reorderings, we implement
* Mitigation A.3 in the RFC and delay the retransmission for a short
* interval if appropriate.
*/
if (tp->do_early_retrans && !tp->retrans_out && tp->sacked_out &&
(tp->packets_out >= (tp->sacked_out + 1) && tp->packets_out < 4) &&
!tcp_may_send_now(sk))
return !tcp_pause_early_retransmit(sk, flag);
return false;
}
Commit Message: tcp: make challenge acks less predictable
Yue Cao claims that current host rate limiting of challenge ACKS
(RFC 5961) could leak enough information to allow a patient attacker
to hijack TCP sessions. He will soon provide details in an academic
paper.
This patch increases the default limit from 100 to 1000, and adds
some randomization so that the attacker can no longer hijack
sessions without spending a considerable amount of probes.
Based on initial analysis and patch from Linus.
Note that we also have per socket rate limiting, so it is tempting
to remove the host limit in the future.
v2: randomize the count of challenge acks per second, not the period.
Fixes: 282f23c6ee34 ("tcp: implement RFC 5961 3.2")
Reported-by: Yue Cao <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Cc: Yuchung Cheng <[email protected]>
Cc: Neal Cardwell <[email protected]>
Acked-by: Neal Cardwell <[email protected]>
Acked-by: Yuchung Cheng <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void kvm_pit_load_count(struct kvm *kvm, int channel, u32 val, int hpet_legacy_start)
{
u8 saved_mode;
if (hpet_legacy_start) {
/* save existing mode for later reenablement */
saved_mode = kvm->arch.vpit->pit_state.channels[0].mode;
kvm->arch.vpit->pit_state.channels[0].mode = 0xff; /* disable timer */
pit_load_count(kvm, channel, val);
kvm->arch.vpit->pit_state.channels[0].mode = saved_mode;
} else {
pit_load_count(kvm, channel, val);
}
}
Commit Message: KVM: x86: Improve thread safety in pit
There's a race condition in the PIT emulation code in KVM. In
__kvm_migrate_pit_timer the pit_timer object is accessed without
synchronization. If the race condition occurs at the wrong time this
can crash the host kernel.
This fixes CVE-2014-3611.
Cc: [email protected]
Signed-off-by: Andrew Honig <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void pdf_load_pages_kids(FILE *fp, pdf_t *pdf)
{
int i, id, dummy;
char *buf, *c;
long start, sz;
start = ftell(fp);
/* Load all kids for all xref tables (versions) */
for (i=0; i<pdf->n_xrefs; i++)
{
if (pdf->xrefs[i].version && (pdf->xrefs[i].end != 0))
{
fseek(fp, pdf->xrefs[i].start, SEEK_SET);
while (SAFE_F(fp, (fgetc(fp) != 't')))
; /* Iterate to trailer */
/* Get root catalog */
sz = pdf->xrefs[i].end - ftell(fp);
buf = malloc(sz + 1);
SAFE_E(fread(buf, 1, sz, fp), sz, "Failed to load /Root.\n");
buf[sz] = '\0';
if (!(c = strstr(buf, "/Root")))
{
free(buf);
continue;
}
/* Jump to catalog (root) */
id = atoi(c + strlen("/Root") + 1);
free(buf);
buf = get_object(fp, id, &pdf->xrefs[i], NULL, &dummy);
if (!buf || !(c = strstr(buf, "/Pages")))
{
free(buf);
continue;
}
/* Start at the first Pages obj and get kids */
id = atoi(c + strlen("/Pages") + 1);
load_kids(fp, id, &pdf->xrefs[i]);
free(buf);
}
}
fseek(fp, start, SEEK_SET);
}
Commit Message: Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf
CWE ID: CWE-787
Target: 1
Example 2:
Code: void V8TestObject::UseToImpl4ArgumentsCheckingIfPossibleWithNullableArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_useToImpl4ArgumentsCheckingIfPossibleWithNullableArg");
test_object_v8_internal::UseToImpl4ArgumentsCheckingIfPossibleWithNullableArgMethod(info);
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RTCPeerConnectionHandlerChromium::setRemoteDescription(PassRefPtr<RTCVoidRequest> request, PassRefPtr<RTCSessionDescriptionDescriptor> sessionDescription)
{
if (!m_webHandler)
return;
m_webHandler->setRemoteDescription(request, sessionDescription);
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SPL_METHOD(GlobIterator, count)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) {
RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL));
} else {
/* should not happen */
php_error_docref(NULL TSRMLS_CC, E_ERROR, "GlobIterator lost glob state");
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
Target: 1
Example 2:
Code: static int do_rt_sigqueueinfo(pid_t pid, int sig, siginfo_t *info)
{
/* Not even root can pretend to send signals from the kernel.
* Nor can they impersonate a kill()/tgkill(), which adds source info.
*/
if ((info->si_code >= 0 || info->si_code == SI_TKILL) &&
(task_pid_vnr(current) != pid))
return -EPERM;
info->si_signo = sig;
/* POSIX.1b doesn't mention process groups. */
return kill_proc_info(sig, info, pid);
}
Commit Message: kernel/signal.c: avoid undefined behaviour in kill_something_info
When running kill(72057458746458112, 0) in userspace I hit the following
issue.
UBSAN: Undefined behaviour in kernel/signal.c:1462:11
negation of -2147483648 cannot be represented in type 'int':
CPU: 226 PID: 9849 Comm: test Tainted: G B ---- ------- 3.10.0-327.53.58.70.x86_64_ubsan+ #116
Hardware name: Huawei Technologies Co., Ltd. RH8100 V3/BC61PBIA, BIOS BLHSV028 11/11/2014
Call Trace:
dump_stack+0x19/0x1b
ubsan_epilogue+0xd/0x50
__ubsan_handle_negate_overflow+0x109/0x14e
SYSC_kill+0x43e/0x4d0
SyS_kill+0xe/0x10
system_call_fastpath+0x16/0x1b
Add code to avoid the UBSAN detection.
[[email protected]: tweak comment]
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: zhongjiang <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: Michal Hocko <[email protected]>
Cc: Vlastimil Babka <[email protected]>
Cc: Xishi Qiu <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int hid_resume_common(struct hid_device *hid, bool driver_suspended)
{
int status = 0;
hid_restart_io(hid);
if (driver_suspended && hid->driver && hid->driver->resume)
status = hid->driver->resume(hid);
return status;
}
Commit Message: HID: usbhid: fix out-of-bounds bug
The hid descriptor identifies the length and type of subordinate
descriptors for a device. If the received hid descriptor is smaller than
the size of the struct hid_descriptor, it is possible to cause
out-of-bounds.
In addition, if bNumDescriptors of the hid descriptor have an incorrect
value, this can also cause out-of-bounds while approaching hdesc->desc[n].
So check the size of hid descriptor and bNumDescriptors.
BUG: KASAN: slab-out-of-bounds in usbhid_parse+0x9b1/0xa20
Read of size 1 at addr ffff88006c5f8edf by task kworker/1:2/1261
CPU: 1 PID: 1261 Comm: kworker/1:2 Not tainted
4.14.0-rc1-42251-gebb2c2437d80 #169
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
Workqueue: usb_hub_wq hub_event
Call Trace:
__dump_stack lib/dump_stack.c:16
dump_stack+0x292/0x395 lib/dump_stack.c:52
print_address_description+0x78/0x280 mm/kasan/report.c:252
kasan_report_error mm/kasan/report.c:351
kasan_report+0x22f/0x340 mm/kasan/report.c:409
__asan_report_load1_noabort+0x19/0x20 mm/kasan/report.c:427
usbhid_parse+0x9b1/0xa20 drivers/hid/usbhid/hid-core.c:1004
hid_add_device+0x16b/0xb30 drivers/hid/hid-core.c:2944
usbhid_probe+0xc28/0x1100 drivers/hid/usbhid/hid-core.c:1369
usb_probe_interface+0x35d/0x8e0 drivers/usb/core/driver.c:361
really_probe drivers/base/dd.c:413
driver_probe_device+0x610/0xa00 drivers/base/dd.c:557
__device_attach_driver+0x230/0x290 drivers/base/dd.c:653
bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463
__device_attach+0x26e/0x3d0 drivers/base/dd.c:710
device_initial_probe+0x1f/0x30 drivers/base/dd.c:757
bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523
device_add+0xd0b/0x1660 drivers/base/core.c:1835
usb_set_configuration+0x104e/0x1870 drivers/usb/core/message.c:1932
generic_probe+0x73/0xe0 drivers/usb/core/generic.c:174
usb_probe_device+0xaf/0xe0 drivers/usb/core/driver.c:266
really_probe drivers/base/dd.c:413
driver_probe_device+0x610/0xa00 drivers/base/dd.c:557
__device_attach_driver+0x230/0x290 drivers/base/dd.c:653
bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463
__device_attach+0x26e/0x3d0 drivers/base/dd.c:710
device_initial_probe+0x1f/0x30 drivers/base/dd.c:757
bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523
device_add+0xd0b/0x1660 drivers/base/core.c:1835
usb_new_device+0x7b8/0x1020 drivers/usb/core/hub.c:2457
hub_port_connect drivers/usb/core/hub.c:4903
hub_port_connect_change drivers/usb/core/hub.c:5009
port_event drivers/usb/core/hub.c:5115
hub_event+0x194d/0x3740 drivers/usb/core/hub.c:5195
process_one_work+0xc7f/0x1db0 kernel/workqueue.c:2119
worker_thread+0x221/0x1850 kernel/workqueue.c:2253
kthread+0x3a1/0x470 kernel/kthread.c:231
ret_from_fork+0x2a/0x40 arch/x86/entry/entry_64.S:431
Cc: [email protected]
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: Jaejoong Kim <[email protected]>
Tested-by: Andrey Konovalov <[email protected]>
Acked-by: Alan Stern <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void get_nb10(ut8* dbg_data, SCV_NB10_HEADER* res) {
const int nb10sz = 16;
memcpy (res, dbg_data, nb10sz);
res->file_name = (ut8*) strdup ((const char*) dbg_data + nb10sz);
}
Commit Message: Fix crash in pe
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int mxf_read_header(AVFormatContext *s)
{
MXFContext *mxf = s->priv_data;
KLVPacket klv;
int64_t essence_offset = 0;
int ret;
mxf->last_forward_tell = INT64_MAX;
mxf->edit_units_per_packet = 1;
if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {
av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
return AVERROR_INVALIDDATA;
}
avio_seek(s->pb, -14, SEEK_CUR);
mxf->fc = s;
mxf->run_in = avio_tell(s->pb);
mxf_read_random_index_pack(s);
while (!avio_feof(s->pb)) {
const MXFMetadataReadTableEntry *metadata;
if (klv_read_packet(&klv, s->pb) < 0) {
/* EOF - seek to previous partition or stop */
if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
break;
else
continue;
}
PRINT_KEY(s, "read header", klv.key);
av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
IS_KLV_KEY(klv.key, mxf_avid_essence_element_key) ||
IS_KLV_KEY(klv.key, mxf_system_item_key)) {
if (!mxf->current_partition) {
av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to first PartitionPack\n");
return AVERROR_INVALIDDATA;
}
if (!mxf->current_partition->essence_offset) {
/* for OP1a we compute essence_offset
* for OPAtom we point essence_offset after the KL (usually op1a_essence_offset + 20 or 25)
* TODO: for OP1a we could eliminate this entire if statement, always stopping parsing at op1a_essence_offset
* for OPAtom we still need the actual essence_offset though (the KL's length can vary)
*/
int64_t op1a_essence_offset =
round_to_kag(mxf->current_partition->this_partition +
mxf->current_partition->pack_length, mxf->current_partition->kag_size) +
round_to_kag(mxf->current_partition->header_byte_count, mxf->current_partition->kag_size) +
round_to_kag(mxf->current_partition->index_byte_count, mxf->current_partition->kag_size);
if (mxf->op == OPAtom) {
/* point essence_offset to the actual data
* OPAtom has all the essence in one big KLV
*/
mxf->current_partition->essence_offset = avio_tell(s->pb);
mxf->current_partition->essence_length = klv.length;
} else {
/* NOTE: op1a_essence_offset may be less than to klv.offset (C0023S01.mxf) */
mxf->current_partition->essence_offset = op1a_essence_offset;
}
}
if (!essence_offset)
essence_offset = klv.offset;
/* seek to footer, previous partition or stop */
if (mxf_parse_handle_essence(mxf) <= 0)
break;
continue;
} else if (mxf_is_partition_pack_key(klv.key) && mxf->current_partition) {
/* next partition pack - keep going, seek to previous partition or stop */
if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
break;
else if (mxf->parsing_backward)
continue;
/* we're still parsing forward. proceed to parsing this partition pack */
}
for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
if (IS_KLV_KEY(klv.key, metadata->key)) {
if ((ret = mxf_parse_klv(mxf, klv, metadata->read, metadata->ctx_size, metadata->type)) < 0)
goto fail;
break;
}
}
if (!metadata->read) {
av_log(s, AV_LOG_VERBOSE, "Dark key " PRIxUID "\n",
UID_ARG(klv.key));
avio_skip(s->pb, klv.length);
}
}
/* FIXME avoid seek */
if (!essence_offset) {
av_log(s, AV_LOG_ERROR, "no essence\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
avio_seek(s->pb, essence_offset, SEEK_SET);
mxf_compute_essence_containers(mxf);
/* we need to do this before computing the index tables
* to be able to fill in zero IndexDurations with st->duration */
if ((ret = mxf_parse_structural_metadata(mxf)) < 0)
goto fail;
mxf_handle_missing_index_segment(mxf);
if ((ret = mxf_compute_index_tables(mxf)) < 0)
goto fail;
if (mxf->nb_index_tables > 1) {
/* TODO: look up which IndexSID to use via EssenceContainerData */
av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n",
mxf->nb_index_tables, mxf->index_tables[0].index_sid);
} else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom) {
av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
mxf_handle_small_eubc(s);
return 0;
fail:
mxf_read_close(s);
return ret;
}
Commit Message: avformat/mxfdec: Fix DoS issues in mxf_read_index_entry_array()
Fixes: 20170829A.mxf
Co-Author: 张洪亮(望初)" <[email protected]>
Found-by: Xiaohei and Wangchu from Alibaba Security Team
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-834
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: BlockEntry::~BlockEntry()
{
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WT_InterpolateMono (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_I32 *pMixBuffer;
const EAS_I8 *pLoopEnd;
const EAS_I8 *pCurrentPhaseInt;
EAS_I32 numSamples;
EAS_I32 gain;
EAS_I32 gainIncrement;
EAS_I32 currentPhaseFrac;
EAS_I32 phaseInc;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 tmp2;
EAS_I8 *pLoopStart;
numSamples = pWTIntFrame->numSamples;
pMixBuffer = pWTIntFrame->pMixBuffer;
/* calculate gain increment */
gainIncrement = (pWTIntFrame->gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS);
if (gainIncrement < 0)
gainIncrement++;
gain = pWTIntFrame->prevGain << 16;
pCurrentPhaseInt = pWTVoice->pPhaseAccum;
currentPhaseFrac = pWTVoice->phaseFrac;
phaseInc = pWTIntFrame->phaseIncrement;
pLoopStart = pWTVoice->pLoopStart;
pLoopEnd = pWTVoice->pLoopEnd + 1;
InterpolationLoop:
tmp0 = (EAS_I32)(pCurrentPhaseInt - pLoopEnd);
if (tmp0 >= 0)
pCurrentPhaseInt = pLoopStart + tmp0;
tmp0 = *pCurrentPhaseInt;
tmp1 = *(pCurrentPhaseInt + 1);
tmp2 = phaseInc + currentPhaseFrac;
tmp1 = tmp1 - tmp0;
tmp1 = tmp1 * currentPhaseFrac;
tmp1 = tmp0 + (tmp1 >> NUM_EG1_FRAC_BITS);
pCurrentPhaseInt += (tmp2 >> NUM_PHASE_FRAC_BITS);
currentPhaseFrac = tmp2 & PHASE_FRAC_MASK;
gain += gainIncrement;
tmp2 = (gain >> SYNTH_UPDATE_PERIOD_IN_BITS);
tmp0 = *pMixBuffer;
tmp2 = tmp1 * tmp2;
tmp2 = (tmp2 >> 9);
tmp0 = tmp2 + tmp0;
*pMixBuffer++ = tmp0;
numSamples--;
if (numSamples > 0)
goto InterpolationLoop;
pWTVoice->pPhaseAccum = pCurrentPhaseInt;
pWTVoice->phaseFrac = currentPhaseFrac;
/*lint -e{702} <avoid divide>*/
pWTVoice->gain = (EAS_I16)(gain >> SYNTH_UPDATE_PERIOD_IN_BITS);
}
Commit Message: Sonivox: sanity check numSamples.
Bug: 26366256
Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc
CWE ID: CWE-119
Target: 1
Example 2:
Code: error::Error GLES2DecoderPassthroughImpl::DoIsSampler(GLuint sampler,
uint32_t* result) {
*result = api()->glIsSamplerFn(GetSamplerServiceID(sampler, resources_));
return error::kNoError;
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void V8TestObject::VoidMethodSequenceTestInterfaceEmptyArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_voidMethodSequenceTestInterfaceEmptyArg");
test_object_v8_internal::VoidMethodSequenceTestInterfaceEmptyArgMethod(info);
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int DH_check_pub_key(const DH *dh, const BIGNUM *pub_key, int *ret)
{
int ok = 0;
BIGNUM *q = NULL;
*ret = 0;
q = BN_new();
if (q == NULL)
goto err;
BN_set_word(q, 1);
if (BN_cmp(pub_key, q) <= 0)
*ret |= DH_CHECK_PUBKEY_TOO_SMALL;
BN_copy(q, dh->p);
BN_sub_word(q, 1);
if (BN_cmp(pub_key, q) >= 0)
*ret |= DH_CHECK_PUBKEY_TOO_LARGE;
ok = 1;
err:
if (q != NULL)
BN_free(q);
return (ok);
}
Commit Message:
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void floppy_release(struct gendisk *disk, fmode_t mode)
{
int drive = (long)disk->private_data;
mutex_lock(&floppy_mutex);
mutex_lock(&open_lock);
if (!UDRS->fd_ref--) {
DPRINT("floppy_release with fd_ref == 0");
UDRS->fd_ref = 0;
}
if (!UDRS->fd_ref)
opened_bdev[drive] = NULL;
mutex_unlock(&open_lock);
mutex_unlock(&floppy_mutex);
}
Commit Message: floppy: don't write kernel-only members to FDRAWCMD ioctl output
Do not leak kernel-only floppy_raw_cmd structure members to userspace.
This includes the linked-list pointer and the pointer to the allocated
DMA space.
Signed-off-by: Matthew Daley <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: gs_main_init1(gs_main_instance * minst)
{
if (minst->init_done < 1) {
gs_dual_memory_t idmem;
int code =
ialloc_init(&idmem, minst->heap,
minst->memory_clump_size, gs_have_level2());
if (code < 0)
return code;
code = gs_lib_init1((gs_memory_t *)idmem.space_system);
if (code < 0)
return code;
alloc_save_init(&idmem);
{
gs_memory_t *mem = (gs_memory_t *)idmem.space_system;
name_table *nt = names_init(minst->name_table_size,
idmem.space_system);
if (nt == 0)
return_error(gs_error_VMerror);
mem->gs_lib_ctx->gs_name_table = nt;
code = gs_register_struct_root(mem, NULL,
(void **)&mem->gs_lib_ctx->gs_name_table,
"the_gs_name_table");
"the_gs_name_table");
if (code < 0)
return code;
}
code = obj_init(&minst->i_ctx_p, &idmem); /* requires name_init */
if (code < 0)
if (code < 0)
return code;
code = i_iodev_init(minst->i_ctx_p);
if (code < 0)
return code;
minst->init_done = 1;
}
return 0;
}
Commit Message:
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: TestWebKitPlatformSupport::TestWebKitPlatformSupport(bool unit_test_mode)
: unit_test_mode_(unit_test_mode) {
v8::V8::SetCounterFunction(base::StatsTable::FindLocation);
WebKit::initialize(this);
WebKit::setLayoutTestMode(true);
WebKit::WebSecurityPolicy::registerURLSchemeAsLocal(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebKit::WebSecurityPolicy::registerURLSchemeAsNoAccess(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebScriptController::enableV8SingleThreadMode();
WebKit::WebRuntimeFeatures::enableSockets(true);
WebKit::WebRuntimeFeatures::enableApplicationCache(true);
WebKit::WebRuntimeFeatures::enableDatabase(true);
WebKit::WebRuntimeFeatures::enableDataTransferItems(true);
WebKit::WebRuntimeFeatures::enablePushState(true);
WebKit::WebRuntimeFeatures::enableNotifications(true);
WebKit::WebRuntimeFeatures::enableTouch(true);
WebKit::WebRuntimeFeatures::enableGamepad(true);
bool enable_media = false;
FilePath module_path;
if (PathService::Get(base::DIR_MODULE, &module_path)) {
#if defined(OS_MACOSX)
if (base::mac::AmIBundled())
module_path = module_path.DirName().DirName().DirName();
#endif
if (media::InitializeMediaLibrary(module_path))
enable_media = true;
}
WebKit::WebRuntimeFeatures::enableMediaPlayer(enable_media);
LOG_IF(WARNING, !enable_media) << "Failed to initialize the media library.\n";
WebKit::WebRuntimeFeatures::enableGeolocation(false);
if (!appcache_dir_.CreateUniqueTempDir()) {
LOG(WARNING) << "Failed to create a temp dir for the appcache, "
"using in-memory storage.";
DCHECK(appcache_dir_.path().empty());
}
SimpleAppCacheSystem::InitializeOnUIThread(appcache_dir_.path());
WebKit::WebDatabase::setObserver(&database_system_);
blob_registry_ = new TestShellWebBlobRegistryImpl();
file_utilities_.set_sandbox_enabled(false);
if (!file_system_root_.CreateUniqueTempDir()) {
LOG(WARNING) << "Failed to create a temp dir for the filesystem."
"FileSystem feature will be disabled.";
DCHECK(file_system_root_.path().empty());
}
#if defined(OS_WIN)
SetThemeEngine(NULL);
#endif
net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL;
net::CookieMonster::EnableFileScheme();
SimpleResourceLoaderBridge::Init(FilePath(), cache_mode, true);
webkit_glue::SetJavaScriptFlags(" --expose-gc");
WebScriptController::registerExtension(extensions_v8::GCExtension::Get());
}
Commit Message: Use a new scheme for swapping out RenderViews.
BUG=118664
TEST=none
Review URL: http://codereview.chromium.org/9720004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: file_deleted_callback (GFile *file,
GError *error,
gpointer callback_data)
{
DeleteData *data = callback_data;
CommonJob *job;
SourceInfo *source_info;
TransferInfo *transfer_info;
GFileType file_type;
char *primary;
char *secondary;
char *details = NULL;
int response;
job = data->job;
source_info = data->source_info;
transfer_info = data->transfer_info;
data->transfer_info->num_files++;
if (error == NULL)
{
nautilus_file_changes_queue_file_removed (file);
report_delete_progress (data->job, data->source_info, data->transfer_info);
return;
}
if (job_aborted (job) ||
job->skip_all_error ||
should_skip_file (job, file) ||
should_skip_readdir_error (job, file))
{
return;
}
primary = f (_("Error while deleting."));
file_type = g_file_query_file_type (file,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable);
if (file_type == G_FILE_TYPE_DIRECTORY)
{
secondary = IS_IO_ERROR (error, PERMISSION_DENIED) ?
f (_("There was an error deleting the folder “%B”."),
file) :
f (_("You do not have sufficient permissions to delete the folder “%B”."),
file);
}
else
{
secondary = IS_IO_ERROR (error, PERMISSION_DENIED) ?
f (_("There was an error deleting the file “%B”."),
file) :
f (_("You do not have sufficient permissions to delete the file “%B”."),
file);
}
details = error->message;
response = run_cancel_or_skip_warning (job,
primary,
secondary,
details,
source_info->num_files,
source_info->num_files - transfer_info->num_files);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1)
{
/* skip all */
job->skip_all_error = TRUE;
}
}
Commit Message: mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void write_response(ESPState *s)
{
trace_esp_write_response(s->status);
s->ti_buf[0] = s->status;
s->ti_buf[1] = 0;
if (s->dma) {
s->dma_memory_write(s->dma_opaque, s->ti_buf, 2);
s->rregs[ESP_RSTAT] = STAT_TC | STAT_ST;
s->rregs[ESP_RINTR] = INTR_BS | INTR_FC;
s->rregs[ESP_RSEQ] = SEQ_CD;
} else {
s->ti_size = 2;
s->ti_rptr = 0;
s->ti_wptr = 0;
s->rregs[ESP_RFLAGS] = 2;
}
esp_raise_irq(s);
}
Commit Message:
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SPL_METHOD(FilesystemIterator, key)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (SPL_FILE_DIR_KEY(intern, SPL_FILE_DIR_KEY_AS_FILENAME)) {
RETURN_STRING(intern->u.dir.entry.d_name, 1);
} else {
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
RETURN_STRINGL(intern->file_name, intern->file_name_len, 1);
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
Target: 1
Example 2:
Code: static int tun_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t total_len,
int flags)
{
struct tun_struct *tun = container_of(sock, struct tun_struct, socket);
int ret;
if (flags & ~(MSG_DONTWAIT|MSG_TRUNC))
return -EINVAL;
ret = tun_do_read(tun, iocb, m->msg_iov, total_len,
flags & MSG_DONTWAIT);
if (ret > total_len) {
m->msg_flags |= MSG_TRUNC;
ret = flags & MSG_TRUNC ? ret : total_len;
}
return ret;
}
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
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ResourceDispatcherHostImpl::ResumeDeferredRequest(int child_id,
int request_id) {
PauseRequest(child_id, request_id, false);
}
Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T>
This change refines r137676.
BUG=122654
TEST=browser_test
Review URL: https://chromiumcodereview.appspot.com/10332233
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DocumentLoader::CommitNavigation(const AtomicString& mime_type,
const KURL& overriding_url) {
if (state_ != kProvisional)
return;
if (!GetFrameLoader().StateMachine()->CreatingInitialEmptyDocument()) {
SetHistoryItemStateForCommit(
GetFrameLoader().GetDocumentLoader()->GetHistoryItem(), load_type_,
HistoryNavigationType::kDifferentDocument);
}
DCHECK_EQ(state_, kProvisional);
GetFrameLoader().CommitProvisionalLoad();
if (!frame_)
return;
const AtomicString& encoding = GetResponse().TextEncodingName();
Document* owner_document = nullptr;
if (Document::ShouldInheritSecurityOriginFromOwner(Url())) {
Frame* owner_frame = frame_->Tree().Parent();
if (!owner_frame)
owner_frame = frame_->Loader().Opener();
if (owner_frame && owner_frame->IsLocalFrame())
owner_document = ToLocalFrame(owner_frame)->GetDocument();
}
DCHECK(frame_->GetPage());
ParserSynchronizationPolicy parsing_policy = kAllowAsynchronousParsing;
if (!Document::ThreadedParsingEnabledForTesting())
parsing_policy = kForceSynchronousParsing;
InstallNewDocument(Url(), owner_document,
frame_->ShouldReuseDefaultView(Url())
? WebGlobalObjectReusePolicy::kUseExisting
: WebGlobalObjectReusePolicy::kCreateNew,
mime_type, encoding, InstallNewDocumentReason::kNavigation,
parsing_policy, overriding_url);
parser_->SetDocumentWasLoadedAsPartOfNavigation();
if (request_.WasDiscarded())
frame_->GetDocument()->SetWasDiscarded(true);
frame_->GetDocument()->MaybeHandleHttpRefresh(
response_.HttpHeaderField(HTTPNames::Refresh),
Document::kHttpRefreshFromHeader);
}
Commit Message: Prevent sandboxed documents from reusing the default window
Bug: 377995
Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541
Reviewed-on: https://chromium-review.googlesource.com/983558
Commit-Queue: Andy Paicu <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#567663}
CWE ID: CWE-285
Target: 1
Example 2:
Code: nvmet_fc_fodnum(struct nvmet_fc_fcp_iod *fodptr)
{
return (fodptr - fodptr->queue->fod);
}
Commit Message: nvmet-fc: ensure target queue id within range.
When searching for queue id's ensure they are within the expected range.
Signed-off-by: James Smart <[email protected]>
Signed-off-by: Christoph Hellwig <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: rx_cache_insert(netdissect_options *ndo,
const u_char *bp, const struct ip *ip, int dport)
{
struct rx_cache_entry *rxent;
const struct rx_header *rxh = (const struct rx_header *) bp;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t)))
return;
rxent = &rx_cache[rx_cache_next];
if (++rx_cache_next >= RX_CACHE_SIZE)
rx_cache_next = 0;
rxent->callnum = EXTRACT_32BITS(&rxh->callNumber);
UNALIGNED_MEMCPY(&rxent->client, &ip->ip_src, sizeof(uint32_t));
UNALIGNED_MEMCPY(&rxent->server, &ip->ip_dst, sizeof(uint32_t));
rxent->dport = dport;
rxent->serviceId = EXTRACT_32BITS(&rxh->serviceId);
rxent->opcode = EXTRACT_32BITS(bp + sizeof(struct rx_header));
}
Commit Message: (for 4.9.3) CVE-2018-14466/Rx: fix an over-read bug
In rx_cache_insert() and rx_cache_find() properly read the serviceId
field of the rx_header structure as a 16-bit integer. When those
functions tried to read 32 bits the extra 16 bits could be outside of
the bounds checked in rx_print() for the rx_header structure, as
serviceId is the last field in that structure.
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GpuChannel::OnInitialize(base::ProcessHandle renderer_process) {
DCHECK(!renderer_process_);
if (base::GetProcId(renderer_process) == renderer_pid_)
renderer_process_ = renderer_process;
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: static void flush_multipath_work(struct multipath *m)
{
flush_workqueue(kmpath_handlerd);
multipath_wait_for_pg_init_completion(m);
flush_workqueue(kmultipathd);
flush_work_sync(&m->trigger_event);
}
Commit Message: dm: do not forward ioctls from logical volumes to the underlying device
A logical volume can map to just part of underlying physical volume.
In this case, it must be treated like a partition.
Based on a patch from Alasdair G Kergon.
Cc: Alasdair G Kergon <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool ClassicPendingScript::IsCurrentlyStreaming() const {
return is_currently_streaming_;
}
Commit Message: Check CORS using PassesAccessControlCheck() with supplied SecurityOrigin
Partial revert of https://chromium-review.googlesource.com/535694.
Bug: 799477
Change-Id: I878bb9bcb83afaafe8601293db9aa644fc5929b3
Reviewed-on: https://chromium-review.googlesource.com/898427
Commit-Queue: Hiroshige Hayashizaki <[email protected]>
Reviewed-by: Kouhei Ueno <[email protected]>
Reviewed-by: Yutaka Hirano <[email protected]>
Reviewed-by: Takeshi Yoshino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#535176}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void opj_get_encoding_parameters(const opj_image_t *p_image,
const opj_cp_t *p_cp,
OPJ_UINT32 p_tileno,
OPJ_INT32 * p_tx0,
OPJ_INT32 * p_tx1,
OPJ_INT32 * p_ty0,
OPJ_INT32 * p_ty1,
OPJ_UINT32 * p_dx_min,
OPJ_UINT32 * p_dy_min,
OPJ_UINT32 * p_max_prec,
OPJ_UINT32 * p_max_res)
{
/* loop */
OPJ_UINT32 compno, resno;
/* pointers */
const opj_tcp_t *l_tcp = 00;
const opj_tccp_t * l_tccp = 00;
const opj_image_comp_t * l_img_comp = 00;
/* position in x and y of tile */
OPJ_UINT32 p, q;
/* preconditions */
assert(p_cp != 00);
assert(p_image != 00);
assert(p_tileno < p_cp->tw * p_cp->th);
/* initializations */
l_tcp = &p_cp->tcps [p_tileno];
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
/* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */
p = p_tileno % p_cp->tw;
q = p_tileno / p_cp->tw;
/* find extent of tile */
*p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx),
(OPJ_INT32)p_image->x0);
*p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx),
(OPJ_INT32)p_image->x1);
*p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy),
(OPJ_INT32)p_image->y0);
*p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy),
(OPJ_INT32)p_image->y1);
/* max precision is 0 (can only grow) */
*p_max_prec = 0;
*p_max_res = 0;
/* take the largest value for dx_min and dy_min */
*p_dx_min = 0x7fffffff;
*p_dy_min = 0x7fffffff;
for (compno = 0; compno < p_image->numcomps; ++compno) {
/* arithmetic variables to calculate */
OPJ_UINT32 l_level_no;
OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1;
OPJ_INT32 l_px0, l_py0, l_px1, py1;
OPJ_UINT32 l_pdx, l_pdy;
OPJ_UINT32 l_pw, l_ph;
OPJ_UINT32 l_product;
OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;
l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx);
l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy);
l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx);
l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy);
if (l_tccp->numresolutions > *p_max_res) {
*p_max_res = l_tccp->numresolutions;
}
/* use custom size for precincts */
for (resno = 0; resno < l_tccp->numresolutions; ++resno) {
OPJ_UINT32 l_dx, l_dy;
/* precinct width and height */
l_pdx = l_tccp->prcw[resno];
l_pdy = l_tccp->prch[resno];
l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno));
l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno));
/* take the minimum size for dx for each comp and resolution */
*p_dx_min = opj_uint_min(*p_dx_min, l_dx);
*p_dy_min = opj_uint_min(*p_dy_min, l_dy);
/* various calculations of extents */
l_level_no = l_tccp->numresolutions - 1 - resno;
l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no);
l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no);
l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no);
l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no);
l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx;
l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy;
l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx;
py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy;
l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx);
l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy);
l_product = l_pw * l_ph;
/* update precision */
if (l_product > *p_max_prec) {
*p_max_prec = l_product;
}
}
++l_img_comp;
++l_tccp;
}
}
Commit Message: [OPENJP2] change the way to compute *p_tx0, *p_tx1, *p_ty0, *p_ty1 in function
opj_get_encoding_parameters
Signed-off-by: Young_X <[email protected]>
CWE ID: CWE-190
Target: 1
Example 2:
Code: ModuleExport void UnregisterEXRImage(void)
{
(void) UnregisterMagickInfo("EXR");
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset)
{
if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
return false;
bool isControlClip = hasControlClip();
bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
if (!isControlClip && !isOverflowClip)
return false;
if (paintInfo.phase == PaintPhaseOutline)
paintInfo.phase = PaintPhaseChildOutlines;
else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
paintInfo.phase = PaintPhaseBlockBackground;
paintObject(paintInfo, accumulatedOffset);
paintInfo.phase = PaintPhaseChildBlockBackgrounds;
}
IntRect clipRect(isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset));
paintInfo.context->save();
if (style()->hasBorderRadius())
paintInfo.context->addRoundedRectClip(style()->getRoundedBorderFor(IntRect(accumulatedOffset, size())));
paintInfo.context->clip(clipRect);
return true;
}
Commit Message: Source/WebCore: Fix for bug 64046 - Wrong image height in absolutely positioned div in
relatively positioned parent with bottom padding.
https://bugs.webkit.org/show_bug.cgi?id=64046
Patch by Kulanthaivel Palanichamy <[email protected]> on 2011-07-21
Reviewed by David Hyatt.
Test: fast/css/absolute-child-with-percent-height-inside-relative-parent.html
* rendering/RenderBox.cpp:
(WebCore::RenderBox::availableLogicalHeightUsing):
LayoutTests: Test to cover absolutely positioned child with percentage height
in relatively positioned parent with bottom padding.
https://bugs.webkit.org/show_bug.cgi?id=64046
Patch by Kulanthaivel Palanichamy <[email protected]> on 2011-07-21
Reviewed by David Hyatt.
* fast/css/absolute-child-with-percent-height-inside-relative-parent-expected.txt: Added.
* fast/css/absolute-child-with-percent-height-inside-relative-parent.html: Added.
git-svn-id: svn://svn.chromium.org/blink/trunk@91533 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static ssize_t read_mem(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
phys_addr_t p = *ppos;
ssize_t read, sz;
void *ptr;
if (p != *ppos)
return 0;
if (!valid_phys_addr_range(p, count))
return -EFAULT;
read = 0;
#ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED
/* we don't have page 0 mapped on sparc and m68k.. */
if (p < PAGE_SIZE) {
sz = size_inside_page(p, count);
if (sz > 0) {
if (clear_user(buf, sz))
return -EFAULT;
buf += sz;
p += sz;
count -= sz;
read += sz;
}
}
#endif
while (count > 0) {
unsigned long remaining;
sz = size_inside_page(p, count);
if (!range_is_allowed(p >> PAGE_SHIFT, count))
return -EPERM;
/*
* On ia64 if a page has been mapped somewhere as uncached, then
* it must also be accessed uncached by the kernel or data
* corruption may occur.
*/
ptr = xlate_dev_mem_ptr(p);
if (!ptr)
return -EFAULT;
remaining = copy_to_user(buf, ptr, sz);
unxlate_dev_mem_ptr(p, ptr);
if (remaining)
return -EFAULT;
buf += sz;
p += sz;
count -= sz;
read += sz;
}
*ppos += read;
return read;
}
Commit Message: mm: Tighten x86 /dev/mem with zeroing reads
Under CONFIG_STRICT_DEVMEM, reading System RAM through /dev/mem is
disallowed. However, on x86, the first 1MB was always allowed for BIOS
and similar things, regardless of it actually being System RAM. It was
possible for heap to end up getting allocated in low 1MB RAM, and then
read by things like x86info or dd, which would trip hardened usercopy:
usercopy: kernel memory exposure attempt detected from ffff880000090000 (dma-kmalloc-256) (4096 bytes)
This changes the x86 exception for the low 1MB by reading back zeros for
System RAM areas instead of blindly allowing them. More work is needed to
extend this to mmap, but currently mmap doesn't go through usercopy, so
hardened usercopy won't Oops the kernel.
Reported-by: Tommi Rantala <[email protected]>
Tested-by: Tommi Rantala <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
CWE ID: CWE-732
Target: 1
Example 2:
Code: PHP_METHOD(Phar, getSupportedSignatures)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
add_next_index_stringl(return_value, "MD5", 3);
add_next_index_stringl(return_value, "SHA-1", 5);
#ifdef PHAR_HASH_OK
add_next_index_stringl(return_value, "SHA-256", 7);
add_next_index_stringl(return_value, "SHA-512", 7);
#endif
#if PHAR_HAVE_OPENSSL
add_next_index_stringl(return_value, "OpenSSL", 7);
#else
if (zend_hash_str_exists(&module_registry, "openssl", sizeof("openssl")-1)) {
add_next_index_stringl(return_value, "OpenSSL", 7);
}
#endif
}
Commit Message:
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void gdImageLine (gdImagePtr im, int x1, int y1, int x2, int y2, int color)
{
int dx, dy, incr1, incr2, d, x, y, xend, yend, xdirflag, ydirflag;
int wid;
int w, wstart;
int thick = im->thick;
if (color == gdAntiAliased) {
/*
gdAntiAliased passed as color: use the much faster, much cheaper
and equally attractive gdImageAALine implementation. That
clips too, so don't clip twice.
*/
gdImageAALine(im, x1, y1, x2, y2, im->AA_color);
return;
}
/* 2.0.10: Nick Atty: clip to edges of drawing rectangle, return if no points need to be drawn */
if (!clip_1d(&x1,&y1,&x2,&y2,gdImageSX(im)) || !clip_1d(&y1,&x1,&y2,&x2,gdImageSY(im))) {
return;
}
dx = abs (x2 - x1);
dy = abs (y2 - y1);
if (dx == 0) {
gdImageVLine(im, x1, y1, y2, color);
return;
} else if (dy == 0) {
gdImageHLine(im, y1, x1, x2, color);
return;
}
if (dy <= dx) {
/* More-or-less horizontal. use wid for vertical stroke */
/* Doug Claar: watch out for NaN in atan2 (2.0.5) */
if ((dx == 0) && (dy == 0)) {
wid = 1;
} else {
/* 2.0.12: Michael Schwartz: divide rather than multiply;
TBB: but watch out for /0! */
double ac = cos (atan2 (dy, dx));
if (ac != 0) {
wid = thick / ac;
} else {
wid = 1;
}
if (wid == 0) {
wid = 1;
}
}
d = 2 * dy - dx;
incr1 = 2 * dy;
incr2 = 2 * (dy - dx);
if (x1 > x2) {
x = x2;
y = y2;
ydirflag = (-1);
xend = x1;
} else {
x = x1;
y = y1;
ydirflag = 1;
xend = x2;
}
/* Set up line thickness */
wstart = y - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel(im, x, w, color);
}
if (((y2 - y1) * ydirflag) > 0) {
while (x < xend) {
x++;
if (d < 0) {
d += incr1;
} else {
y++;
d += incr2;
}
wstart = y - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel (im, x, w, color);
}
}
} else {
while (x < xend) {
x++;
if (d < 0) {
d += incr1;
} else {
y--;
d += incr2;
}
wstart = y - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel (im, x, w, color);
}
}
}
} else {
/* More-or-less vertical. use wid for horizontal stroke */
/* 2.0.12: Michael Schwartz: divide rather than multiply;
TBB: but watch out for /0! */
double as = sin (atan2 (dy, dx));
if (as != 0) {
wid = thick / as;
} else {
wid = 1;
}
if (wid == 0) {
wid = 1;
}
d = 2 * dx - dy;
incr1 = 2 * dx;
incr2 = 2 * (dx - dy);
if (y1 > y2) {
y = y2;
x = x2;
yend = y1;
xdirflag = (-1);
} else {
y = y1;
x = x1;
yend = y2;
xdirflag = 1;
}
/* Set up line thickness */
wstart = x - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel (im, w, y, color);
}
if (((x2 - x1) * xdirflag) > 0) {
while (y < yend) {
y++;
if (d < 0) {
d += incr1;
} else {
x++;
d += incr2;
}
wstart = x - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel (im, w, y, color);
}
}
} else {
while (y < yend) {
y++;
if (d < 0) {
d += incr1;
} else {
x--;
d += incr2;
}
wstart = x - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel (im, w, y, color);
}
}
}
}
}
Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void TabStrip::ChangeTabGroup(int model_index,
base::Optional<int> old_group,
base::Optional<int> new_group) {
if (new_group.has_value() && !group_headers_[new_group.value()]) {
const TabGroupData* group_data =
controller_->GetDataForGroup(new_group.value());
auto header = std::make_unique<TabGroupHeader>(group_data->title());
header->set_owned_by_client();
AddChildView(header.get());
group_headers_[new_group.value()] = std::move(header);
}
if (old_group.has_value() &&
controller_->ListTabsInGroup(old_group.value()).size() == 0) {
group_headers_.erase(old_group.value());
}
UpdateIdealBounds();
AnimateToIdealBounds();
}
Commit Message: Paint tab groups with the group color.
* The background of TabGroupHeader now uses the group color.
* The backgrounds of tabs in the group are tinted with the group color.
This treatment, along with the colors chosen, are intended to be
a placeholder.
Bug: 905491
Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504
Commit-Queue: Bret Sepulveda <[email protected]>
Reviewed-by: Taylor Bergquist <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660498}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int bin_pe_init_exports(struct PE_(r_bin_pe_obj_t)* bin) {
PE_(image_data_directory) * data_dir_export = &bin->data_directory[PE_IMAGE_DIRECTORY_ENTRY_EXPORT];
PE_DWord export_dir_paddr = bin_pe_rva_to_paddr (bin, data_dir_export->VirtualAddress);
if (!export_dir_paddr) {
return false;
}
if (!(bin->export_directory = malloc (sizeof(PE_(image_export_directory))))) {
r_sys_perror ("malloc (export directory)");
return false;
}
if (r_buf_read_at (bin->b, export_dir_paddr, (ut8*) bin->export_directory, sizeof (PE_(image_export_directory))) == -1) {
bprintf ("Warning: read (export directory)\n");
free (bin->export_directory);
bin->export_directory = NULL;
return false;
}
return true;
}
Commit Message: Fix crash in pe
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ShowPageInfoDialogImpl(Browser* browser,
content::WebContents* web_contents,
const GURL& virtual_url,
const security_state::SecurityInfo& security_info) {
views::BubbleDialogDelegateView* bubble =
PageInfoBubbleView::CreatePageInfoBubble(browser, web_contents,
virtual_url, security_info);
BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser);
bubble->GetWidget()->AddObserver(
browser_view->GetLocationBarView()->location_icon_view());
bubble->GetWidget()->Show();
}
Commit Message: Desktop Page Info/Harmony: Show close button for internal pages.
The Harmony version of Page Info for internal Chrome pages (chrome://,
chrome-extension:// and view-source:// pages) show a close button. Update the
code to match this.
This patch also adds TestBrowserDialog tests for the latter two cases described
above (internal extension and view source pages).
See screenshot -
https://drive.google.com/file/d/18RZnMiHCu-rCX9N6DLUpu4mkFWguh1xm/view?usp=sharing
Bug: 535074
Change-Id: I55e5f1aa682fd4ec85f7b65ac88f5a4f5906fe53
Reviewed-on: https://chromium-review.googlesource.com/759624
Commit-Queue: Patti <[email protected]>
Reviewed-by: Trent Apted <[email protected]>
Cr-Commit-Position: refs/heads/master@{#516624}
CWE ID: CWE-704
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void XMLHttpRequest::genericError()
{
clearResponse();
clearRequest();
m_error = true;
changeState(DONE);
}
Commit Message: Don't dispatch events when XHR is set to sync mode
Any of readystatechange, progress, abort, error, timeout and loadend
event are not specified to be dispatched in sync mode in the latest
spec. Just an exception corresponding to the failure is thrown.
Clean up for readability done in this CL
- factor out dispatchEventAndLoadEnd calling code
- make didTimeout() private
- give error handling methods more descriptive names
- set m_exceptionCode in failure type specific methods
-- Note that for didFailRedirectCheck, m_exceptionCode was not set
in networkError(), but was set at the end of createRequest()
This CL is prep for fixing crbug.com/292422
BUG=292422
Review URL: https://chromiumcodereview.appspot.com/24225002
git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 1
Example 2:
Code: const hci_hal_t *hci_hal_mct_get_test_interface(vendor_t *vendor_interface) {
vendor = vendor_interface;
return &interface;
}
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
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int trusted_update(struct key *key, struct key_preparsed_payload *prep)
{
struct trusted_key_payload *p;
struct trusted_key_payload *new_p;
struct trusted_key_options *new_o;
size_t datalen = prep->datalen;
char *datablob;
int ret = 0;
if (test_bit(KEY_FLAG_NEGATIVE, &key->flags))
return -ENOKEY;
p = key->payload.data[0];
if (!p->migratable)
return -EPERM;
if (datalen <= 0 || datalen > 32767 || !prep->data)
return -EINVAL;
datablob = kmalloc(datalen + 1, GFP_KERNEL);
if (!datablob)
return -ENOMEM;
new_o = trusted_options_alloc();
if (!new_o) {
ret = -ENOMEM;
goto out;
}
new_p = trusted_payload_alloc(key);
if (!new_p) {
ret = -ENOMEM;
goto out;
}
memcpy(datablob, prep->data, datalen);
datablob[datalen] = '\0';
ret = datablob_parse(datablob, new_p, new_o);
if (ret != Opt_update) {
ret = -EINVAL;
kzfree(new_p);
goto out;
}
if (!new_o->keyhandle) {
ret = -EINVAL;
kzfree(new_p);
goto out;
}
/* copy old key values, and reseal with new pcrs */
new_p->migratable = p->migratable;
new_p->key_len = p->key_len;
memcpy(new_p->key, p->key, p->key_len);
dump_payload(p);
dump_payload(new_p);
ret = key_seal(new_p, new_o);
if (ret < 0) {
pr_info("trusted_key: key_seal failed (%d)\n", ret);
kzfree(new_p);
goto out;
}
if (new_o->pcrlock) {
ret = pcrlock(new_o->pcrlock);
if (ret < 0) {
pr_info("trusted_key: pcrlock failed (%d)\n", ret);
kzfree(new_p);
goto out;
}
}
rcu_assign_keypointer(key, new_p);
call_rcu(&p->rcu, trusted_rcu_free);
out:
kzfree(datablob);
kzfree(new_o);
return ret;
}
Commit Message: KEYS: Fix race between updating and finding a negative key
Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection
error into one field such that:
(1) The instantiation state can be modified/read atomically.
(2) The error can be accessed atomically with the state.
(3) The error isn't stored unioned with the payload pointers.
This deals with the problem that the state is spread over three different
objects (two bits and a separate variable) and reading or updating them
atomically isn't practical, given that not only can uninstantiated keys
change into instantiated or rejected keys, but rejected keys can also turn
into instantiated keys - and someone accessing the key might not be using
any locking.
The main side effect of this problem is that what was held in the payload
may change, depending on the state. For instance, you might observe the
key to be in the rejected state. You then read the cached error, but if
the key semaphore wasn't locked, the key might've become instantiated
between the two reads - and you might now have something in hand that isn't
actually an error code.
The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error
code if the key is negatively instantiated. The key_is_instantiated()
function is replaced with key_is_positive() to avoid confusion as negative
keys are also 'instantiated'.
Additionally, barriering is included:
(1) Order payload-set before state-set during instantiation.
(2) Order state-read before payload-read when using the key.
Further separate barriering is necessary if RCU is being used to access the
payload content after reading the payload pointers.
Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data")
Cc: [email protected] # v4.4+
Reported-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
Reviewed-by: Eric Biggers <[email protected]>
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static jlong Region_createFromParcel(JNIEnv* env, jobject clazz, jobject parcel)
{
if (parcel == NULL) {
return NULL;
}
android::Parcel* p = android::parcelForJavaObject(env, parcel);
SkRegion* region = new SkRegion;
size_t size = p->readInt32();
region->readFromMemory(p->readInplace(size), size);
return reinterpret_cast<jlong>(region);
}
Commit Message: Check that the parcel contained the expected amount of region data. DO NOT MERGE
bug:20883006
Change-Id: Ib47a8ec8696dbc37e958b8dbceb43fcbabf6605b
CWE ID: CWE-264
Target: 1
Example 2:
Code: static void bdrv_rebind(BlockDriverState *bs)
{
if (bs->drv && bs->drv->bdrv_rebind) {
bs->drv->bdrv_rebind(bs);
}
}
Commit Message:
CWE ID: CWE-190
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PHP_METHOD(Phar, copy)
{
char *oldfile, *newfile, *error;
const char *pcr_error;
size_t oldfile_len, newfile_len;
phar_entry_info *oldentry, newentry = {0}, *temp;
int tmp_len = 0;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &oldfile, &oldfile_len, &newfile, &newfile_len) == FAILURE) {
return;
}
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"Cannot copy \"%s\" to \"%s\", phar is read-only", oldfile, newfile);
RETURN_FALSE;
}
if (oldfile_len >= sizeof(".phar")-1 && !memcmp(oldfile, ".phar", sizeof(".phar")-1)) {
/* can't copy a meta file */
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", cannot copy Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
if (newfile_len >= sizeof(".phar")-1 && !memcmp(newfile, ".phar", sizeof(".phar")-1)) {
/* can't copy a meta file */
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", cannot copy to Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
if (!zend_hash_str_exists(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len) || NULL == (oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len)) || oldentry->is_deleted) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", file does not exist in %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
if (zend_hash_str_exists(&phar_obj->archive->manifest, newfile, (uint) newfile_len)) {
if (NULL != (temp = zend_hash_str_find_ptr(&phar_obj->archive->manifest, newfile, (uint) newfile_len)) || !temp->is_deleted) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", file must not already exist in phar %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
}
tmp_len = (int)newfile_len;
if (phar_path_check(&newfile, &tmp_len, &pcr_error) > pcr_is_ok) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" contains invalid characters %s, cannot be copied from \"%s\" in phar %s", newfile, pcr_error, oldfile, phar_obj->archive->fname);
RETURN_FALSE;
}
newfile_len = tmp_len;
if (phar_obj->archive->is_persistent) {
if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
/* re-populate with copied-on-write entry */
oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len);
}
memcpy((void *) &newentry, oldentry, sizeof(phar_entry_info));
if (Z_TYPE(newentry.metadata) != IS_UNDEF) {
zval_copy_ctor(&newentry.metadata);
newentry.metadata_str.s = NULL;
}
newentry.filename = estrndup(newfile, newfile_len);
newentry.filename_len = newfile_len;
newentry.fp_refcount = 0;
if (oldentry->fp_type != PHAR_FP) {
if (FAILURE == phar_copy_entry_fp(oldentry, &newentry, &error)) {
efree(newentry.filename);
php_stream_close(newentry.fp);
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
return;
}
}
zend_hash_str_add_mem(&oldentry->phar->manifest, newfile, newfile_len, &newentry, sizeof(phar_entry_info));
phar_obj->archive->is_modified = 1;
phar_flush(phar_obj->archive, 0, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool BrowserCommandController::ExecuteCommandWithDisposition(
int id, WindowOpenDisposition disposition) {
if (!SupportsCommand(id) || !IsCommandEnabled(id))
return false;
if (browser_->tab_strip_model()->active_index() == TabStripModel::kNoTab)
return true;
DCHECK(command_updater_.IsCommandEnabled(id)) << "Invalid/disabled command "
<< id;
switch (id) {
case IDC_BACK:
GoBack(browser_, disposition);
break;
case IDC_FORWARD:
GoForward(browser_, disposition);
break;
case IDC_RELOAD:
Reload(browser_, disposition);
break;
case IDC_RELOAD_CLEARING_CACHE:
ClearCache(browser_);
FALLTHROUGH;
case IDC_RELOAD_BYPASSING_CACHE:
ReloadBypassingCache(browser_, disposition);
break;
case IDC_HOME:
Home(browser_, disposition);
break;
case IDC_OPEN_CURRENT_URL:
OpenCurrentURL(browser_);
break;
case IDC_STOP:
Stop(browser_);
break;
case IDC_NEW_WINDOW:
NewWindow(browser_);
break;
case IDC_NEW_INCOGNITO_WINDOW:
NewIncognitoWindow(profile());
break;
case IDC_CLOSE_WINDOW:
base::RecordAction(base::UserMetricsAction("CloseWindowByKey"));
CloseWindow(browser_);
break;
case IDC_NEW_TAB: {
NewTab(browser_);
#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP)
auto* new_tab_tracker =
feature_engagement::NewTabTrackerFactory::GetInstance()
->GetForProfile(profile());
new_tab_tracker->OnNewTabOpened();
new_tab_tracker->CloseBubble();
#endif
break;
}
case IDC_CLOSE_TAB:
base::RecordAction(base::UserMetricsAction("CloseTabByKey"));
CloseTab(browser_);
break;
case IDC_SELECT_NEXT_TAB:
base::RecordAction(base::UserMetricsAction("Accel_SelectNextTab"));
SelectNextTab(browser_);
break;
case IDC_SELECT_PREVIOUS_TAB:
base::RecordAction(base::UserMetricsAction("Accel_SelectPreviousTab"));
SelectPreviousTab(browser_);
break;
case IDC_MOVE_TAB_NEXT:
MoveTabNext(browser_);
break;
case IDC_MOVE_TAB_PREVIOUS:
MoveTabPrevious(browser_);
break;
case IDC_SELECT_TAB_0:
case IDC_SELECT_TAB_1:
case IDC_SELECT_TAB_2:
case IDC_SELECT_TAB_3:
case IDC_SELECT_TAB_4:
case IDC_SELECT_TAB_5:
case IDC_SELECT_TAB_6:
case IDC_SELECT_TAB_7:
base::RecordAction(base::UserMetricsAction("Accel_SelectNumberedTab"));
SelectNumberedTab(browser_, id - IDC_SELECT_TAB_0);
break;
case IDC_SELECT_LAST_TAB:
base::RecordAction(base::UserMetricsAction("Accel_SelectNumberedTab"));
SelectLastTab(browser_);
break;
case IDC_DUPLICATE_TAB:
DuplicateTab(browser_);
break;
case IDC_RESTORE_TAB:
RestoreTab(browser_);
break;
case IDC_SHOW_AS_TAB:
ConvertPopupToTabbedBrowser(browser_);
break;
case IDC_FULLSCREEN:
chrome::ToggleFullscreenMode(browser_);
break;
case IDC_OPEN_IN_PWA_WINDOW:
base::RecordAction(base::UserMetricsAction("OpenActiveTabInPwaWindow"));
ReparentSecureActiveTabIntoPwaWindow(browser_);
break;
#if defined(OS_CHROMEOS)
case IDC_VISIT_DESKTOP_OF_LRU_USER_2:
case IDC_VISIT_DESKTOP_OF_LRU_USER_3:
ExecuteVisitDesktopCommand(id, window()->GetNativeWindow());
break;
#endif
#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
case IDC_MINIMIZE_WINDOW:
browser_->window()->Minimize();
break;
case IDC_MAXIMIZE_WINDOW:
browser_->window()->Maximize();
break;
case IDC_RESTORE_WINDOW:
browser_->window()->Restore();
break;
case IDC_USE_SYSTEM_TITLE_BAR: {
PrefService* prefs = profile()->GetPrefs();
prefs->SetBoolean(prefs::kUseCustomChromeFrame,
!prefs->GetBoolean(prefs::kUseCustomChromeFrame));
break;
}
#endif
#if defined(OS_MACOSX)
case IDC_TOGGLE_FULLSCREEN_TOOLBAR:
chrome::ToggleFullscreenToolbar(browser_);
break;
case IDC_TOGGLE_JAVASCRIPT_APPLE_EVENTS: {
PrefService* prefs = profile()->GetPrefs();
prefs->SetBoolean(prefs::kAllowJavascriptAppleEvents,
!prefs->GetBoolean(prefs::kAllowJavascriptAppleEvents));
break;
}
#endif
case IDC_EXIT:
Exit();
break;
case IDC_SAVE_PAGE:
SavePage(browser_);
break;
case IDC_BOOKMARK_PAGE:
#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP)
feature_engagement::BookmarkTrackerFactory::GetInstance()
->GetForProfile(profile())
->OnBookmarkAdded();
#endif
BookmarkCurrentPageAllowingExtensionOverrides(browser_);
break;
case IDC_BOOKMARK_ALL_TABS:
#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP)
feature_engagement::BookmarkTrackerFactory::GetInstance()
->GetForProfile(profile())
->OnBookmarkAdded();
#endif
BookmarkAllTabs(browser_);
break;
case IDC_VIEW_SOURCE:
browser_->tab_strip_model()
->GetActiveWebContents()
->GetMainFrame()
->ViewSource();
break;
case IDC_EMAIL_PAGE_LOCATION:
EmailPageLocation(browser_);
break;
case IDC_PRINT:
Print(browser_);
break;
#if BUILDFLAG(ENABLE_PRINTING)
case IDC_BASIC_PRINT:
base::RecordAction(base::UserMetricsAction("Accel_Advanced_Print"));
BasicPrint(browser_);
break;
#endif // ENABLE_PRINTING
case IDC_SAVE_CREDIT_CARD_FOR_PAGE:
SaveCreditCard(browser_);
break;
case IDC_MIGRATE_LOCAL_CREDIT_CARD_FOR_PAGE:
MigrateLocalCards(browser_);
break;
case IDC_TRANSLATE_PAGE:
Translate(browser_);
break;
case IDC_MANAGE_PASSWORDS_FOR_PAGE:
ManagePasswordsForPage(browser_);
break;
case IDC_CUT:
case IDC_COPY:
case IDC_PASTE:
CutCopyPaste(browser_, id);
break;
case IDC_FIND:
Find(browser_);
break;
case IDC_FIND_NEXT:
FindNext(browser_);
break;
case IDC_FIND_PREVIOUS:
FindPrevious(browser_);
break;
case IDC_ZOOM_PLUS:
Zoom(browser_, content::PAGE_ZOOM_IN);
break;
case IDC_ZOOM_NORMAL:
Zoom(browser_, content::PAGE_ZOOM_RESET);
break;
case IDC_ZOOM_MINUS:
Zoom(browser_, content::PAGE_ZOOM_OUT);
break;
case IDC_FOCUS_TOOLBAR:
base::RecordAction(base::UserMetricsAction("Accel_Focus_Toolbar"));
FocusToolbar(browser_);
break;
case IDC_FOCUS_LOCATION:
base::RecordAction(base::UserMetricsAction("Accel_Focus_Location"));
FocusLocationBar(browser_);
break;
case IDC_FOCUS_SEARCH:
base::RecordAction(base::UserMetricsAction("Accel_Focus_Search"));
FocusSearch(browser_);
break;
case IDC_FOCUS_MENU_BAR:
FocusAppMenu(browser_);
break;
case IDC_FOCUS_BOOKMARKS:
base::RecordAction(base::UserMetricsAction("Accel_Focus_Bookmarks"));
FocusBookmarksToolbar(browser_);
break;
case IDC_FOCUS_INACTIVE_POPUP_FOR_ACCESSIBILITY:
FocusInactivePopupForAccessibility(browser_);
break;
case IDC_FOCUS_NEXT_PANE:
FocusNextPane(browser_);
break;
case IDC_FOCUS_PREVIOUS_PANE:
FocusPreviousPane(browser_);
break;
case IDC_OPEN_FILE:
browser_->OpenFile();
break;
case IDC_CREATE_SHORTCUT:
CreateBookmarkAppFromCurrentWebContents(browser_,
true /* force_shortcut_app */);
break;
case IDC_INSTALL_PWA:
CreateBookmarkAppFromCurrentWebContents(browser_,
false /* force_shortcut_app */);
break;
case IDC_DEV_TOOLS:
ToggleDevToolsWindow(browser_, DevToolsToggleAction::Show());
break;
case IDC_DEV_TOOLS_CONSOLE:
ToggleDevToolsWindow(browser_, DevToolsToggleAction::ShowConsolePanel());
break;
case IDC_DEV_TOOLS_DEVICES:
InspectUI::InspectDevices(browser_);
break;
case IDC_DEV_TOOLS_INSPECT:
ToggleDevToolsWindow(browser_, DevToolsToggleAction::Inspect());
break;
case IDC_DEV_TOOLS_TOGGLE:
ToggleDevToolsWindow(browser_, DevToolsToggleAction::Toggle());
break;
case IDC_TASK_MANAGER:
OpenTaskManager(browser_);
break;
#if defined(OS_CHROMEOS)
case IDC_TAKE_SCREENSHOT:
TakeScreenshot();
break;
#endif
#if defined(GOOGLE_CHROME_BUILD)
case IDC_FEEDBACK:
OpenFeedbackDialog(browser_, kFeedbackSourceBrowserCommand);
break;
#endif
case IDC_SHOW_BOOKMARK_BAR:
ToggleBookmarkBar(browser_);
break;
case IDC_PROFILING_ENABLED:
Profiling::Toggle();
break;
case IDC_SHOW_BOOKMARK_MANAGER:
ShowBookmarkManager(browser_);
break;
case IDC_SHOW_APP_MENU:
base::RecordAction(base::UserMetricsAction("Accel_Show_App_Menu"));
ShowAppMenu(browser_);
break;
case IDC_SHOW_AVATAR_MENU:
ShowAvatarMenu(browser_);
break;
case IDC_SHOW_HISTORY:
ShowHistory(browser_);
break;
case IDC_SHOW_DOWNLOADS:
ShowDownloads(browser_);
break;
case IDC_MANAGE_EXTENSIONS:
ShowExtensions(browser_, std::string());
break;
case IDC_OPTIONS:
ShowSettings(browser_);
break;
case IDC_EDIT_SEARCH_ENGINES:
ShowSearchEngineSettings(browser_);
break;
case IDC_VIEW_PASSWORDS:
ShowPasswordManager(browser_);
break;
case IDC_CLEAR_BROWSING_DATA:
ShowClearBrowsingDataDialog(browser_);
break;
case IDC_IMPORT_SETTINGS:
ShowImportDialog(browser_);
break;
case IDC_TOGGLE_REQUEST_TABLET_SITE:
ToggleRequestTabletSite(browser_);
break;
case IDC_ABOUT:
ShowAboutChrome(browser_);
break;
case IDC_UPGRADE_DIALOG:
OpenUpdateChromeDialog(browser_);
break;
case IDC_HELP_PAGE_VIA_KEYBOARD:
ShowHelp(browser_, HELP_SOURCE_KEYBOARD);
break;
case IDC_HELP_PAGE_VIA_MENU:
ShowHelp(browser_, HELP_SOURCE_MENU);
break;
case IDC_SHOW_BETA_FORUM:
ShowBetaForum(browser_);
break;
case IDC_SHOW_SIGNIN:
ShowBrowserSigninOrSettings(
browser_, signin_metrics::AccessPoint::ACCESS_POINT_MENU);
break;
case IDC_DISTILL_PAGE:
DistillCurrentPage(browser_);
break;
case IDC_ROUTE_MEDIA:
RouteMedia(browser_);
break;
case IDC_WINDOW_MUTE_SITE:
MuteSite(browser_);
break;
case IDC_WINDOW_PIN_TAB:
PinTab(browser_);
break;
case IDC_COPY_URL:
CopyURL(browser_);
break;
case IDC_OPEN_IN_CHROME:
OpenInChrome(browser_);
break;
case IDC_SITE_SETTINGS:
ShowSiteSettings(
browser_,
browser_->tab_strip_model()->GetActiveWebContents()->GetVisibleURL());
break;
case IDC_HOSTED_APP_MENU_APP_INFO:
ShowPageInfoDialog(browser_->tab_strip_model()->GetActiveWebContents(),
bubble_anchor_util::kAppMenuButton);
break;
default:
LOG(WARNING) << "Received Unimplemented Command: " << id;
break;
}
return true;
}
Commit Message: mac: Do not let synthetic events toggle "Allow JavaScript From AppleEvents"
Bug: 891697
Change-Id: I49eb77963515637df739c9d2ce83530d4e21cf15
Reviewed-on: https://chromium-review.googlesource.com/c/1308771
Reviewed-by: Elly Fong-Jones <[email protected]>
Commit-Queue: Robert Sesek <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604268}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int ftrace_startup(struct ftrace_ops *ops, int command)
{
bool hash_enable = true;
if (unlikely(ftrace_disabled))
return -ENODEV;
ftrace_start_up++;
command |= FTRACE_UPDATE_CALLS;
/* ops marked global share the filter hashes */
if (ops->flags & FTRACE_OPS_FL_GLOBAL) {
ops = &global_ops;
/* Don't update hash if global is already set */
if (global_start_up)
hash_enable = false;
global_start_up++;
}
ops->flags |= FTRACE_OPS_FL_ENABLED;
if (hash_enable)
ftrace_hash_rec_enable(ops, 1);
ftrace_startup_enable(command);
return 0;
}
Commit Message: tracing: Fix possible NULL pointer dereferences
Currently set_ftrace_pid and set_graph_function files use seq_lseek
for their fops. However seq_open() is called only for FMODE_READ in
the fops->open() so that if an user tries to seek one of those file
when she open it for writing, it sees NULL seq_file and then panic.
It can be easily reproduced with following command:
$ cd /sys/kernel/debug/tracing
$ echo 1234 | sudo tee -a set_ftrace_pid
In this example, GNU coreutils' tee opens the file with fopen(, "a")
and then the fopen() internally calls lseek().
Link: http://lkml.kernel.org/r/[email protected]
Cc: Frederic Weisbecker <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Namhyung Kim <[email protected]>
Cc: [email protected]
Signed-off-by: Namhyung Kim <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: my_object_emit_frobnicate (MyObject *obj, GError **error)
{
g_signal_emit (obj, signals[FROBNICATE], 0, 42);
return TRUE;
}
Commit Message:
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool PaymentRequest::SatisfiesSkipUIConstraints() const {
return base::FeatureList::IsEnabled(features::kWebPaymentsSingleAppUiSkip) &&
base::FeatureList::IsEnabled(::features::kServiceWorkerPaymentApps) &&
is_show_user_gesture_ && state()->is_get_all_instruments_finished() &&
state()->available_instruments().size() == 1 &&
spec()->stringified_method_data().size() == 1 &&
!spec()->request_shipping() && !spec()->request_payer_name() &&
!spec()->request_payer_phone() &&
!spec()->request_payer_email()
&& spec()->url_payment_method_identifiers().size() == 1;
}
Commit Message: [Payment Request][Desktop] Prevent use after free.
Before this patch, a compromised renderer on desktop could make IPC
methods into Payment Request in an unexpected ordering and cause use
after free in the browser.
This patch will disconnect the IPC pipes if:
- Init() is called more than once.
- Any other method is called before Init().
- Show() is called more than once.
- Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or
Complete() are called before Show().
This patch re-orders the IPC methods in payment_request.cc to match the
order in payment_request.h, which eases verifying correctness of their
error handling.
This patch prints more errors to the developer console, if available, to
improve debuggability by web developers, who rarely check where LOG
prints.
After this patch, unexpected ordering of calls into the Payment Request
IPC from the renderer to the browser on desktop will print an error in
the developer console and disconnect the IPC pipes. The binary might
increase slightly in size because more logs are included in the release
version instead of being stripped at compile time.
Bug: 912947
Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a
Reviewed-on: https://chromium-review.googlesource.com/c/1370198
Reviewed-by: anthonyvd <[email protected]>
Commit-Queue: Rouslan Solomakhin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616822}
CWE ID: CWE-189
Target: 1
Example 2:
Code: bool WebContext::setDefaultVideoCaptureDeviceId(const QString& id) {
if (IsInitialized()) {
return MediaCaptureDevicesContext::Get(context_.get())
->SetDefaultVideoDeviceId(id.toStdString());
}
construct_props_->default_video_capture_device_id = id.toStdString();
client_->DefaultVideoCaptureDeviceChanged();
return true;
}
Commit Message:
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->AddHandler(std::make_unique<protocol::InspectorHandler>());
session->AddHandler(std::make_unique<protocol::NetworkHandler>(GetId()));
session->AddHandler(std::make_unique<protocol::SchemaHandler>());
session->SetRenderer(GetProcess(), nullptr);
if (state_ == WORKER_READY)
session->AttachToAgent(EnsureAgent());
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
DCHECK_EQ(-1, mapped_file_);
if (options.size == 0) return false;
if (options.size > static_cast<size_t>(std::numeric_limits<int>::max()))
return false;
base::ThreadRestrictions::ScopedAllowIO allow_io;
FILE *fp;
bool fix_size = true;
FilePath path;
if (options.name == NULL || options.name->empty()) {
DCHECK(!options.open_existing);
fp = file_util::CreateAndOpenTemporaryShmemFile(&path, options.executable);
if (fp) {
if (unlink(path.value().c_str()))
PLOG(WARNING) << "unlink";
}
} else {
if (!FilePathForMemoryName(*options.name, &path))
return false;
fp = file_util::OpenFile(path, "w+x");
if (fp == NULL && options.open_existing) {
fp = file_util::OpenFile(path, "a+");
fix_size = false;
}
}
if (fp && fix_size) {
struct stat stat;
if (fstat(fileno(fp), &stat) != 0) {
file_util::CloseFile(fp);
return false;
}
const size_t current_size = stat.st_size;
if (current_size != options.size) {
if (HANDLE_EINTR(ftruncate(fileno(fp), options.size)) != 0) {
file_util::CloseFile(fp);
return false;
}
}
requested_size_ = options.size;
}
if (fp == NULL) {
#if !defined(OS_MACOSX)
PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
FilePath dir = path.DirName();
if (access(dir.value().c_str(), W_OK | X_OK) < 0) {
PLOG(ERROR) << "Unable to access(W_OK|X_OK) " << dir.value();
if (dir.value() == "/dev/shm") {
LOG(FATAL) << "This is frequently caused by incorrect permissions on "
<< "/dev/shm. Try 'sudo chmod 1777 /dev/shm' to fix.";
}
}
#else
PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
#endif
return false;
}
return PrepareMapFile(fp);
}
Commit Message: Posix: fix named SHM mappings permissions.
Make sure that named mappings in /dev/shm/ aren't created with
broad permissions.
BUG=254159
[email protected], [email protected]
Review URL: https://codereview.chromium.org/17779002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@209814 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Target: 1
Example 2:
Code: void RenderWidgetHostViewGtk::DoPopupOrFullscreenInit(GtkWindow* window,
const gfx::Rect& bounds) {
requested_size_.SetSize(std::min(bounds.width(), kMaxWindowWidth),
std::min(bounds.height(), kMaxWindowHeight));
host_->WasResized();
ui::ActiveWindowWatcherX::AddObserver(this);
if (!is_fullscreen_) {
gtk_widget_set_size_request(
view_.get(), requested_size_.width(), requested_size_.height());
gtk_window_set_resizable(window, FALSE);
gtk_window_set_default_size(window, -1, -1);
gtk_window_move(window, bounds.x(), bounds.y());
}
gtk_widget_show_all(GTK_WIDGET(window));
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: R_API RBinObject *r_bin_get_object(RBin *bin) {
RBinObject *o = r_bin_cur_object (bin);
if (o) {
o->referenced++;
}
return o;
}
Commit Message: Fix #8748 - Fix oobread on string search
CWE ID: CWE-125
Output: | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.