text
stringlengths 478
227k
|
---|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ex_endtry(exarg_T *eap)
{
int idx;
int skip;
int rethrow = FALSE;
int pending = CSTP_NONE;
void *rettv = NULL;
cstack_T *cstack = eap->cstack;
if (cmdmod_error(FALSE))
return;
if (cstack->cs_trylevel <= 0 || cstack->cs_idx < 0)
eap->errmsg = _(e_endtry_without_try);
else
{
/*
* Don't do something after an error, interrupt or throw in the try
* block, catch clause, or finally clause preceding this ":endtry" or
* when an error or interrupt occurred after a ":continue", ":break",
* ":return", or ":finish" in a try block or catch clause preceding this
* ":endtry" or when the try block never got active (because of an
* inactive surrounding conditional or after an error or interrupt or
* throw) or when there is a surrounding conditional and it has been
* made inactive by a ":continue", ":break", ":return", or ":finish" in
* the finally clause. The latter case need not be tested since then
* anything pending has already been discarded. */
skip = did_emsg || got_int || did_throw
|| !(cstack->cs_flags[cstack->cs_idx] & CSF_TRUE);
if (!(cstack->cs_flags[cstack->cs_idx] & CSF_TRY))
{
eap->errmsg = get_end_emsg(cstack);
// Find the matching ":try" and report what's missing.
idx = cstack->cs_idx;
do
--idx;
while (idx > 0 && !(cstack->cs_flags[idx] & CSF_TRY));
rewind_conditionals(cstack, idx, CSF_WHILE | CSF_FOR,
&cstack->cs_looplevel);
skip = TRUE;
/*
* If an exception is being thrown, discard it to prevent it from
* being rethrown at the end of this function. It would be
* discarded by the error message, anyway. Resets did_throw.
* This does not affect the script termination due to the error
* since "trylevel" is decremented after emsg() has been called.
*/
if (did_throw)
discard_current_exception();
// report eap->errmsg, also when there already was an error
did_emsg = FALSE;
}
else
{
idx = cstack->cs_idx;
// Check the flags only when not in a skipped block.
if (!skip && in_vim9script()
&& (cstack->cs_flags[idx] & (CSF_CATCH|CSF_FINALLY)) == 0)
{
// try/endtry without any catch or finally: give an error and
// continue.
eap->errmsg = _(e_missing_catch_or_finally);
}
/*
* If we stopped with the exception currently being thrown at this
* try conditional since we didn't know that it doesn't have
* a finally clause, we need to rethrow it after closing the try
* conditional.
*/
if (did_throw && (cstack->cs_flags[idx] & CSF_TRUE)
&& !(cstack->cs_flags[idx] & CSF_FINALLY))
rethrow = TRUE;
}
// If there was no finally clause, show the user when debugging or
// a breakpoint was encountered that the end of the try conditional has
// been reached: display the debug prompt (if not already done). Do
// this on normal control flow or when an exception was thrown, but not
// on an interrupt or error not converted to an exception or when
// a ":break", ":continue", ":return", or ":finish" is pending. These
// actions are carried out immediately.
if ((rethrow || (!skip
&& !(cstack->cs_flags[idx] & CSF_FINALLY)
&& !cstack->cs_pending[idx]))
&& dbg_check_skipped(eap))
{
// Handle a ">quit" debug command as if an interrupt had occurred
// before the ":endtry". That is, throw an interrupt exception and
// set "skip" and "rethrow".
if (got_int)
{
skip = TRUE;
(void)do_intthrow(cstack);
// The do_intthrow() call may have reset did_throw or
// cstack->cs_pending[idx].
rethrow = FALSE;
if (did_throw && !(cstack->cs_flags[idx] & CSF_FINALLY))
rethrow = TRUE;
}
}
/*
* If a ":return" is pending, we need to resume it after closing the
* try conditional; remember the return value. If there was a finally
* clause making an exception pending, we need to rethrow it. Make it
* the exception currently being thrown.
*/
if (!skip)
{
pending = cstack->cs_pending[idx];
cstack->cs_pending[idx] = CSTP_NONE;
if (pending == CSTP_RETURN)
rettv = cstack->cs_rettv[idx];
else if (pending & CSTP_THROW)
current_exception = cstack->cs_exception[idx];
}
/*
* Discard anything pending on an error, interrupt, or throw in the
* finally clause. If there was no ":finally", discard a pending
* ":continue", ":break", ":return", or ":finish" if an error or
* interrupt occurred afterwards, but before the ":endtry" was reached.
* If an exception was caught by the last of the catch clauses and there
* was no finally clause, finish the exception now. This happens also
* after errors except when this ":endtry" is not within a ":try".
* Restore "emsg_silent" if it has been reset by this try conditional.
*/
(void)cleanup_conditionals(cstack, CSF_TRY | CSF_SILENT, TRUE);
if (cstack->cs_idx >= 0
&& (cstack->cs_flags[cstack->cs_idx] & CSF_TRY))
leave_block(cstack);
--cstack->cs_trylevel;
if (!skip)
{
report_resume_pending(pending,
(pending == CSTP_RETURN) ? rettv :
(pending & CSTP_THROW) ? (void *)current_exception : NULL);
switch (pending)
{
case CSTP_NONE:
break;
// Reactivate a pending ":continue", ":break", ":return",
// ":finish" from the try block or a catch clause of this try
// conditional. This is skipped, if there was an error in an
// (unskipped) conditional command or an interrupt afterwards
// or if the finally clause is present and executed a new error,
// interrupt, throw, ":continue", ":break", ":return", or
// ":finish".
case CSTP_CONTINUE:
ex_continue(eap);
break;
case CSTP_BREAK:
ex_break(eap);
break;
case CSTP_RETURN:
do_return(eap, FALSE, FALSE, rettv);
break;
case CSTP_FINISH:
do_finish(eap, FALSE);
break;
// When the finally clause was entered due to an error,
// interrupt or throw (as opposed to a ":continue", ":break",
// ":return", or ":finish"), restore the pending values of
// did_emsg, got_int, and did_throw. This is skipped, if there
// was a new error, interrupt, throw, ":continue", ":break",
// ":return", or ":finish". in the finally clause.
default:
if (pending & CSTP_ERROR)
did_emsg = TRUE;
if (pending & CSTP_INTERRUPT)
got_int = TRUE;
if (pending & CSTP_THROW)
rethrow = TRUE;
break;
}
}
if (rethrow)
// Rethrow the current exception (within this cstack).
do_throw(cstack);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'patch 9.0.0577: buffer underflow with unexpected :finally
Problem: Buffer underflow with unexpected :finally.
Solution: Check CSF_TRY can be found.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: tlb_update_vma_flags(struct mmu_gather *tlb, struct vm_area_struct *vma)
{
/*
* flush_tlb_range() implementations that look at VM_HUGETLB (tile,
* mips-4k) flush only large pages.
*
* flush_tlb_range() implementations that flush I-TLB also flush D-TLB
* (tile, xtensa, arm), so it's ok to just add VM_EXEC to an existing
* range.
*
* We rely on tlb_end_vma() to issue a flush, such that when we reset
* these values the batch is empty.
*/
tlb->vma_huge = is_vm_hugetlb_page(vma);
tlb->vma_exec = !!(vma->vm_flags & VM_EXEC);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'mmu_gather: Force tlb-flush VM_PFNMAP vmas
Jann reported a race between munmap() and unmap_mapping_range(), where
unmap_mapping_range() will no-op once unmap_vmas() has unlinked the
VMA; however munmap() will not yet have invalidated the TLBs.
Therefore unmap_mapping_range() will complete while there are still
(stale) TLB entries for the specified range.
Mitigate this by force flushing TLBs for VM_PFNMAP ranges.
Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Acked-by: Will Deacon <will@kernel.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int minix_fill_super(struct super_block *s, void *data, int silent)
{
struct buffer_head *bh;
struct buffer_head **map;
struct minix_super_block *ms;
int i, block;
struct inode *root_inode;
struct minix_sb_info *sbi;
sbi = kmalloc(sizeof(struct minix_sb_info), GFP_KERNEL);
if (!sbi)
return -ENOMEM;
s->s_fs_info = sbi;
memset(sbi, 0, sizeof(struct minix_sb_info));
/* N.B. These should be compile-time tests.
Unfortunately that is impossible. */
if (32 != sizeof (struct minix_inode))
panic("bad V1 i-node size");
if (64 != sizeof(struct minix2_inode))
panic("bad V2 i-node size");
if (!sb_set_blocksize(s, BLOCK_SIZE))
goto out_bad_hblock;
if (!(bh = sb_bread(s, 1)))
goto out_bad_sb;
ms = (struct minix_super_block *) bh->b_data;
sbi->s_ms = ms;
sbi->s_sbh = bh;
sbi->s_mount_state = ms->s_state;
sbi->s_ninodes = ms->s_ninodes;
sbi->s_nzones = ms->s_nzones;
sbi->s_imap_blocks = ms->s_imap_blocks;
sbi->s_zmap_blocks = ms->s_zmap_blocks;
sbi->s_firstdatazone = ms->s_firstdatazone;
sbi->s_log_zone_size = ms->s_log_zone_size;
sbi->s_max_size = ms->s_max_size;
s->s_magic = ms->s_magic;
if (s->s_magic == MINIX_SUPER_MAGIC) {
sbi->s_version = MINIX_V1;
sbi->s_dirsize = 16;
sbi->s_namelen = 14;
sbi->s_link_max = MINIX_LINK_MAX;
} else if (s->s_magic == MINIX_SUPER_MAGIC2) {
sbi->s_version = MINIX_V1;
sbi->s_dirsize = 32;
sbi->s_namelen = 30;
sbi->s_link_max = MINIX_LINK_MAX;
} else if (s->s_magic == MINIX2_SUPER_MAGIC) {
sbi->s_version = MINIX_V2;
sbi->s_nzones = ms->s_zones;
sbi->s_dirsize = 16;
sbi->s_namelen = 14;
sbi->s_link_max = MINIX2_LINK_MAX;
} else if (s->s_magic == MINIX2_SUPER_MAGIC2) {
sbi->s_version = MINIX_V2;
sbi->s_nzones = ms->s_zones;
sbi->s_dirsize = 32;
sbi->s_namelen = 30;
sbi->s_link_max = MINIX2_LINK_MAX;
} else
goto out_no_fs;
/*
* Allocate the buffer map to keep the superblock small.
*/
i = (sbi->s_imap_blocks + sbi->s_zmap_blocks) * sizeof(bh);
map = kmalloc(i, GFP_KERNEL);
if (!map)
goto out_no_map;
memset(map, 0, i);
sbi->s_imap = &map[0];
sbi->s_zmap = &map[sbi->s_imap_blocks];
block=2;
for (i=0 ; i < sbi->s_imap_blocks ; i++) {
if (!(sbi->s_imap[i]=sb_bread(s, block)))
goto out_no_bitmap;
block++;
}
for (i=0 ; i < sbi->s_zmap_blocks ; i++) {
if (!(sbi->s_zmap[i]=sb_bread(s, block)))
goto out_no_bitmap;
block++;
}
minix_set_bit(0,sbi->s_imap[0]->b_data);
minix_set_bit(0,sbi->s_zmap[0]->b_data);
/* set up enough so that it can read an inode */
s->s_op = &minix_sops;
root_inode = iget(s, MINIX_ROOT_INO);
if (!root_inode || is_bad_inode(root_inode))
goto out_no_root;
s->s_root = d_alloc_root(root_inode);
if (!s->s_root)
goto out_iput;
if (!NO_TRUNCATE)
s->s_root->d_op = &minix_dentry_operations;
if (!(s->s_flags & MS_RDONLY)) {
ms->s_state &= ~MINIX_VALID_FS;
mark_buffer_dirty(bh);
}
if (!(sbi->s_mount_state & MINIX_VALID_FS))
printk("MINIX-fs: mounting unchecked file system, "
"running fsck is recommended\n");
else if (sbi->s_mount_state & MINIX_ERROR_FS)
printk("MINIX-fs: mounting file system with errors, "
"running fsck is recommended\n");
return 0;
out_iput:
iput(root_inode);
goto out_freemap;
out_no_root:
if (!silent)
printk("MINIX-fs: get root inode failed\n");
goto out_freemap;
out_no_bitmap:
printk("MINIX-fs: bad superblock or unable to read bitmaps\n");
out_freemap:
for (i = 0; i < sbi->s_imap_blocks; i++)
brelse(sbi->s_imap[i]);
for (i = 0; i < sbi->s_zmap_blocks; i++)
brelse(sbi->s_zmap[i]);
kfree(sbi->s_imap);
goto out_release;
out_no_map:
if (!silent)
printk("MINIX-fs: can't allocate map\n");
goto out_release;
out_no_fs:
if (!silent)
printk("VFS: Can't find a Minix or Minix V2 filesystem "
"on device %s\n", s->s_id);
out_release:
brelse(bh);
goto out;
out_bad_hblock:
printk("MINIX-fs: blocksize too small for device\n");
goto out;
out_bad_sb:
printk("MINIX-fs: unable to read superblock\n");
out:
s->s_fs_info = NULL;
kfree(sbi);
return -EINVAL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': '[PATCH] Fix for minix crash
Mounting a (corrupt) minix filesystem with zero s_zmap_blocks
gives a spectacular crash on my 2.6.17.8 system, no doubt
because minix/inode.c does an unconditional
minix_set_bit(0,sbi->s_zmap[0]->b_data);
[akpm@osdl.org: make labels conistent while we're there]
Signed-off-by: Andrew Morton <akpm@osdl.org>
Signed-off-by: Linus Torvalds <torvalds@osdl.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int fprintf_utab_fs(FILE *f, struct libmnt_fs *fs)
{
char *p;
assert(fs);
assert(f);
if (!fs || !f)
return -EINVAL;
p = mangle(mnt_fs_get_source(fs));
if (p) {
fprintf(f, "SRC=%s ", p);
free(p);
}
p = mangle(mnt_fs_get_target(fs));
if (p) {
fprintf(f, "TARGET=%s ", p);
free(p);
}
p = mangle(mnt_fs_get_root(fs));
if (p) {
fprintf(f, "ROOT=%s ", p);
free(p);
}
p = mangle(mnt_fs_get_bindsrc(fs));
if (p) {
fprintf(f, "BINDSRC=%s ", p);
free(p);
}
p = mangle(mnt_fs_get_attributes(fs));
if (p) {
fprintf(f, "ATTRS=%s ", p);
free(p);
}
p = mangle(mnt_fs_get_user_options(fs));
if (p) {
fprintf(f, "OPTS=%s", p);
free(p);
}
fputc('\n', f);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'libmount: more robust mtab and utab update (CVE-2011-1676, CVE-2011-1677)
http://thread.gmane.org/gmane.comp.security.oss.general/4374
Changes:
- always use temporary file
- use fflush() for the temporary file
- check fprintf() return value
Signed-off-by: Karel Zak <kzak@redhat.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int utab_lock(const char *filename)
{
char *lfile;
int fd;
assert(filename);
if (asprintf(&lfile, "%s.lock", filename) == -1)
return -1;
DBG(UPDATE, mnt_debug("%s: locking", lfile));
fd = open(lfile, O_RDONLY|O_CREAT|O_CLOEXEC, S_IWUSR|
S_IRUSR|S_IRGRP|S_IROTH);
free(lfile);
if (fd < 0)
return -errno;
while (flock(fd, LOCK_EX) < 0) {
int errsv;
if (errno == EINTR)
continue;
errsv = errno;
close(fd);
return -errsv;
}
return fd;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'libmount: block signals when update utab
Signed-off-by: Karel Zak <kzak@redhat.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: log_tx_piggyback (const char *q, const char qtype[2], const char *control)
{
string("txpb ");
logtype (qtype);
space ();
name (q);
space ();
name (control);
line ();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'Merge identical outgoing requests - patch 2.
This patch fixes dnscache to combine *same* client queries into one
single outgoing request, thus securing the server from possible cache
poisoning attacks. The merges operation takes place in the
dns_transmit layer, rather than between query and dns_transmit layers,
as done in the previous patch.
This fixes one of the cache poisoning vulnerability reported by
Mr Mark Johnson -> https://bugzilla.redhat.com/show_bug.cgi?id=838965.
Nonetheless the original patch for this issue was created by
Mr Jeff king -> http://marc.info/?l=djbdns&m=123859517723684&w=3#2
Sincere thanks to Mr Mark for reporting this issue and Mr Jeff for
creating the patch and releasing it under GPLv2.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int keyring_detect_cycle_iterator(const void *object,
void *iterator_data)
{
struct keyring_search_context *ctx = iterator_data;
const struct key *key = keyring_ptr_to_key(object);
kenter("{%d}", key->serial);
BUG_ON(key != ctx->match_data);
ctx->result = ERR_PTR(-EDEADLK);
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'KEYS: Make the keyring cycle detector ignore other keyrings of the same name
This fixes CVE-2014-0102.
The following command sequence produces an oops:
keyctl new_session
i=`keyctl newring _ses @s`
keyctl link @s $i
The problem is that search_nested_keyrings() sees two keyrings that have
matching type and description, so keyring_compare_object() returns true.
s_n_k() then passes the key to the iterator function -
keyring_detect_cycle_iterator() - which *should* check to see whether this is
the keyring of interest, not just one with the same name.
Because assoc_array_find() will return one and only one match, I assumed that
the iterator function would only see an exact match or never be called - but
the iterator isn't only called from assoc_array_find()...
The oops looks something like this:
kernel BUG at /data/fs/linux-2.6-fscache/security/keys/keyring.c:1003!
invalid opcode: 0000 [#1] SMP
...
RIP: keyring_detect_cycle_iterator+0xe/0x1f
...
Call Trace:
search_nested_keyrings+0x76/0x2aa
__key_link_check_live_key+0x50/0x5f
key_link+0x4e/0x85
keyctl_keyring_link+0x60/0x81
SyS_keyctl+0x65/0xe4
tracesys+0xdd/0xe2
The fix is to make keyring_detect_cycle_iterator() check that the key it
has is the key it was actually looking for rather than calling BUG_ON().
A testcase has been included in the keyutils testsuite for this:
http://git.kernel.org/cgit/linux/kernel/git/dhowells/keyutils.git/commit/?id=891f3365d07f1996778ade0e3428f01878a1790b
Reported-by: Tommi Rantala <tt.rantala@gmail.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Acked-by: James Morris <james.l.morris@oracle.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy)
{
struct negotiatedata *neg_ctx = proxy?&conn->data->state.proxyneg:
&conn->data->state.negotiate;
char *encoded = NULL;
size_t len = 0;
char *userp;
CURLcode error;
error = Curl_base64_encode(conn->data,
(const char*)neg_ctx->output_token,
neg_ctx->output_token_length,
&encoded, &len);
if(error)
return error;
if(len == 0)
return CURLE_REMOTE_ACCESS_DENIED;
userp = aprintf("%sAuthorization: %s %s\r\n", proxy ? "Proxy-" : "",
neg_ctx->protocol, encoded);
if(proxy)
conn->allocptr.proxyuserpwd = userp;
else
conn->allocptr.userpwd = userp;
free(encoded);
Curl_cleanup_negotiate (conn->data);
return (userp == NULL) ? CURLE_OUT_OF_MEMORY : CURLE_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284'], 'message': 'Don't clear GSSAPI state between each exchange in the negotiation
GSSAPI doesn't work very well if we forget everything ever time.
XX: Is Curl_http_done() the right place to do the final cleanup?'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void qemu_input_queue_delay(struct QemuInputEventQueueHead *queue,
QEMUTimer *timer, uint32_t delay_ms)
{
QemuInputEventQueue *item = g_new0(QemuInputEventQueue, 1);
bool start_timer = QTAILQ_EMPTY(queue);
item->type = QEMU_INPUT_QUEUE_DELAY;
item->delay_ms = delay_ms;
item->timer = timer;
QTAILQ_INSERT_TAIL(queue, item, node);
if (start_timer) {
timer_mod(item->timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL)
+ item->delay_ms);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-772'], 'message': 'input: limit kbd queue depth
Apply a limit to the number of items we accept into the keyboard queue.
Impact: Without this limit vnc clients can exhaust host memory by
sending keyboard events faster than qemu feeds them to the guest.
Fixes: CVE-2017-8379
Cc: P J P <ppandit@redhat.com>
Cc: Huawei PSIRT <PSIRT@huawei.com>
Reported-by: jiangxin1@huawei.com
Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>
Message-id: 20170428084237.23960-1-kraxel@redhat.com'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: CalendarRegressionTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ )
{
// if (exec) logln((UnicodeString)"TestSuite NumberFormatRegressionTest");
switch (index) {
CASE(0,test4100311);
CASE(1,test4074758);
CASE(2,test4028518);
CASE(3,test4031502);
CASE(4,test4035301);
CASE(5,test4040996);
CASE(6,test4051765);
CASE(7,test4061476);
CASE(8,test4070502);
CASE(9,test4071197);
CASE(10,test4071385);
CASE(11,test4073929);
CASE(12,test4083167);
CASE(13,test4086724);
CASE(14,test4095407);
CASE(15,test4096231);
CASE(16,test4096539);
CASE(17,test41003112);
CASE(18,test4103271);
CASE(19,test4106136);
CASE(20,test4108764);
CASE(21,test4114578);
CASE(22,test4118384);
CASE(23,test4125881);
CASE(24,test4125892);
CASE(25,test4141665);
CASE(26,test4142933);
CASE(27,test4145158);
CASE(28,test4145983);
CASE(29,test4147269);
CASE(30,Test4149677);
CASE(31,Test4162587);
CASE(32,Test4165343);
CASE(33,Test4166109);
CASE(34,Test4167060);
CASE(35,Test4197699);
CASE(36,TestJ81);
CASE(37,TestJ438);
CASE(38,TestLeapFieldDifference);
CASE(39,TestMalaysianInstance);
CASE(40,test4059654);
CASE(41,test4092362);
CASE(42,TestWeekShift);
CASE(43,TestTimeZoneTransitionAdd);
CASE(44,TestDeprecates);
CASE(45,TestT5555);
CASE(46,TestT6745);
CASE(47,TestT8057);
CASE(48,TestT8596);
CASE(49,Test9019);
CASE(50,TestT9452);
CASE(51,TestT11632);
default: name = ""; break;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'ICU-12504 in ICU4C Persian cal, use int64_t math for one operation to avoid overflow; add tests in C and J
X-SVN-Rev: 40654'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int sudo_process_init(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct confdb_ctx *cdb)
{
struct resp_ctx *rctx;
struct sss_cmd_table *sudo_cmds;
struct sudo_ctx *sudo_ctx;
struct be_conn *iter;
int ret;
int max_retries;
sudo_cmds = get_sudo_cmds();
ret = sss_process_init(mem_ctx, ev, cdb,
sudo_cmds,
SSS_SUDO_SOCKET_NAME, -1, NULL, -1,
CONFDB_SUDO_CONF_ENTRY,
SSS_SUDO_SBUS_SERVICE_NAME,
SSS_SUDO_SBUS_SERVICE_VERSION,
&monitor_sudo_methods,
"SUDO",
NULL,
sss_connection_setup,
&rctx);
if (ret != EOK) {
DEBUG(SSSDBG_FATAL_FAILURE, "sss_process_init() failed\n");
return ret;
}
sudo_ctx = talloc_zero(rctx, struct sudo_ctx);
if (!sudo_ctx) {
DEBUG(SSSDBG_FATAL_FAILURE, "fatal error initializing sudo_ctx\n");
ret = ENOMEM;
goto fail;
}
sudo_ctx->rctx = rctx;
sudo_ctx->rctx->pvt_ctx = sudo_ctx;
sss_ncache_prepopulate(sudo_ctx->rctx->ncache, sudo_ctx->rctx->cdb, rctx);
if (ret != EOK) {
DEBUG(SSSDBG_FATAL_FAILURE,
"failed to set ncache for sudo's filter_users\n");
goto fail;
}
/* Enable automatic reconnection to the Data Provider */
ret = confdb_get_int(sudo_ctx->rctx->cdb,
CONFDB_SUDO_CONF_ENTRY,
CONFDB_SERVICE_RECON_RETRIES,
3, &max_retries);
if (ret != EOK) {
DEBUG(SSSDBG_FATAL_FAILURE,
"Failed to set up automatic reconnection\n");
goto fail;
}
for (iter = sudo_ctx->rctx->be_conns; iter; iter = iter->next) {
sbus_reconnect_init(iter->conn, max_retries,
sudo_dp_reconnect_init, iter);
}
/* Get sudo_timed option */
ret = confdb_get_bool(sudo_ctx->rctx->cdb,
CONFDB_SUDO_CONF_ENTRY, CONFDB_SUDO_TIMED,
CONFDB_DEFAULT_SUDO_TIMED,
&sudo_ctx->timed);
if (ret != EOK) {
DEBUG(SSSDBG_FATAL_FAILURE, "Error reading from confdb (%d) [%s]\n",
ret, strerror(ret));
goto fail;
}
/* Get sudo_inverse_order option */
ret = confdb_get_bool(sudo_ctx->rctx->cdb,
CONFDB_SUDO_CONF_ENTRY, CONFDB_SUDO_INVERSE_ORDER,
CONFDB_DEFAULT_SUDO_INVERSE_ORDER,
&sudo_ctx->inverse_order);
if (ret != EOK) {
DEBUG(SSSDBG_FATAL_FAILURE, "Error reading from confdb (%d) [%s]\n",
ret, strerror(ret));
goto fail;
}
/* Get sudo_inverse_order option */
ret = confdb_get_int(sudo_ctx->rctx->cdb,
CONFDB_SUDO_CONF_ENTRY, CONFDB_SUDO_THRESHOLD,
CONFDB_DEFAULT_SUDO_THRESHOLD,
&sudo_ctx->threshold);
if (ret != EOK) {
DEBUG(SSSDBG_FATAL_FAILURE, "Error reading from confdb (%d) [%s]\n",
ret, strerror(ret));
goto fail;
}
ret = schedule_get_domains_task(rctx, rctx->ev, rctx, NULL);
if (ret != EOK) {
DEBUG(SSSDBG_FATAL_FAILURE, "schedule_get_domains_tasks failed.\n");
goto fail;
}
DEBUG(SSSDBG_TRACE_FUNC, "SUDO Initialization complete\n");
return EOK;
fail:
talloc_free(rctx);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'SUDO: Create the socket with stricter permissions
This patch switches the sudo responder from being created as a public
responder where the permissions are open and not checked by the sssd
deaamon to a private socket. In this case, sssd creates the pipes with
strict permissions (see the umask in the call to create_pipe_fd() in
set_unix_socket()) and additionaly checks the permissions with every read
via the tevent integrations (see accept_fd_handler()).
Resolves:
https://pagure.io/SSSD/sssd/issue/3766 (CVE-2018-10852)
Reviewed-by: Sumit Bose <sbose@redhat.com>
Reviewed-by: Pavel Březina <pbrezina@redhat.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: SYSCALL_DEFINE5(mremap, unsigned long, addr, unsigned long, old_len,
unsigned long, new_len, unsigned long, flags,
unsigned long, new_addr)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma;
unsigned long ret = -EINVAL;
unsigned long charged = 0;
bool locked = false;
bool downgraded = false;
struct vm_userfaultfd_ctx uf = NULL_VM_UFFD_CTX;
LIST_HEAD(uf_unmap_early);
LIST_HEAD(uf_unmap);
/*
* Architectures may interpret the tag passed to mmap as a background
* colour for the corresponding vma. For mremap we don't allow tagged
* new_addr to preserve similar behaviour to mmap.
*/
addr = untagged_addr(addr);
if (flags & ~(MREMAP_FIXED | MREMAP_MAYMOVE))
return ret;
if (flags & MREMAP_FIXED && !(flags & MREMAP_MAYMOVE))
return ret;
if (offset_in_page(addr))
return ret;
old_len = PAGE_ALIGN(old_len);
new_len = PAGE_ALIGN(new_len);
/*
* We allow a zero old-len as a special case
* for DOS-emu "duplicate shm area" thing. But
* a zero new-len is nonsensical.
*/
if (!new_len)
return ret;
if (down_write_killable(¤t->mm->mmap_sem))
return -EINTR;
if (flags & MREMAP_FIXED) {
ret = mremap_to(addr, old_len, new_addr, new_len,
&locked, &uf, &uf_unmap_early, &uf_unmap);
goto out;
}
/*
* Always allow a shrinking remap: that just unmaps
* the unnecessary pages..
* __do_munmap does all the needed commit accounting, and
* downgrades mmap_sem to read if so directed.
*/
if (old_len >= new_len) {
int retval;
retval = __do_munmap(mm, addr+new_len, old_len - new_len,
&uf_unmap, true);
if (retval < 0 && old_len != new_len) {
ret = retval;
goto out;
/* Returning 1 indicates mmap_sem is downgraded to read. */
} else if (retval == 1)
downgraded = true;
ret = addr;
goto out;
}
/*
* Ok, we need to grow..
*/
vma = vma_to_resize(addr, old_len, new_len, &charged);
if (IS_ERR(vma)) {
ret = PTR_ERR(vma);
goto out;
}
/* old_len exactly to the end of the area..
*/
if (old_len == vma->vm_end - addr) {
/* can we just expand the current mapping? */
if (vma_expandable(vma, new_len - old_len)) {
int pages = (new_len - old_len) >> PAGE_SHIFT;
if (vma_adjust(vma, vma->vm_start, addr + new_len,
vma->vm_pgoff, NULL)) {
ret = -ENOMEM;
goto out;
}
vm_stat_account(mm, vma->vm_flags, pages);
if (vma->vm_flags & VM_LOCKED) {
mm->locked_vm += pages;
locked = true;
new_addr = addr;
}
ret = addr;
goto out;
}
}
/*
* We weren't able to just expand or shrink the area,
* we need to create a new one and move it..
*/
ret = -ENOMEM;
if (flags & MREMAP_MAYMOVE) {
unsigned long map_flags = 0;
if (vma->vm_flags & VM_MAYSHARE)
map_flags |= MAP_SHARED;
new_addr = get_unmapped_area(vma->vm_file, 0, new_len,
vma->vm_pgoff +
((addr - vma->vm_start) >> PAGE_SHIFT),
map_flags);
if (offset_in_page(new_addr)) {
ret = new_addr;
goto out;
}
ret = move_vma(vma, addr, old_len, new_len, new_addr,
&locked, &uf, &uf_unmap);
}
out:
if (offset_in_page(ret)) {
vm_unacct_memory(charged);
locked = 0;
}
if (downgraded)
up_read(¤t->mm->mmap_sem);
else
up_write(¤t->mm->mmap_sem);
if (locked && new_len > old_len)
mm_populate(new_addr + old_len, new_len - old_len);
userfaultfd_unmap_complete(mm, &uf_unmap_early);
mremap_userfaultfd_complete(&uf, addr, new_addr, old_len);
userfaultfd_unmap_complete(mm, &uf_unmap);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'mm: untag user pointers in mmap/munmap/mremap/brk
There isn't a good reason to differentiate between the user address space
layout modification syscalls and the other memory permission/attributes
ones (e.g. mprotect, madvise) w.r.t. the tagged address ABI. Untag the
user addresses on entry to these functions.
Link: http://lkml.kernel.org/r/20190821164730.47450-2-catalin.marinas@arm.com
Signed-off-by: Catalin Marinas <catalin.marinas@arm.com>
Acked-by: Will Deacon <will@kernel.org>
Acked-by: Andrey Konovalov <andreyknvl@google.com>
Cc: Vincenzo Frascino <vincenzo.frascino@arm.com>
Cc: Szabolcs Nagy <szabolcs.nagy@arm.com>
Cc: Kevin Brodsky <kevin.brodsky@arm.com>
Cc: Dave P Martin <Dave.Martin@arm.com>
Cc: Dave Hansen <dave.hansen@intel.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: nbd_internal_command_common (struct nbd_handle *h,
uint16_t flags, uint16_t type,
uint64_t offset, uint64_t count, int count_err,
void *data, struct command_cb *cb)
{
struct command *cmd;
if (h->disconnect_request) {
set_error (EINVAL, "cannot request more commands after NBD_CMD_DISC");
goto err;
}
if (h->in_flight == INT_MAX) {
set_error (ENOMEM, "too many commands already in flight");
goto err;
}
if (count_err) {
if ((h->strict & LIBNBD_STRICT_ZERO_SIZE) && count == 0) {
set_error (EINVAL, "count cannot be 0");
goto err;
}
if ((h->strict & LIBNBD_STRICT_BOUNDS) &&
(offset > h->exportsize || count > h->exportsize - offset)) {
set_error (count_err, "request out of bounds");
goto err;
}
if (h->block_minimum && (h->strict & LIBNBD_STRICT_ALIGN) &&
(offset | count) & (h->block_minimum - 1)) {
set_error (EINVAL, "request is unaligned");
goto err;
}
}
switch (type) {
/* Commands which send or receive data are limited to MAX_REQUEST_SIZE. */
case NBD_CMD_READ:
case NBD_CMD_WRITE:
if (count > MAX_REQUEST_SIZE) {
set_error (ERANGE, "request too large: maximum request size is %d",
MAX_REQUEST_SIZE);
goto err;
}
break;
/* Other commands are currently limited by the 32 bit field in the
* command structure on the wire, but in future we hope to support
* 64 bit values here with a change to the NBD protocol which is
* being discussed upstream.
*/
default:
if (count > UINT32_MAX) {
set_error (ERANGE, "request too large: maximum request size is %" PRIu32,
UINT32_MAX);
goto err;
}
break;
}
cmd = calloc (1, sizeof *cmd);
if (cmd == NULL) {
set_error (errno, "calloc");
goto err;
}
cmd->flags = flags;
cmd->type = type;
cmd->cookie = h->unique++;
cmd->offset = offset;
cmd->count = count;
cmd->data = data;
if (cb)
cmd->cb = *cb;
/* If structured replies were negotiated then we trust the server to
* send back sufficient data to cover the whole buffer. It's tricky
* to check this, so an easier thing is simply to zero the buffer
* ahead of time which avoids any security problems. I measured the
* overhead of this and for non-TLS there is no measurable overhead
* in the highly intensive loopback case. For TLS we get a
* performance gain, go figure. For an older server with only
* simple replies, it's still better to do the same memset() so we
* don't have behavior that is server-dependent.
*/
if (cmd->data && type == NBD_CMD_READ)
memset (cmd->data, 0, cmd->count);
/* Add the command to the end of the queue. Kick the state machine
* if there is no other command being processed, otherwise, it will
* be handled automatically on a future cycle around to READY.
* Beyond this point, we have to return a cookie to the user, since
* we are queuing the command, even if kicking the state machine
* detects a failure. Not reporting a state machine failure here is
* okay - any caller of an async command will be calling more API to
* await results, and will eventually learn that the machine has
* moved on to DEAD at that time.
*/
h->in_flight++;
if (h->cmds_to_issue != NULL) {
assert (nbd_internal_is_state_processing (get_next_state (h)));
h->cmds_to_issue_tail = h->cmds_to_issue_tail->next = cmd;
}
else {
assert (h->cmds_to_issue_tail == NULL);
h->cmds_to_issue = h->cmds_to_issue_tail = cmd;
if (nbd_internal_is_state_ready (get_next_state (h)) &&
nbd_internal_run (h, cmd_issue) == -1)
debug (h, "command queued, ignoring state machine failure");
}
return cmd->cookie;
err:
/* Since we did not queue the command, we must free the callbacks. */
if (cb) {
if (type == NBD_CMD_BLOCK_STATUS)
FREE_CALLBACK (cb->fn.extent);
if (type == NBD_CMD_READ)
FREE_CALLBACK (cb->fn.chunk);
FREE_CALLBACK (cb->completion);
}
return -1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-252'], 'message': 'api: Guarantee sanitized buffer on pread failure
As mentioned in the previous patch, we left the state of the buffer
undefined if we fail pread prior to attempting NBD_CMD_READ. Better
is to tweak the generator to sanitize the buffer unconditionally, as a
way of hardening against potential bugs in client applications that
fail to check for errors, but which should not be leaking
uninitialized data. In the process, we can document that the contents
of buf are now merely unspecified, rather than undefined (valgrind
will no longer complain if you read buf, regardless of how nbd_pread
failed).
Since always calling memset() can be a performance hit if the client
also sanitizes the buffer or is willing to take the audit risk, the
next patch will add a knob that allows the client to control when this
happens.
This patch causes changes to just the four APIs
nbd_{aio_,}pread{,_structured}, with the generated lib/api.c changes
looking like:
| --- lib/api.c.bak 2022-02-10 08:15:05.418371357 -0600
| +++ lib/api.c 2022-02-10 08:15:13.224372023 -0600
| @@ -2871,6 +2871,7 @@ nbd_pread (struct nbd_handle *h, void *b
| debug (h, "enter: buf=<buf> count=%zu offset=%" PRIu64 " flags=0x%x", count, offset, flags);
| }
|
| + memset (buf, 0, count);
| if (unlikely (!pread_in_permitted_state (h))) {
| ret = -1;
| goto out;
Message-Id: <20220209220726.1902761-3-eblake@redhat.com>
Acked-by: Laszlo Ersek <lersek@redhat.com>
[eblake: enhance commit message to show generated file diff]
Reviewed-by: Richard W.M. Jones <rjones@redhat.com>
(cherry picked from commit c7fbc71de54bf4e477011176197ad22950a02aa3)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: duint32 dwgCompressor::longCompressionOffset(){
duint32 cont = 0;
duint8 ll = bufC[pos++];
while (ll == 0x00){
cont += 0xFF;
ll = bufC[pos++];
}
cont += ll;
return cont;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-191'], 'message': 'fixed out-of-bounds write vulnerability CVE-2021-21898
as reported in TALOS-2021-1349 / CVE-2021-21898,
dwgCompressor::decompress18() could be abused with a malformed DWG file
to force out-of-bounds write and possibly lead to malicious code
execution.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: duint32 dwgCompressor::compressedByte(void)
{
duint32 result {0};
compressedGood = (compressedPos < compressedSize);
if (compressedGood) {
result = compressedBuffer[compressedPos];
++compressedPos;
}
return result;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-191'], 'message': 'fixed heap buffer overflow vulnerability CVE-2021-21899
as reported in TALOS-2021-1350 / CVE-2021-21899,
dwgCompressor::decompress21() could be abused with a malformed DWG file
to force heap buffer overflow and possibly lead to malicious code
execution.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void jsP_dumplist(js_State *J, js_Ast *prog)
{
minify = 0;
if (prog->type == AST_LIST)
sblock(0, prog);
else
snode(0, prog);
nl();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Issue #161: Cope with empty programs in mujs-pp.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: inline int qs_parse(char* qs, char* qs_kv[], int qs_kv_size, bool parse_url = true)
{
int i, j;
char * substr_ptr;
for(i=0; i<qs_kv_size; i++) qs_kv[i] = NULL;
// find the beginning of the k/v substrings or the fragment
substr_ptr = parse_url ? qs + strcspn(qs, "?#") : qs;
if (parse_url)
{
if (substr_ptr[0] != '\0')
substr_ptr++;
else
return 0; // no query or fragment
}
i=0;
while(i<qs_kv_size)
{
qs_kv[i] = substr_ptr;
j = strcspn(substr_ptr, "&");
if ( substr_ptr[j] == '\0' ) { break; }
substr_ptr += j + 1;
i++;
}
i++; // x &'s -> means x iterations of this loop -> means *x+1* k/v pairs
// we only decode the values in place, the keys could have '='s in them
// which will hose our ability to distinguish keys from values later
for(j=0; j<i; j++)
{
substr_ptr = qs_kv[j] + strcspn(qs_kv[j], "=&#");
if ( substr_ptr[0] == '&' || substr_ptr[0] == '\0') // blank value: skip decoding
substr_ptr[0] = '\0';
else
qs_decode(++substr_ptr);
}
#ifdef _qsSORTING
// TODO: qsort qs_kv, using qs_strncmp() for the comparison
#endif
return i;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'Fixed issue where an index in qs_parse is incorrectly incremented beyond the maximum possible value'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int rose_route_frame(struct sk_buff *skb, ax25_cb *ax25)
{
struct rose_neigh *rose_neigh, *new_neigh;
struct rose_route *rose_route;
struct rose_facilities_struct facilities;
rose_address *src_addr, *dest_addr;
struct sock *sk;
unsigned short frametype;
unsigned int lci, new_lci;
unsigned char cause, diagnostic;
struct net_device *dev;
int len, res = 0;
char buf[11];
#if 0
if (call_in_firewall(PF_ROSE, skb->dev, skb->data, NULL, &skb) != FW_ACCEPT)
return res;
#endif
frametype = skb->data[2];
lci = ((skb->data[0] << 8) & 0xF00) + ((skb->data[1] << 0) & 0x0FF);
src_addr = (rose_address *)(skb->data + 9);
dest_addr = (rose_address *)(skb->data + 4);
spin_lock_bh(&rose_neigh_list_lock);
spin_lock_bh(&rose_route_list_lock);
rose_neigh = rose_neigh_list;
while (rose_neigh != NULL) {
if (ax25cmp(&ax25->dest_addr, &rose_neigh->callsign) == 0 &&
ax25->ax25_dev->dev == rose_neigh->dev)
break;
rose_neigh = rose_neigh->next;
}
if (rose_neigh == NULL) {
printk("rose_route : unknown neighbour or device %s\n",
ax2asc(buf, &ax25->dest_addr));
goto out;
}
/*
* Obviously the link is working, halt the ftimer.
*/
rose_stop_ftimer(rose_neigh);
/*
* LCI of zero is always for us, and its always a restart
* frame.
*/
if (lci == 0) {
rose_link_rx_restart(skb, rose_neigh, frametype);
goto out;
}
/*
* Find an existing socket.
*/
if ((sk = rose_find_socket(lci, rose_neigh)) != NULL) {
if (frametype == ROSE_CALL_REQUEST) {
struct rose_sock *rose = rose_sk(sk);
/* Remove an existing unused socket */
rose_clear_queues(sk);
rose->cause = ROSE_NETWORK_CONGESTION;
rose->diagnostic = 0;
rose->neighbour->use--;
rose->neighbour = NULL;
rose->lci = 0;
rose->state = ROSE_STATE_0;
sk->sk_state = TCP_CLOSE;
sk->sk_err = 0;
sk->sk_shutdown |= SEND_SHUTDOWN;
if (!sock_flag(sk, SOCK_DEAD)) {
sk->sk_state_change(sk);
sock_set_flag(sk, SOCK_DEAD);
}
}
else {
skb_reset_transport_header(skb);
res = rose_process_rx_frame(sk, skb);
goto out;
}
}
/*
* Is is a Call Request and is it for us ?
*/
if (frametype == ROSE_CALL_REQUEST)
if ((dev = rose_dev_get(dest_addr)) != NULL) {
res = rose_rx_call_request(skb, dev, rose_neigh, lci);
dev_put(dev);
goto out;
}
if (!sysctl_rose_routing_control) {
rose_transmit_clear_request(rose_neigh, lci, ROSE_NOT_OBTAINABLE, 0);
goto out;
}
/*
* Route it to the next in line if we have an entry for it.
*/
rose_route = rose_route_list;
while (rose_route != NULL) {
if (rose_route->lci1 == lci &&
rose_route->neigh1 == rose_neigh) {
if (frametype == ROSE_CALL_REQUEST) {
/* F6FBB - Remove an existing unused route */
rose_remove_route(rose_route);
break;
} else if (rose_route->neigh2 != NULL) {
skb->data[0] &= 0xF0;
skb->data[0] |= (rose_route->lci2 >> 8) & 0x0F;
skb->data[1] = (rose_route->lci2 >> 0) & 0xFF;
rose_transmit_link(skb, rose_route->neigh2);
if (frametype == ROSE_CLEAR_CONFIRMATION)
rose_remove_route(rose_route);
res = 1;
goto out;
} else {
if (frametype == ROSE_CLEAR_CONFIRMATION)
rose_remove_route(rose_route);
goto out;
}
}
if (rose_route->lci2 == lci &&
rose_route->neigh2 == rose_neigh) {
if (frametype == ROSE_CALL_REQUEST) {
/* F6FBB - Remove an existing unused route */
rose_remove_route(rose_route);
break;
} else if (rose_route->neigh1 != NULL) {
skb->data[0] &= 0xF0;
skb->data[0] |= (rose_route->lci1 >> 8) & 0x0F;
skb->data[1] = (rose_route->lci1 >> 0) & 0xFF;
rose_transmit_link(skb, rose_route->neigh1);
if (frametype == ROSE_CLEAR_CONFIRMATION)
rose_remove_route(rose_route);
res = 1;
goto out;
} else {
if (frametype == ROSE_CLEAR_CONFIRMATION)
rose_remove_route(rose_route);
goto out;
}
}
rose_route = rose_route->next;
}
/*
* We know that:
* 1. The frame isn't for us,
* 2. It isn't "owned" by any existing route.
*/
if (frametype != ROSE_CALL_REQUEST) { /* XXX */
res = 0;
goto out;
}
len = (((skb->data[3] >> 4) & 0x0F) + 1) >> 1;
len += (((skb->data[3] >> 0) & 0x0F) + 1) >> 1;
memset(&facilities, 0x00, sizeof(struct rose_facilities_struct));
if (!rose_parse_facilities(skb->data + len + 4, &facilities)) {
rose_transmit_clear_request(rose_neigh, lci, ROSE_INVALID_FACILITY, 76);
goto out;
}
/*
* Check for routing loops.
*/
rose_route = rose_route_list;
while (rose_route != NULL) {
if (rose_route->rand == facilities.rand &&
rosecmp(src_addr, &rose_route->src_addr) == 0 &&
ax25cmp(&facilities.dest_call, &rose_route->src_call) == 0 &&
ax25cmp(&facilities.source_call, &rose_route->dest_call) == 0) {
rose_transmit_clear_request(rose_neigh, lci, ROSE_NOT_OBTAINABLE, 120);
goto out;
}
rose_route = rose_route->next;
}
if ((new_neigh = rose_get_neigh(dest_addr, &cause, &diagnostic, 1)) == NULL) {
rose_transmit_clear_request(rose_neigh, lci, cause, diagnostic);
goto out;
}
if ((new_lci = rose_new_lci(new_neigh)) == 0) {
rose_transmit_clear_request(rose_neigh, lci, ROSE_NETWORK_CONGESTION, 71);
goto out;
}
if ((rose_route = kmalloc(sizeof(*rose_route), GFP_ATOMIC)) == NULL) {
rose_transmit_clear_request(rose_neigh, lci, ROSE_NETWORK_CONGESTION, 120);
goto out;
}
rose_route->lci1 = lci;
rose_route->src_addr = *src_addr;
rose_route->dest_addr = *dest_addr;
rose_route->src_call = facilities.dest_call;
rose_route->dest_call = facilities.source_call;
rose_route->rand = facilities.rand;
rose_route->neigh1 = rose_neigh;
rose_route->lci2 = new_lci;
rose_route->neigh2 = new_neigh;
rose_route->neigh1->use++;
rose_route->neigh2->use++;
rose_route->next = rose_route_list;
rose_route_list = rose_route;
skb->data[0] &= 0xF0;
skb->data[0] |= (rose_route->lci2 >> 8) & 0x0F;
skb->data[1] = (rose_route->lci2 >> 0) & 0xFF;
rose_transmit_link(skb, rose_route->neigh2);
res = 1;
out:
spin_unlock_bh(&rose_route_list_lock);
spin_unlock_bh(&rose_neigh_list_lock);
return res;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'rose: Add length checks to CALL_REQUEST parsing
Define some constant offsets for CALL_REQUEST based on the description
at <http://www.techfest.com/networking/wan/x25plp.htm> and the
definition of ROSE as using 10-digit (5-byte) addresses. Use them
consistently. Validate all implicit and explicit facilities lengths.
Validate the address length byte rather than either trusting or
assuming its value.
Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int build_ntlmssp_auth_blob(unsigned char **pbuffer,
u16 *buflen,
struct cifs_ses *ses,
const struct nls_table *nls_cp)
{
int rc;
AUTHENTICATE_MESSAGE *sec_blob;
__u32 flags;
unsigned char *tmp;
rc = setup_ntlmv2_rsp(ses, nls_cp);
if (rc) {
cifs_dbg(VFS, "Error %d during NTLMSSP authentication\n", rc);
*buflen = 0;
goto setup_ntlmv2_ret;
}
*pbuffer = kmalloc(size_of_ntlmssp_blob(ses), GFP_KERNEL);
sec_blob = (AUTHENTICATE_MESSAGE *)*pbuffer;
memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
sec_blob->MessageType = NtLmAuthenticate;
flags = NTLMSSP_NEGOTIATE_56 |
NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_TARGET_INFO |
NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |
NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC;
if (ses->server->sign) {
flags |= NTLMSSP_NEGOTIATE_SIGN;
if (!ses->server->session_estab ||
ses->ntlmssp->sesskey_per_smbsess)
flags |= NTLMSSP_NEGOTIATE_KEY_XCH;
}
tmp = *pbuffer + sizeof(AUTHENTICATE_MESSAGE);
sec_blob->NegotiateFlags = cpu_to_le32(flags);
sec_blob->LmChallengeResponse.BufferOffset =
cpu_to_le32(sizeof(AUTHENTICATE_MESSAGE));
sec_blob->LmChallengeResponse.Length = 0;
sec_blob->LmChallengeResponse.MaximumLength = 0;
sec_blob->NtChallengeResponse.BufferOffset =
cpu_to_le32(tmp - *pbuffer);
if (ses->user_name != NULL) {
memcpy(tmp, ses->auth_key.response + CIFS_SESS_KEY_SIZE,
ses->auth_key.len - CIFS_SESS_KEY_SIZE);
tmp += ses->auth_key.len - CIFS_SESS_KEY_SIZE;
sec_blob->NtChallengeResponse.Length =
cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);
sec_blob->NtChallengeResponse.MaximumLength =
cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);
} else {
/*
* don't send an NT Response for anonymous access
*/
sec_blob->NtChallengeResponse.Length = 0;
sec_blob->NtChallengeResponse.MaximumLength = 0;
}
if (ses->domainName == NULL) {
sec_blob->DomainName.BufferOffset = cpu_to_le32(tmp - *pbuffer);
sec_blob->DomainName.Length = 0;
sec_blob->DomainName.MaximumLength = 0;
tmp += 2;
} else {
int len;
len = cifs_strtoUTF16((__le16 *)tmp, ses->domainName,
CIFS_MAX_DOMAINNAME_LEN, nls_cp);
len *= 2; /* unicode is 2 bytes each */
sec_blob->DomainName.BufferOffset = cpu_to_le32(tmp - *pbuffer);
sec_blob->DomainName.Length = cpu_to_le16(len);
sec_blob->DomainName.MaximumLength = cpu_to_le16(len);
tmp += len;
}
if (ses->user_name == NULL) {
sec_blob->UserName.BufferOffset = cpu_to_le32(tmp - *pbuffer);
sec_blob->UserName.Length = 0;
sec_blob->UserName.MaximumLength = 0;
tmp += 2;
} else {
int len;
len = cifs_strtoUTF16((__le16 *)tmp, ses->user_name,
CIFS_MAX_USERNAME_LEN, nls_cp);
len *= 2; /* unicode is 2 bytes each */
sec_blob->UserName.BufferOffset = cpu_to_le32(tmp - *pbuffer);
sec_blob->UserName.Length = cpu_to_le16(len);
sec_blob->UserName.MaximumLength = cpu_to_le16(len);
tmp += len;
}
sec_blob->WorkstationName.BufferOffset = cpu_to_le32(tmp - *pbuffer);
sec_blob->WorkstationName.Length = 0;
sec_blob->WorkstationName.MaximumLength = 0;
tmp += 2;
if (((ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_KEY_XCH) ||
(ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_EXTENDED_SEC))
&& !calc_seckey(ses)) {
memcpy(tmp, ses->ntlmssp->ciphertext, CIFS_CPHTXT_SIZE);
sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer);
sec_blob->SessionKey.Length = cpu_to_le16(CIFS_CPHTXT_SIZE);
sec_blob->SessionKey.MaximumLength =
cpu_to_le16(CIFS_CPHTXT_SIZE);
tmp += CIFS_CPHTXT_SIZE;
} else {
sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer);
sec_blob->SessionKey.Length = 0;
sec_blob->SessionKey.MaximumLength = 0;
}
*buflen = tmp - *pbuffer;
setup_ntlmv2_ret:
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'CIFS: Enable encryption during session setup phase
In order to allow encryption on SMB connection we need to exchange
a session key and generate encryption and decryption keys.
Signed-off-by: Pavel Shilovsky <pshilov@microsoft.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ephy_string_shorten (char *str,
gsize target_length)
{
char *new_str;
glong actual_length;
gulong bytes;
g_assert (target_length > 0);
if (!str)
return NULL;
/* FIXME: this function is a big mess. While it is utf-8 safe now,
* it can still split a sequence of combining characters.
*/
actual_length = g_utf8_strlen (str, -1);
/* if the string is already short enough, or if it's too short for
* us to shorten it, return a new copy */
if ((gsize)actual_length <= target_length)
return str;
/* create string */
bytes = GPOINTER_TO_UINT (g_utf8_offset_to_pointer (str, target_length - 1) - str);
/* +1 for ellipsis, +1 for trailing NUL */
new_str = g_new (gchar, bytes + 1 + 1);
strncpy (new_str, str, bytes);
strcat (new_str, "…");
g_free (str);
return new_str;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Fix memory corruption in ephy_string_shorten()
This fixes a regression that I introduced in 232c613472b38ff0d0d97338f366024ddb9cd228.
I got my browser stuck in a crash loop today while visiting a website
with a page title greater than ephy-embed.c's MAX_TITLE_LENGTH, the only
condition in which ephy_string_shorten() is ever used. Turns out this
commit is wrong: an ellipses is a multibyte character (three bytes in
UTF-8) and so we're writing past the end of the buffer when calling
strcat() here. Ooops.
Shame it took nearly four years to notice and correct this.
Part-of: <https://gitlab.gnome.org/GNOME/epiphany/-/merge_requests/1106>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ftrace_regex_lseek(struct file *file, loff_t offset, int whence)
{
loff_t ret;
if (file->f_mode & FMODE_READ)
ret = seq_lseek(file, offset, whence);
else
file->f_pos = ret = 1;
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], '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/1365663302-2170-1-git-send-email-namhyung@kernel.org
Cc: Frederic Weisbecker <fweisbec@gmail.com>
Cc: Ingo Molnar <mingo@kernel.org>
Cc: Namhyung Kim <namhyung.kim@lge.com>
Cc: stable@vger.kernel.org
Signed-off-by: Namhyung Kim <namhyung@kernel.org>
Signed-off-by: Steven Rostedt <rostedt@goodmis.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
{
AVFilterContext *ctx = inlink->dst;
FPSContext *s = ctx->priv;
AVFilterLink *outlink = ctx->outputs[0];
int64_t delta;
int i, ret;
s->frames_in++;
/* discard frames until we get the first timestamp */
if (s->pts == AV_NOPTS_VALUE) {
if (buf->pts != AV_NOPTS_VALUE) {
ret = write_to_fifo(s->fifo, buf);
if (ret < 0)
return ret;
if (s->start_time != DBL_MAX && s->start_time != AV_NOPTS_VALUE) {
double first_pts = s->start_time * AV_TIME_BASE;
first_pts = FFMIN(FFMAX(first_pts, INT64_MIN), INT64_MAX);
s->first_pts = s->pts = av_rescale_q(first_pts, AV_TIME_BASE_Q,
inlink->time_base);
av_log(ctx, AV_LOG_VERBOSE, "Set first pts to (in:%"PRId64" out:%"PRId64")\n",
s->first_pts, av_rescale_q(first_pts, AV_TIME_BASE_Q,
outlink->time_base));
} else {
s->first_pts = s->pts = buf->pts;
}
} else {
av_log(ctx, AV_LOG_WARNING, "Discarding initial frame(s) with no "
"timestamp.\n");
av_frame_free(&buf);
s->drop++;
}
return 0;
}
/* now wait for the next timestamp */
if (buf->pts == AV_NOPTS_VALUE) {
return write_to_fifo(s->fifo, buf);
}
/* number of output frames */
delta = av_rescale_q_rnd(buf->pts - s->pts, inlink->time_base,
outlink->time_base, s->rounding);
if (delta < 1) {
/* drop the frame and everything buffered except the first */
AVFrame *tmp;
int drop = av_fifo_size(s->fifo)/sizeof(AVFrame*);
av_log(ctx, AV_LOG_DEBUG, "Dropping %d frame(s).\n", drop);
s->drop += drop;
av_fifo_generic_read(s->fifo, &tmp, sizeof(tmp), NULL);
flush_fifo(s->fifo);
ret = write_to_fifo(s->fifo, tmp);
av_frame_free(&buf);
return ret;
}
/* can output >= 1 frames */
for (i = 0; i < delta; i++) {
AVFrame *buf_out;
av_fifo_generic_read(s->fifo, &buf_out, sizeof(buf_out), NULL);
/* duplicate the frame if needed */
if (!av_fifo_size(s->fifo) && i < delta - 1) {
AVFrame *dup = av_frame_clone(buf_out);
av_log(ctx, AV_LOG_DEBUG, "Duplicating frame.\n");
if (dup)
ret = write_to_fifo(s->fifo, dup);
else
ret = AVERROR(ENOMEM);
if (ret < 0) {
av_frame_free(&buf_out);
av_frame_free(&buf);
return ret;
}
s->dup++;
}
buf_out->pts = av_rescale_q(s->first_pts, inlink->time_base,
outlink->time_base) + s->frames_out;
if ((ret = ff_filter_frame(outlink, buf_out)) < 0) {
av_frame_free(&buf);
return ret;
}
s->frames_out++;
}
flush_fifo(s->fifo);
ret = write_to_fifo(s->fifo, buf);
s->pts = s->first_pts + av_rescale_q(s->frames_out, outlink->time_base, inlink->time_base);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'avfilter/vf_fps: make sure the fifo is not empty before using it
Fixes Ticket2905
Signed-off-by: Michael Niedermayer <michaelni@gmx.at>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int udf_read_inode(struct inode *inode, bool hidden_inode)
{
struct buffer_head *bh = NULL;
struct fileEntry *fe;
struct extendedFileEntry *efe;
uint16_t ident;
struct udf_inode_info *iinfo = UDF_I(inode);
struct udf_sb_info *sbi = UDF_SB(inode->i_sb);
struct kernel_lb_addr *iloc = &iinfo->i_location;
unsigned int link_count;
unsigned int indirections = 0;
int bs = inode->i_sb->s_blocksize;
int ret = -EIO;
reread:
if (iloc->logicalBlockNum >=
sbi->s_partmaps[iloc->partitionReferenceNum].s_partition_len) {
udf_debug("block=%d, partition=%d out of range\n",
iloc->logicalBlockNum, iloc->partitionReferenceNum);
return -EIO;
}
/*
* Set defaults, but the inode is still incomplete!
* Note: get_new_inode() sets the following on a new inode:
* i_sb = sb
* i_no = ino
* i_flags = sb->s_flags
* i_state = 0
* clean_inode(): zero fills and sets
* i_count = 1
* i_nlink = 1
* i_op = NULL;
*/
bh = udf_read_ptagged(inode->i_sb, iloc, 0, &ident);
if (!bh) {
udf_err(inode->i_sb, "(ino %ld) failed !bh\n", inode->i_ino);
return -EIO;
}
if (ident != TAG_IDENT_FE && ident != TAG_IDENT_EFE &&
ident != TAG_IDENT_USE) {
udf_err(inode->i_sb, "(ino %ld) failed ident=%d\n",
inode->i_ino, ident);
goto out;
}
fe = (struct fileEntry *)bh->b_data;
efe = (struct extendedFileEntry *)bh->b_data;
if (fe->icbTag.strategyType == cpu_to_le16(4096)) {
struct buffer_head *ibh;
ibh = udf_read_ptagged(inode->i_sb, iloc, 1, &ident);
if (ident == TAG_IDENT_IE && ibh) {
struct kernel_lb_addr loc;
struct indirectEntry *ie;
ie = (struct indirectEntry *)ibh->b_data;
loc = lelb_to_cpu(ie->indirectICB.extLocation);
if (ie->indirectICB.extLength) {
brelse(ibh);
memcpy(&iinfo->i_location, &loc,
sizeof(struct kernel_lb_addr));
if (++indirections > UDF_MAX_ICB_NESTING) {
udf_err(inode->i_sb,
"too many ICBs in ICB hierarchy"
" (max %d supported)\n",
UDF_MAX_ICB_NESTING);
goto out;
}
brelse(bh);
goto reread;
}
}
brelse(ibh);
} else if (fe->icbTag.strategyType != cpu_to_le16(4)) {
udf_err(inode->i_sb, "unsupported strategy type: %d\n",
le16_to_cpu(fe->icbTag.strategyType));
goto out;
}
if (fe->icbTag.strategyType == cpu_to_le16(4))
iinfo->i_strat4096 = 0;
else /* if (fe->icbTag.strategyType == cpu_to_le16(4096)) */
iinfo->i_strat4096 = 1;
iinfo->i_alloc_type = le16_to_cpu(fe->icbTag.flags) &
ICBTAG_FLAG_AD_MASK;
iinfo->i_unique = 0;
iinfo->i_lenEAttr = 0;
iinfo->i_lenExtents = 0;
iinfo->i_lenAlloc = 0;
iinfo->i_next_alloc_block = 0;
iinfo->i_next_alloc_goal = 0;
if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_EFE)) {
iinfo->i_efe = 1;
iinfo->i_use = 0;
ret = udf_alloc_i_data(inode, bs -
sizeof(struct extendedFileEntry));
if (ret)
goto out;
memcpy(iinfo->i_ext.i_data,
bh->b_data + sizeof(struct extendedFileEntry),
bs - sizeof(struct extendedFileEntry));
} else if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_FE)) {
iinfo->i_efe = 0;
iinfo->i_use = 0;
ret = udf_alloc_i_data(inode, bs - sizeof(struct fileEntry));
if (ret)
goto out;
memcpy(iinfo->i_ext.i_data,
bh->b_data + sizeof(struct fileEntry),
bs - sizeof(struct fileEntry));
} else if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_USE)) {
iinfo->i_efe = 0;
iinfo->i_use = 1;
iinfo->i_lenAlloc = le32_to_cpu(
((struct unallocSpaceEntry *)bh->b_data)->
lengthAllocDescs);
ret = udf_alloc_i_data(inode, bs -
sizeof(struct unallocSpaceEntry));
if (ret)
goto out;
memcpy(iinfo->i_ext.i_data,
bh->b_data + sizeof(struct unallocSpaceEntry),
bs - sizeof(struct unallocSpaceEntry));
return 0;
}
ret = -EIO;
read_lock(&sbi->s_cred_lock);
i_uid_write(inode, le32_to_cpu(fe->uid));
if (!uid_valid(inode->i_uid) ||
UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_IGNORE) ||
UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_SET))
inode->i_uid = UDF_SB(inode->i_sb)->s_uid;
i_gid_write(inode, le32_to_cpu(fe->gid));
if (!gid_valid(inode->i_gid) ||
UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_IGNORE) ||
UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_SET))
inode->i_gid = UDF_SB(inode->i_sb)->s_gid;
if (fe->icbTag.fileType != ICBTAG_FILE_TYPE_DIRECTORY &&
sbi->s_fmode != UDF_INVALID_MODE)
inode->i_mode = sbi->s_fmode;
else if (fe->icbTag.fileType == ICBTAG_FILE_TYPE_DIRECTORY &&
sbi->s_dmode != UDF_INVALID_MODE)
inode->i_mode = sbi->s_dmode;
else
inode->i_mode = udf_convert_permissions(fe);
inode->i_mode &= ~sbi->s_umask;
read_unlock(&sbi->s_cred_lock);
link_count = le16_to_cpu(fe->fileLinkCount);
if (!link_count) {
if (!hidden_inode) {
ret = -ESTALE;
goto out;
}
link_count = 1;
}
set_nlink(inode, link_count);
inode->i_size = le64_to_cpu(fe->informationLength);
iinfo->i_lenExtents = inode->i_size;
if (iinfo->i_efe == 0) {
inode->i_blocks = le64_to_cpu(fe->logicalBlocksRecorded) <<
(inode->i_sb->s_blocksize_bits - 9);
if (!udf_disk_stamp_to_time(&inode->i_atime, fe->accessTime))
inode->i_atime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&inode->i_mtime,
fe->modificationTime))
inode->i_mtime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&inode->i_ctime, fe->attrTime))
inode->i_ctime = sbi->s_record_time;
iinfo->i_unique = le64_to_cpu(fe->uniqueID);
iinfo->i_lenEAttr = le32_to_cpu(fe->lengthExtendedAttr);
iinfo->i_lenAlloc = le32_to_cpu(fe->lengthAllocDescs);
iinfo->i_checkpoint = le32_to_cpu(fe->checkpoint);
} else {
inode->i_blocks = le64_to_cpu(efe->logicalBlocksRecorded) <<
(inode->i_sb->s_blocksize_bits - 9);
if (!udf_disk_stamp_to_time(&inode->i_atime, efe->accessTime))
inode->i_atime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&inode->i_mtime,
efe->modificationTime))
inode->i_mtime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&iinfo->i_crtime, efe->createTime))
iinfo->i_crtime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&inode->i_ctime, efe->attrTime))
inode->i_ctime = sbi->s_record_time;
iinfo->i_unique = le64_to_cpu(efe->uniqueID);
iinfo->i_lenEAttr = le32_to_cpu(efe->lengthExtendedAttr);
iinfo->i_lenAlloc = le32_to_cpu(efe->lengthAllocDescs);
iinfo->i_checkpoint = le32_to_cpu(efe->checkpoint);
}
inode->i_generation = iinfo->i_unique;
/* Sanity checks for files in ICB so that we don't get confused later */
if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) {
/*
* For file in ICB data is stored in allocation descriptor
* so sizes should match
*/
if (iinfo->i_lenAlloc != inode->i_size)
goto out;
/* File in ICB has to fit in there... */
if (inode->i_size > bs - udf_file_entry_alloc_offset(inode))
goto out;
}
switch (fe->icbTag.fileType) {
case ICBTAG_FILE_TYPE_DIRECTORY:
inode->i_op = &udf_dir_inode_operations;
inode->i_fop = &udf_dir_operations;
inode->i_mode |= S_IFDIR;
inc_nlink(inode);
break;
case ICBTAG_FILE_TYPE_REALTIME:
case ICBTAG_FILE_TYPE_REGULAR:
case ICBTAG_FILE_TYPE_UNDEF:
case ICBTAG_FILE_TYPE_VAT20:
if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB)
inode->i_data.a_ops = &udf_adinicb_aops;
else
inode->i_data.a_ops = &udf_aops;
inode->i_op = &udf_file_inode_operations;
inode->i_fop = &udf_file_operations;
inode->i_mode |= S_IFREG;
break;
case ICBTAG_FILE_TYPE_BLOCK:
inode->i_mode |= S_IFBLK;
break;
case ICBTAG_FILE_TYPE_CHAR:
inode->i_mode |= S_IFCHR;
break;
case ICBTAG_FILE_TYPE_FIFO:
init_special_inode(inode, inode->i_mode | S_IFIFO, 0);
break;
case ICBTAG_FILE_TYPE_SOCKET:
init_special_inode(inode, inode->i_mode | S_IFSOCK, 0);
break;
case ICBTAG_FILE_TYPE_SYMLINK:
inode->i_data.a_ops = &udf_symlink_aops;
inode->i_op = &udf_symlink_inode_operations;
inode->i_mode = S_IFLNK | S_IRWXUGO;
break;
case ICBTAG_FILE_TYPE_MAIN:
udf_debug("METADATA FILE-----\n");
break;
case ICBTAG_FILE_TYPE_MIRROR:
udf_debug("METADATA MIRROR FILE-----\n");
break;
case ICBTAG_FILE_TYPE_BITMAP:
udf_debug("METADATA BITMAP FILE-----\n");
break;
default:
udf_err(inode->i_sb, "(ino %ld) failed unknown file type=%d\n",
inode->i_ino, fe->icbTag.fileType);
goto out;
}
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
struct deviceSpec *dsea =
(struct deviceSpec *)udf_get_extendedattr(inode, 12, 1);
if (dsea) {
init_special_inode(inode, inode->i_mode,
MKDEV(le32_to_cpu(dsea->majorDeviceIdent),
le32_to_cpu(dsea->minorDeviceIdent)));
/* Developer ID ??? */
} else
goto out;
}
ret = 0;
out:
brelse(bh);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'udf: Check length of extended attributes and allocation descriptors
Check length of extended attributes and allocation descriptors when
loading inodes from disk. Otherwise corrupted filesystems could confuse
the code and make the kernel oops.
Reported-by: Carl Henrik Lunde <chlunde@ping.uio.no>
CC: stable@vger.kernel.org
Signed-off-by: Jan Kara <jack@suse.cz>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int ndpi_netbios_name_interpret(char *in, size_t in_len, char *out, u_int out_len) {
u_int ret = 0, len, idx = in_len, out_idx = 0;
len = (*in++)/2;
out_len--;
out[out_idx] = 0;
if((len > out_len) || (len < 1) || ((2*len) > in_len))
return(-1);
while((len--) && (out_idx < out_len)) {
if((idx < 2) || (in[0] < 'A') || (in[0] > 'P') || (in[1] < 'A') || (in[1] > 'P')) {
out[out_idx] = 0;
break;
}
out[out_idx] = ((in[0] - 'A') << 4) + (in[1] - 'A');
in += 2, idx -= 2;
if(isprint(out[out_idx]))
out_idx++, ret++;
}
/* Trim trailing whitespace from the returned string */
if(out_idx > 0) {
out[out_idx] = 0;
out_idx--;
while((out_idx > 0) && (out[out_idx] == ' ')) {
out[out_idx] = 0;
out_idx--;
}
}
return(ret);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Added further checks'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: vsyslog(pri, fmt, ap)
int pri;
register const char *fmt;
va_list ap;
{
struct tm now_tm;
time_t now;
int fd;
FILE *f;
char *buf = 0;
size_t bufsize = 0;
size_t prioff, msgoff;
struct sigaction action, oldaction;
struct sigaction *oldaction_ptr = NULL;
int sigpipe;
int saved_errno = errno;
#define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
/* Check for invalid bits. */
if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
syslog(INTERNALLOG,
"syslog: unknown facility/priority: %x", pri);
pri &= LOG_PRIMASK|LOG_FACMASK;
}
/* Check priority against setlogmask values. */
if ((LOG_MASK (LOG_PRI (pri)) & LogMask) == 0)
return;
/* Set default facility if none specified. */
if ((pri & LOG_FACMASK) == 0)
pri |= LogFacility;
/* Build the message in a memory-buffer stream. */
f = open_memstream (&buf, &bufsize);
prioff = fprintf (f, "<%d>", pri);
(void) time (&now);
#ifdef USE_IN_LIBIO
f->_IO_write_ptr += strftime (f->_IO_write_ptr,
f->_IO_write_end - f->_IO_write_ptr,
"%h %e %T ",
__localtime_r (&now, &now_tm));
#else
f->__bufp += strftime (f->__bufp, f->__put_limit - f->__bufp,
"%h %e %T ", __localtime_r (&now, &now_tm));
#endif
msgoff = ftell (f);
if (LogTag == NULL)
LogTag = __progname;
if (LogTag != NULL)
fputs_unlocked (LogTag, f);
if (LogStat & LOG_PID)
fprintf (f, "[%d]", __getpid ());
if (LogTag != NULL)
putc_unlocked (':', f), putc_unlocked (' ', f);
/* Restore errno for %m format. */
__set_errno (saved_errno);
/* We have the header. Print the user's format into the buffer. */
vfprintf (f, fmt, ap);
/* Close the memory stream; this will finalize the data
into a malloc'd buffer in BUF. */
fclose (f);
/* Output to stderr if requested. */
if (LogStat & LOG_PERROR) {
struct iovec iov[2];
register struct iovec *v = iov;
v->iov_base = buf + msgoff;
v->iov_len = bufsize - msgoff;
++v;
v->iov_base = (char *) "\n";
v->iov_len = 1;
(void)__writev(STDERR_FILENO, iov, 2);
}
/* Prepare for multiple users. We have to take care: open and
write are cancellation points. */
__libc_cleanup_region_start ((void (*) (void *)) cancel_handler,
&oldaction_ptr);
__libc_lock_lock (syslog_lock);
/* Prepare for a broken connection. */
memset (&action, 0, sizeof (action));
action.sa_handler = sigpipe_handler;
sigemptyset (&action.sa_mask);
sigpipe = __sigaction (SIGPIPE, &action, &oldaction);
if (sigpipe == 0)
oldaction_ptr = &oldaction;
/* Get connected, output the message to the local logger. */
if (!connected)
openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
/* If we have a SOCK_STREAM connection, also send ASCII NUL as
a record terminator. */
if (LogType == SOCK_STREAM)
++bufsize;
if (!connected || __send(LogFile, buf, bufsize, 0) < 0)
{
closelog_internal (); /* attempt re-open next time */
/*
* Output the message to the console; don't worry about blocking,
* if console blocks everything will. Make sure the error reported
* is the one from the syslogd failure.
*/
if (LogStat & LOG_CONS &&
(fd = __open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY, 0)) >= 0)
{
dprintf (fd, "%s\r\n", buf + msgoff);
(void)__close(fd);
}
}
if (sigpipe == 0)
__sigaction (SIGPIPE, &oldaction, (struct sigaction *) NULL);
/* End of critical section. */
__libc_cleanup_region_end (0);
__libc_lock_unlock (syslog_lock);
free (buf);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190', 'CWE-252'], 'message': 'Update.
1999-11-09 Ulrich Drepper <drepper@cygnus.com>
* elf/dl-load.c (_dl_dst_count): Allow $ORIGIN to point to
directory with the reference since this is as secure as using the
object with the dependency.
(_dl_dst_substitute): Likewise.
* elf/dl-load.c (_dl_dst_count): Change strings in first two
strncmp calls to allow reuse.
(_dl_dst_substitute): Likewise.
1999-11-01 Arnold D. Robbins <arnold@skeeve.com>
* posix/regex.c (init_syntax_once): move below definition of
ISALNUM etc., then use ISALNUM to init the table, so that
the word ops will work if i18n'ed.
(SYNTAX): And subscript with 0xFF for 8bit character sets.
1999-11-09 Andreas Jaeger <aj@suse.de>
* sysdeps/unix/getlogin_r.c (getlogin_r): Sync with getlogin
implementation for ttyname_r call; fix inverted condition; return
ut_user. Closes PR libc/1438.
1999-11-09 Ulrich Drepper <drepper@cygnus.com>
* timezone/checktab.awk: Update from tzcode1999h.
* timezone/africa: Update from tzdata1999i.
* timezone/asia: Likewise.
* timezone/australasia: Likewise.
* timezone/backward: Likewise.
* timezone/europe: Likewise.
* timezone/northamerica: Likewise.
* timezone/southamerica: Likewise.
* timezone/iso3166.tab: Likewise.
* timezone/zone.tab: Likewise.
* sysdeps/unix/sysv/linux/bits/resource.h: Define values also as
macros. Patch by brg@csua.berkeley.edu [PR libc/1439].
1999-11-09 Andreas Jaeger <aj@suse.de>
* posix/Makefile (tests): Added tst-getlogin.
* posix/tst-getlogin.c: New file, contains simple tests for
getlogin and getlogin_r.
1999-11-09 Andreas Schwab <schwab@suse.de>
* misc/syslog.c: For LOG_PERROR only append a newline if
necessary.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_nack(
const void *buf,
pj_size_t length,
unsigned *nack_cnt,
pjmedia_rtcp_fb_nack nack[])
{
pjmedia_rtcp_common *hdr = (pjmedia_rtcp_common*) buf;
pj_uint8_t *p;
unsigned cnt, i;
PJ_ASSERT_RETURN(buf && nack_cnt && nack, PJ_EINVAL);
PJ_ASSERT_RETURN(length >= sizeof(pjmedia_rtcp_common), PJ_ETOOSMALL);
/* Generic NACK uses pt==RTCP_RTPFB and FMT==1 */
if (hdr->pt != RTCP_RTPFB || hdr->count != 1)
return PJ_ENOTFOUND;
cnt = pj_ntohs((pj_uint16_t)hdr->length);
if (cnt > 2) cnt -= 2; else cnt = 0;
if (length < (cnt+3)*4)
return PJ_ETOOSMALL;
*nack_cnt = PJ_MIN(*nack_cnt, cnt);
p = (pj_uint8_t*)hdr + sizeof(*hdr);
for (i = 0; i < *nack_cnt; ++i) {
pj_uint16_t val;
pj_memcpy(&val, p, 2);
nack[i].pid = pj_ntohs(val);
pj_memcpy(&val, p+2, 2);
nack[i].blp = pj_ntohs(val);
p += 4;
}
return PJ_SUCCESS;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-787'], 'message': 'Merge pull request from GHSA-vhxv-phmx-g52q
* Prevent OOB read/write when parsing RTCP FB RPSI
* Add log information
* Modification based on comments.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: GPMF_ERR IsValidSize(GPMF_stream *ms, uint32_t size) // size is in longs not bytes.
{
if (ms)
{
int32_t nestsize = (int32_t)ms->nest_size[ms->nest_level];
if (nestsize == 0 && ms->nest_level == 0)
nestsize = ms->buffer_size_longs;
if (size + 2 <= nestsize) return GPMF_OK;
}
return GPMF_ERROR_BAD_STRUCTURE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-369', 'CWE-787'], 'message': 'fixed many security issues with the too crude mp4 reader'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void ext4_free_branches(handle_t *handle, struct inode *inode,
struct buffer_head *parent_bh,
__le32 *first, __le32 *last, int depth)
{
ext4_fsblk_t nr;
__le32 *p;
if (ext4_handle_is_aborted(handle))
return;
if (depth--) {
struct buffer_head *bh;
int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
p = last;
while (--p >= first) {
nr = le32_to_cpu(*p);
if (!nr)
continue; /* A hole */
if (!ext4_data_block_valid(EXT4_SB(inode->i_sb),
nr, 1)) {
EXT4_ERROR_INODE(inode,
"invalid indirect mapped "
"block %lu (level %d)",
(unsigned long) nr, depth);
break;
}
/* Go read the buffer for the next level down */
bh = sb_bread(inode->i_sb, nr);
/*
* A read failure? Report error and clear slot
* (should be rare).
*/
if (!bh) {
ext4_error_inode_block(inode, nr, EIO,
"Read failure");
continue;
}
/* This zaps the entire block. Bottom up. */
BUFFER_TRACE(bh, "free child branches");
ext4_free_branches(handle, inode, bh,
(__le32 *) bh->b_data,
(__le32 *) bh->b_data + addr_per_block,
depth);
brelse(bh);
/*
* Everything below this this pointer has been
* released. Now let this top-of-subtree go.
*
* We want the freeing of this indirect block to be
* atomic in the journal with the updating of the
* bitmap block which owns it. So make some room in
* the journal.
*
* We zero the parent pointer *after* freeing its
* pointee in the bitmaps, so if extend_transaction()
* for some reason fails to put the bitmap changes and
* the release into the same transaction, recovery
* will merely complain about releasing a free block,
* rather than leaking blocks.
*/
if (ext4_handle_is_aborted(handle))
return;
if (ext4_ind_truncate_ensure_credits(handle, inode,
NULL,
ext4_free_metadata_revoke_credits(
inode->i_sb, 1)) < 0)
return;
/*
* The forget flag here is critical because if
* we are journaling (and not doing data
* journaling), we have to make sure a revoke
* record is written to prevent the journal
* replay from overwriting the (former)
* indirect block if it gets reallocated as a
* data block. This must happen in the same
* transaction where the data blocks are
* actually freed.
*/
ext4_free_blocks(handle, inode, NULL, nr, 1,
EXT4_FREE_BLOCKS_METADATA|
EXT4_FREE_BLOCKS_FORGET);
if (parent_bh) {
/*
* The block which we have just freed is
* pointed to by an indirect block: journal it
*/
BUFFER_TRACE(parent_bh, "get_write_access");
if (!ext4_journal_get_write_access(handle,
parent_bh)){
*p = 0;
BUFFER_TRACE(parent_bh,
"call ext4_handle_dirty_metadata");
ext4_handle_dirty_metadata(handle,
inode,
parent_bh);
}
}
}
} else {
/* We have reached the bottom of the tree. */
BUFFER_TRACE(parent_bh, "free data blocks");
ext4_free_data(handle, inode, parent_bh, first, last);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'ext4: check journal inode extents more carefully
Currently, system zones just track ranges of block, that are "important"
fs metadata (bitmaps, group descriptors, journal blocks, etc.). This
however complicates how extent tree (or indirect blocks) can be checked
for inodes that actually track such metadata - currently the journal
inode but arguably we should be treating quota files or resize inode
similarly. We cannot run __ext4_ext_check() on such metadata inodes when
loading their extents as that would immediately trigger the validity
checks and so we just hack around that and special-case the journal
inode. This however leads to a situation that a journal inode which has
extent tree of depth at least one can have invalid extent tree that gets
unnoticed until ext4_cache_extents() crashes.
To overcome this limitation, track inode number each system zone belongs
to (0 is used for zones not belonging to any inode). We can then verify
inode number matches the expected one when verifying extent tree and
thus avoid the false errors. With this there's no need to to
special-case journal inode during extent tree checking anymore so remove
it.
Fixes: 0a944e8a6c66 ("ext4: don't perform block validity checks on the journal inode")
Reported-by: Wolfgang Frisch <wolfgang.frisch@suse.com>
Reviewed-by: Lukas Czerner <lczerner@redhat.com>
Signed-off-by: Jan Kara <jack@suse.cz>
Link: https://lore.kernel.org/r/20200728130437.7804-4-jack@suse.cz
Signed-off-by: Theodore Ts'o <tytso@mit.edu>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int ext4_valid_extent_idx(struct inode *inode,
struct ext4_extent_idx *ext_idx)
{
ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'ext4: check journal inode extents more carefully
Currently, system zones just track ranges of block, that are "important"
fs metadata (bitmaps, group descriptors, journal blocks, etc.). This
however complicates how extent tree (or indirect blocks) can be checked
for inodes that actually track such metadata - currently the journal
inode but arguably we should be treating quota files or resize inode
similarly. We cannot run __ext4_ext_check() on such metadata inodes when
loading their extents as that would immediately trigger the validity
checks and so we just hack around that and special-case the journal
inode. This however leads to a situation that a journal inode which has
extent tree of depth at least one can have invalid extent tree that gets
unnoticed until ext4_cache_extents() crashes.
To overcome this limitation, track inode number each system zone belongs
to (0 is used for zones not belonging to any inode). We can then verify
inode number matches the expected one when verifying extent tree and
thus avoid the false errors. With this there's no need to to
special-case journal inode during extent tree checking anymore so remove
it.
Fixes: 0a944e8a6c66 ("ext4: don't perform block validity checks on the journal inode")
Reported-by: Wolfgang Frisch <wolfgang.frisch@suse.com>
Reviewed-by: Lukas Czerner <lczerner@redhat.com>
Signed-off-by: Jan Kara <jack@suse.cz>
Link: https://lore.kernel.org/r/20200728130437.7804-4-jack@suse.cz
Signed-off-by: Theodore Ts'o <tytso@mit.edu>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: njs_vm_start(njs_vm_t *vm)
{
njs_int_t ret;
ret = njs_module_load(vm);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
ret = njs_vmcode_interpreter(vm, vm->start);
return (ret == NJS_ERROR) ? NJS_ERROR : NJS_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Fixed recursive async function calls.
Previously, PromiseCapability record was stored (function->context)
directly in function object during a function invocation. This is
not correct, because PromiseCapability record should be linked to
current execution context. As a result, function->context is
overwritten with consecutive recursive calls which results in
use-after-free.
This closes #451 issue on Github.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
int noblock = flags & MSG_DONTWAIT;
struct sock *sk = sock->sk;
struct sk_buff *skb;
size_t copied;
int err;
BT_DBG("sock %p sk %p len %zu", sock, sk, len);
if (flags & (MSG_OOB))
return -EOPNOTSUPP;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb) {
if (sk->sk_shutdown & RCV_SHUTDOWN) {
msg->msg_namelen = 0;
return 0;
}
return err;
}
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
skb_reset_transport_header(skb);
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err == 0) {
sock_recv_ts_and_drops(msg, sk, skb);
if (bt_sk(sk)->skb_msg_name)
bt_sk(sk)->skb_msg_name(skb, msg->msg_name,
&msg->msg_namelen);
else
msg->msg_namelen = 0;
}
skb_free_datagram(sk, skb);
return err ? : copied;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-269'], '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 <davem@davemloft.net>
Suggested-by: Eric Dumazet <eric.dumazet@gmail.com>
Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int recv_msg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t buf_len, int flags)
{
struct sock *sk = sock->sk;
struct tipc_port *tport = tipc_sk_port(sk);
struct sk_buff *buf;
struct tipc_msg *msg;
long timeout;
unsigned int sz;
u32 err;
int res;
/* Catch invalid receive requests */
if (unlikely(!buf_len))
return -EINVAL;
lock_sock(sk);
if (unlikely(sock->state == SS_UNCONNECTED)) {
res = -ENOTCONN;
goto exit;
}
/* will be updated in set_orig_addr() if needed */
m->msg_namelen = 0;
timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
restart:
/* Look for a message in receive queue; wait if necessary */
while (skb_queue_empty(&sk->sk_receive_queue)) {
if (sock->state == SS_DISCONNECTING) {
res = -ENOTCONN;
goto exit;
}
if (timeout <= 0L) {
res = timeout ? timeout : -EWOULDBLOCK;
goto exit;
}
release_sock(sk);
timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
tipc_rx_ready(sock),
timeout);
lock_sock(sk);
}
/* Look at first message in receive queue */
buf = skb_peek(&sk->sk_receive_queue);
msg = buf_msg(buf);
sz = msg_data_sz(msg);
err = msg_errcode(msg);
/* Discard an empty non-errored message & try again */
if ((!sz) && (!err)) {
advance_rx_queue(sk);
goto restart;
}
/* Capture sender's address (optional) */
set_orig_addr(m, msg);
/* Capture ancillary data (optional) */
res = anc_data_recv(m, msg, tport);
if (res)
goto exit;
/* Capture message data (if valid) & compute return value (always) */
if (!err) {
if (unlikely(buf_len < sz)) {
sz = buf_len;
m->msg_flags |= MSG_TRUNC;
}
res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg),
m->msg_iov, sz);
if (res)
goto exit;
res = sz;
} else {
if ((sock->state == SS_READY) ||
((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
res = 0;
else
res = -ECONNRESET;
}
/* Consume received message (optional) */
if (likely(!(flags & MSG_PEEK))) {
if ((sock->state != SS_READY) &&
(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
tipc_acknowledge(tport->ref, tport->conn_unacked);
advance_rx_queue(sk);
}
exit:
release_sock(sk);
return res;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-269'], '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 <davem@davemloft.net>
Suggested-by: Eric Dumazet <eric.dumazet@gmail.com>
Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int rfcomm_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
int len;
if (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) {
rfcomm_dlc_accept(d);
msg->msg_namelen = 0;
return 0;
}
len = bt_sock_stream_recvmsg(iocb, sock, msg, size, flags);
lock_sock(sk);
if (!(flags & MSG_PEEK) && len > 0)
atomic_sub(len, &sk->sk_rmem_alloc);
if (atomic_read(&sk->sk_rmem_alloc) <= (sk->sk_rcvbuf >> 2))
rfcomm_dlc_unthrottle(rfcomm_pi(sk)->dlc);
release_sock(sk);
return len;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-269'], '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 <davem@davemloft.net>
Suggested-by: Eric Dumazet <eric.dumazet@gmail.com>
Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
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;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-269'], '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 <davem@davemloft.net>
Suggested-by: Eric Dumazet <eric.dumazet@gmail.com>
Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus GatherStrings(TfLiteContext* context, const TfLiteTensor* input,
const TfLiteTensor* positions,
TfLiteTensor* output) {
DynamicBuffer buffer;
const PositionT* indexes = GetTensorData<PositionT>(positions);
const PositionT num_strings = GetStringCount(input);
const int num_indexes = NumElements(positions);
for (int i = 0; i < num_indexes; ++i) {
const PositionT pos = indexes[i];
TF_LITE_ENSURE(context, pos < num_strings);
const auto string_ref = GetString(input, pos);
buffer.AddString(string_ref.str, string_ref.len);
}
buffer.WriteToTensor(output, /*new_shape=*/nullptr);
return kTfLiteOk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'Prevent heap OOB read in TFLite's `gather.cc`.
Passing negative indices is illegal but there was a missing check so that resulted in OOB accesses.
PiperOrigin-RevId: 387231300
Change-Id: I3111b54b2f232638d795be17efc46abe4ede6bf8'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int caf_parse(caf_reader_t *reader, int64_t *data_length)
{
uint32_t fcc;
int64_t chunk_size;
*data_length = 0;
/* CAFFileHeader */
TRY_IO(pcm_read32be(&reader->io, &fcc));
ENSURE(fcc == M4AF_FOURCC('c','a','f','f'));
TRY_IO(pcm_skip(&reader->io, 4)); /* mFileVersion, mFileFlags */
while ((fcc = caf_next_chunk(reader, &chunk_size)) != 0) {
if (fcc == M4AF_FOURCC('d','e','s','c'))
TRY_IO(caf_desc(reader, chunk_size));
else if (fcc == M4AF_FOURCC('i','n','f','o'))
TRY_IO(caf_info(reader, chunk_size));
else if (fcc == M4AF_FOURCC('c','h','a','n')) {
ENSURE(reader->sample_format.channels_per_frame);
if (apple_chan_chunk(&reader->io, chunk_size,
&reader->sample_format, reader->chanmap) < 0)
goto FAIL;
} else if (fcc == M4AF_FOURCC('d','a','t','a')) {
TRY_IO(pcm_skip(&reader->io, 4)); /* mEditCount */
*data_length = (chunk_size == ~0ULL) ? chunk_size : chunk_size - 4;
reader->data_offset = pcm_tell(&reader->io);
break;
} else
TRY_IO(pcm_skip(&reader->io, chunk_size));
}
ENSURE(reader->sample_format.channels_per_frame);
ENSURE(fcc == M4AF_FOURCC('d','a','t','a'));
return 0;
FAIL:
return -1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'wav/caf parser: ensure fmt/desc chunk
fixes https://github.com/nu774/fdkaac/issues/52'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static s32 gf_hevc_read_pps_bs_internal(GF_BitStream *bs, HEVCState *hevc)
{
u32 i;
s32 pps_id;
HEVC_PPS *pps;
//NAL header already read
pps_id = gf_bs_read_ue_log(bs, "pps_id");
if ((pps_id < 0) || (pps_id >= 64)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] wrong PPS ID %d in PPS\n", pps_id));
return -1;
}
pps = &hevc->pps[pps_id];
if (!pps->state) {
pps->id = pps_id;
pps->state = 1;
}
pps->sps_id = gf_bs_read_ue_log(bs, "sps_id");
if (pps->sps_id >= 16) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] wrong SPS ID %d in PPS\n", pps->sps_id));
pps->sps_id=0;
return -1;
}
hevc->sps_active_idx = pps->sps_id; /*set active sps*/
pps->dependent_slice_segments_enabled_flag = gf_bs_read_int_log(bs, 1, "dependent_slice_segments_enabled_flag");
pps->output_flag_present_flag = gf_bs_read_int_log(bs, 1, "output_flag_present_flag");
pps->num_extra_slice_header_bits = gf_bs_read_int_log(bs, 3, "num_extra_slice_header_bits");
pps->sign_data_hiding_flag = gf_bs_read_int_log(bs, 1, "sign_data_hiding_flag");
pps->cabac_init_present_flag = gf_bs_read_int_log(bs, 1, "cabac_init_present_flag");
pps->num_ref_idx_l0_default_active = 1 + gf_bs_read_ue_log(bs, "num_ref_idx_l0_default_active");
pps->num_ref_idx_l1_default_active = 1 + gf_bs_read_ue_log(bs, "num_ref_idx_l1_default_active");
pps->pic_init_qp_minus26 = gf_bs_read_se_log(bs, "pic_init_qp_minus26");
pps->constrained_intra_pred_flag = gf_bs_read_int_log(bs, 1, "constrained_intra_pred_flag");
pps->transform_skip_enabled_flag = gf_bs_read_int_log(bs, 1, "transform_skip_enabled_flag");
if ((pps->cu_qp_delta_enabled_flag = gf_bs_read_int_log(bs, 1, "cu_qp_delta_enabled_flag")))
pps->diff_cu_qp_delta_depth = gf_bs_read_ue_log(bs, "diff_cu_qp_delta_depth");
pps->pic_cb_qp_offset = gf_bs_read_se_log(bs, "pic_cb_qp_offset");
pps->pic_cr_qp_offset = gf_bs_read_se_log(bs, "pic_cr_qp_offset");
pps->slice_chroma_qp_offsets_present_flag = gf_bs_read_int_log(bs, 1, "slice_chroma_qp_offsets_present_flag");
pps->weighted_pred_flag = gf_bs_read_int_log(bs, 1, "weighted_pred_flag");
pps->weighted_bipred_flag = gf_bs_read_int_log(bs, 1, "weighted_bipred_flag");
pps->transquant_bypass_enable_flag = gf_bs_read_int_log(bs, 1, "transquant_bypass_enable_flag");
pps->tiles_enabled_flag = gf_bs_read_int_log(bs, 1, "tiles_enabled_flag");
pps->entropy_coding_sync_enabled_flag = gf_bs_read_int_log(bs, 1, "entropy_coding_sync_enabled_flag");
if (pps->tiles_enabled_flag) {
pps->num_tile_columns = 1 + gf_bs_read_ue_log(bs, "num_tile_columns_minus1");
pps->num_tile_rows = 1 + gf_bs_read_ue_log(bs, "num_tile_rows_minus1");
pps->uniform_spacing_flag = gf_bs_read_int_log(bs, 1, "uniform_spacing_flag");
if (!pps->uniform_spacing_flag) {
for (i = 0; i < pps->num_tile_columns - 1; i++) {
pps->column_width[i] = 1 + gf_bs_read_ue_log_idx(bs, "column_width_minus1", i);
}
for (i = 0; i < pps->num_tile_rows - 1; i++) {
pps->row_height[i] = 1 + gf_bs_read_ue_log_idx(bs, "row_height_minus1", i);
}
}
pps->loop_filter_across_tiles_enabled_flag = gf_bs_read_int_log(bs, 1, "loop_filter_across_tiles_enabled_flag");
}
pps->loop_filter_across_slices_enabled_flag = gf_bs_read_int_log(bs, 1, "loop_filter_across_slices_enabled_flag");
if ((pps->deblocking_filter_control_present_flag = gf_bs_read_int_log(bs, 1, "deblocking_filter_control_present_flag"))) {
pps->deblocking_filter_override_enabled_flag = gf_bs_read_int_log(bs, 1, "deblocking_filter_override_enabled_flag");
if (! (pps->pic_disable_deblocking_filter_flag = gf_bs_read_int_log(bs, 1, "pic_disable_deblocking_filter_flag"))) {
pps->beta_offset_div2 = gf_bs_read_se_log(bs, "beta_offset_div2");
pps->tc_offset_div2 = gf_bs_read_se_log(bs, "tc_offset_div2");
}
}
if ((pps->pic_scaling_list_data_present_flag = gf_bs_read_int_log(bs, 1, "pic_scaling_list_data_present_flag"))) {
hevc_scaling_list_data(bs);
}
pps->lists_modification_present_flag = gf_bs_read_int_log(bs, 1, "lists_modification_present_flag");
pps->log2_parallel_merge_level_minus2 = gf_bs_read_ue_log(bs, "log2_parallel_merge_level_minus2");
pps->slice_segment_header_extension_present_flag = gf_bs_read_int_log(bs, 1, "slice_segment_header_extension_present_flag");
if (gf_bs_read_int_log(bs, 1, "pps_extension_flag")) {
#if 0
while (gf_bs_available(bs)) {
/*pps_extension_data_flag */ gf_bs_read_int(bs, 1);
}
#endif
}
return pps_id;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'add safety in avc/hevc/vvc sps/pps/vps ID check - cf #1720 #1721 #1722'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int g2m_init_buffers(G2MContext *c)
{
int aligned_height;
if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) {
c->framebuf_stride = FFALIGN(c->width * 3, 16);
aligned_height = FFALIGN(c->height, 16);
av_free(c->framebuf);
c->framebuf = av_mallocz(c->framebuf_stride * aligned_height);
if (!c->framebuf)
return AVERROR(ENOMEM);
}
if (!c->synth_tile || !c->jpeg_tile ||
c->old_tile_w < c->tile_width ||
c->old_tile_h < c->tile_height) {
c->tile_stride = FFALIGN(c->tile_width, 16) * 3;
aligned_height = FFALIGN(c->tile_height, 16);
av_free(c->synth_tile);
av_free(c->jpeg_tile);
av_free(c->kempf_buf);
av_free(c->kempf_flags);
c->synth_tile = av_mallocz(c->tile_stride * aligned_height);
c->jpeg_tile = av_mallocz(c->tile_stride * aligned_height);
c->kempf_buf = av_mallocz((c->tile_width + 1) * aligned_height
+ FF_INPUT_BUFFER_PADDING_SIZE);
c->kempf_flags = av_mallocz( c->tile_width * aligned_height);
if (!c->synth_tile || !c->jpeg_tile ||
!c->kempf_buf || !c->kempf_flags)
return AVERROR(ENOMEM);
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'avcodec/g2meet: Fix framebuf size
Currently the code can in some cases draw tiles that hang outside the
allocated buffer. This patch increases the buffer size to avoid out
of array accesses. An alternative would be to fail if such tiles are
encountered.
I do not know if any valid files use such hanging tiles.
Fixes Ticket2971
Found-by: ami_stuff
Signed-off-by: Michael Niedermayer <michaelni@gmx.at>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ngx_http_lua_adjust_subrequest(ngx_http_request_t *sr, ngx_uint_t method,
int always_forward_body, ngx_http_request_body_t *body,
unsigned vars_action, ngx_array_t *extra_vars)
{
ngx_http_request_t *r;
ngx_int_t rc;
ngx_http_core_main_conf_t *cmcf;
size_t size;
r = sr->parent;
sr->header_in = r->header_in;
if (body) {
sr->request_body = body;
rc = ngx_http_lua_set_content_length_header(sr,
body->buf
? ngx_buf_size(body->buf)
: 0);
if (rc != NGX_OK) {
return NGX_ERROR;
}
} else if (!always_forward_body
&& method != NGX_HTTP_PUT
&& method != NGX_HTTP_POST
&& r->headers_in.content_length_n > 0)
{
rc = ngx_http_lua_set_content_length_header(sr, 0);
if (rc != NGX_OK) {
return NGX_ERROR;
}
#if 1
sr->request_body = NULL;
#endif
} else {
if (ngx_http_lua_copy_request_headers(sr, r) != NGX_OK) {
return NGX_ERROR;
}
if (sr->request_body) {
/* deep-copy the request body */
if (sr->request_body->temp_file) {
if (ngx_http_lua_copy_in_file_request_body(sr) != NGX_OK) {
return NGX_ERROR;
}
}
}
}
sr->method = method;
switch (method) {
case NGX_HTTP_GET:
sr->method_name = ngx_http_lua_get_method;
break;
case NGX_HTTP_POST:
sr->method_name = ngx_http_lua_post_method;
break;
case NGX_HTTP_PUT:
sr->method_name = ngx_http_lua_put_method;
break;
case NGX_HTTP_HEAD:
sr->method_name = ngx_http_lua_head_method;
break;
case NGX_HTTP_DELETE:
sr->method_name = ngx_http_lua_delete_method;
break;
case NGX_HTTP_OPTIONS:
sr->method_name = ngx_http_lua_options_method;
break;
case NGX_HTTP_MKCOL:
sr->method_name = ngx_http_lua_mkcol_method;
break;
case NGX_HTTP_COPY:
sr->method_name = ngx_http_lua_copy_method;
break;
case NGX_HTTP_MOVE:
sr->method_name = ngx_http_lua_move_method;
break;
case NGX_HTTP_PROPFIND:
sr->method_name = ngx_http_lua_propfind_method;
break;
case NGX_HTTP_PROPPATCH:
sr->method_name = ngx_http_lua_proppatch_method;
break;
case NGX_HTTP_LOCK:
sr->method_name = ngx_http_lua_lock_method;
break;
case NGX_HTTP_UNLOCK:
sr->method_name = ngx_http_lua_unlock_method;
break;
case NGX_HTTP_PATCH:
sr->method_name = ngx_http_lua_patch_method;
break;
case NGX_HTTP_TRACE:
sr->method_name = ngx_http_lua_trace_method;
break;
default:
ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
"unsupported HTTP method: %u", (unsigned) method);
return NGX_ERROR;
}
if (!(vars_action & NGX_HTTP_LUA_SHARE_ALL_VARS)) {
/* we do not inherit the parent request's variables */
cmcf = ngx_http_get_module_main_conf(sr, ngx_http_core_module);
size = cmcf->variables.nelts * sizeof(ngx_http_variable_value_t);
if (vars_action & NGX_HTTP_LUA_COPY_ALL_VARS) {
sr->variables = ngx_palloc(sr->pool, size);
if (sr->variables == NULL) {
return NGX_ERROR;
}
ngx_memcpy(sr->variables, r->variables, size);
} else {
/* we do not inherit the parent request's variables */
sr->variables = ngx_pcalloc(sr->pool, size);
if (sr->variables == NULL) {
return NGX_ERROR;
}
}
}
return ngx_http_lua_subrequest_add_extra_vars(sr, extra_vars);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-444'], 'message': 'bugfix: prevented request smuggling in the ngx.location.capture API.
Signed-off-by: Yichun Zhang (agentzh) <yichun@openresty.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: AP4_AtomSampleTable::GetSample(AP4_Ordinal index,
AP4_Sample& sample)
{
AP4_Result result;
// check that we have a chunk offset table
if (m_StcoAtom == NULL && m_Co64Atom == NULL) {
return AP4_ERROR_INVALID_FORMAT;
}
// MP4 uses 1-based indexes internally, so adjust by one
index++;
// find out in which chunk this sample is located
AP4_Ordinal chunk, skip, desc;
result = m_StscAtom->GetChunkForSample(index, chunk, skip, desc);
if (AP4_FAILED(result)) return result;
// check that the result is within bounds
if (skip > index) return AP4_ERROR_INTERNAL;
// get the atom offset for this chunk
AP4_UI64 offset;
if (m_StcoAtom) {
AP4_UI32 offset_32;
result = m_StcoAtom->GetChunkOffset(chunk, offset_32);
offset = offset_32;
} else {
result = m_Co64Atom->GetChunkOffset(chunk, offset);
}
if (AP4_FAILED(result)) return result;
// compute the additional offset inside the chunk
for (unsigned int i = index-skip; i < index; i++) {
AP4_Size size = 0;
if (m_StszAtom) {
result = m_StszAtom->GetSampleSize(i, size);
} else if (m_Stz2Atom) {
result = m_Stz2Atom->GetSampleSize(i, size);
} else {
result = AP4_ERROR_INVALID_FORMAT;
}
if (AP4_FAILED(result)) return result;
offset += size;
}
// set the description index
sample.SetDescriptionIndex(desc-1); // adjust for 0-based indexes
// set the dts and cts
AP4_UI32 cts_offset = 0;
AP4_UI64 dts = 0;
AP4_UI32 duration = 0;
result = m_SttsAtom->GetDts(index, dts, &duration);
if (AP4_FAILED(result)) return result;
sample.SetDuration(duration);
sample.SetDts(dts);
if (m_CttsAtom == NULL) {
sample.SetCts(dts);
} else {
result = m_CttsAtom->GetCtsOffset(index, cts_offset);
if (AP4_FAILED(result)) return result;
sample.SetCtsDelta(cts_offset);
}
// set the size
AP4_Size sample_size = 0;
if (m_StszAtom) {
result = m_StszAtom->GetSampleSize(index, sample_size);
} else if (m_Stz2Atom) {
result = m_Stz2Atom->GetSampleSize(index, sample_size);
} else {
result = AP4_ERROR_INVALID_FORMAT;
}
if (AP4_FAILED(result)) return result;
sample.SetSize(sample_size);
// set the sync flag
if (m_StssAtom == NULL) {
sample.SetSync(true);
} else {
sample.SetSync(m_StssAtom->IsSampleSync(index));
}
// set the offset
sample.SetOffset(offset);
// set the data stream
sample.SetDataStream(m_SampleStream);
return AP4_SUCCESS;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476', 'CWE-703'], 'message': 'fixed possible crashes on malformed inputs.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: GF_Err url_box_read(GF_Box *s, GF_BitStream *bs)
{
GF_DataEntryURLBox *ptr = (GF_DataEntryURLBox *)s;
if (ptr->size) {
ptr->location = (char*)gf_malloc((u32) ptr->size);
if (! ptr->location) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, ptr->location, (u32)ptr->size);
}
return GF_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'fixed #1587'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void CLASS foveon_load_camf()
{
unsigned type, wide, high, i, j, row, col, diff;
ushort huff[258], vpred[2][2] = {{512,512},{512,512}}, hpred[2];
fseek (ifp, meta_offset, SEEK_SET);
type = get4(); get4(); get4();
wide = get4();
high = get4();
if (type == 2) {
fread (meta_data, 1, meta_length, ifp);
for (i=0; i < meta_length; i++) {
high = (high * 1597 + 51749) % 244944;
wide = high * (INT64) 301593171 >> 24;
meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17;
}
} else if (type == 4) {
free (meta_data);
meta_data = (char *) malloc (meta_length = wide*high*3/2);
merror (meta_data, "foveon_load_camf()");
foveon_huff (huff);
get4();
getbits(-1);
for (j=row=0; row < high; row++) {
for (col=0; col < wide; col++) {
diff = ljpeg_diff(huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
if (col & 1) {
meta_data[j++] = hpred[0] >> 4;
meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8;
meta_data[j++] = hpred[1];
}
}
}
} else
fprintf (stderr,_("%s has unknown CAMF type %d.\n"), ifname, type);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787', 'CWE-190'], 'message': 'Fixed possible foveon buffer overrun (Secunia SA750000)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: beep_print(netdissect_options *ndo, const u_char *bp, u_int length)
{
if (l_strnstart("MSG", 4, (const char *)bp, length)) /* A REQuest */
ND_PRINT((ndo, " BEEP MSG"));
else if (l_strnstart("RPY ", 4, (const char *)bp, length))
ND_PRINT((ndo, " BEEP RPY"));
else if (l_strnstart("ERR ", 4, (const char *)bp, length))
ND_PRINT((ndo, " BEEP ERR"));
else if (l_strnstart("ANS ", 4, (const char *)bp, length))
ND_PRINT((ndo, " BEEP ANS"));
else if (l_strnstart("NUL ", 4, (const char *)bp, length))
ND_PRINT((ndo, " BEEP NUL"));
else if (l_strnstart("SEQ ", 4, (const char *)bp, length))
ND_PRINT((ndo, " BEEP SEQ"));
else if (l_strnstart("END", 4, (const char *)bp, length))
ND_PRINT((ndo, " BEEP END"));
else
ND_PRINT((ndo, " BEEP (payload or undecoded)"));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13010/BEEP: Do bounds checking when comparing strings.
This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.
Add a test using the capture file supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TEST_CASE("Ordered choice count", "[general]")
{
parser parser(R"(
S <- 'a' / 'b'
)");
parser["S"] = [](const SemanticValues& sv) {
REQUIRE(sv.choice() == 1);
REQUIRE(sv.choice_count() == 2);
};
parser.parse("b");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix #122'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TEST_CASE("Action taking non const Semantic Values parameter", "[general]")
{
parser parser(R"(
ROOT <- TEXT
TEXT <- [a-zA-Z]+
)");
parser["ROOT"] = [&](SemanticValues& sv) {
auto s = any_cast<std::string>(sv[0]);
s[0] = 'H'; // mutate
return std::string(std::move(s)); // move
};
parser["TEXT"] = [&](SemanticValues& sv) {
return sv.token();
};
std::string val;
auto ret = parser.parse("hello", val);
REQUIRE(ret == true);
REQUIRE(val == "Hello");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix #122'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TEST_CASE("String capture test", "[general]")
{
parser parser(R"(
ROOT <- _ ('[' TAG_NAME ']' _)*
TAG_NAME <- (!']' .)+
_ <- [ \t]*
)");
std::vector<std::string> tags;
parser["TAG_NAME"] = [&](const SemanticValues& sv) {
tags.push_back(sv.str());
};
auto ret = parser.parse(" [tag1] [tag:2] [tag-3] ");
REQUIRE(ret == true);
REQUIRE(tags.size() == 3);
REQUIRE(tags[0] == "tag1");
REQUIRE(tags[1] == "tag:2");
REQUIRE(tags[2] == "tag-3");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix #122'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: name_len(netdissect_options *ndo,
const unsigned char *s, const unsigned char *maxbuf)
{
const unsigned char *s0 = s;
unsigned char c;
if (s >= maxbuf)
return(-1); /* name goes past the end of the buffer */
ND_TCHECK2(*s, 1);
c = *s;
if ((c & 0xC0) == 0xC0)
return(2);
while (*s) {
if (s >= maxbuf)
return(-1); /* name goes past the end of the buffer */
ND_TCHECK2(*s, 1);
s += (*s) + 1;
}
return(PTR_DIFF(s, s0) + 1);
trunc:
return(-1); /* name goes past the end of the buffer */
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2017-12893/SMB/CIFS: Add a bounds check in name_len().
After we advance the pointer by the length value in the buffer, make
sure it points to something in the captured data.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: gerbv_gdk_draw_prim4(GdkPixmap *pixmap, GdkGC *gc, double *p,
double scale, gint x, gint y)
{
const int exposure_idx = 0;
const int nuf_points_idx = 1;
const int first_x_idx = 2;
const int first_y_idx = 3;
const int rotext_idx = 4;
GdkGC *local_gc = gdk_gc_new(pixmap);
int nuf_points, point;
double rotation;
GdkPoint *points;
GdkColor color;
/* Include start point */
nuf_points = (int)p[nuf_points_idx] + 1;
points = g_new(GdkPoint, nuf_points);
if (!points) {
g_free(points);
return;
}
rotation = p[(nuf_points - 1) * 2 + rotext_idx];
for (point = 0; point < nuf_points; point++) {
points[point].x = (int)round(scale * p[point * 2 + first_x_idx]);
points[point].y = -(int)round(scale * p[point * 2 + first_y_idx]);
if (rotation != 0.0)
points[point] = rotate_point(points[point], rotation);
points[point].x += x;
points[point].y += y;
}
gdk_gc_copy(local_gc, gc);
/* Exposure */
if (p[exposure_idx] == 0.0) {
color.pixel = 0;
gdk_gc_set_foreground(local_gc, &color);
}
gdk_gc_set_line_attributes(local_gc,
1, /* outline always 1 pixels */
GDK_LINE_SOLID,
GDK_CAP_BUTT,
GDK_JOIN_MITER);
gdk_draw_polygon(pixmap, local_gc, 1, points, nuf_points);
g_free(points);
gdk_gc_unref(local_gc);
return;
} /* gerbv_gdk_draw_prim4 */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'Avoid direct access on array of unknown size
Be requiring a `gerbv_simplified_amacro_t` the `dgk_draw_amacro_funcs` can be sure of the length of the parameter array.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: if (sz + idx > maxSz || sz > WOLFSSH_MAX_HANDLE) {
WLOG(WS_LOG_SFTP, "Error with file handle size");
res = err;
type = WOLFSSH_FTP_FAILURE;
ret = WS_BAD_FILE_E;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'ASAN SFTP Fixes
When decoding SFTP messages, fix the size checks so they don't wrap. (ZD12766)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static bool ok_jpg_read_dht(ok_jpg_decoder *decoder) {
// JPEG spec: Table B.5
ok_jpg *jpg = decoder->jpg;
uint8_t buffer[17];
if (!ok_read(decoder, buffer, 2)) {
return false;
}
int length = readBE16(buffer) - 2;
while (length >= 17) {
if (!ok_read(decoder, buffer, 17)) {
return false;
}
length -= 17;
int Tc = buffer[0] >> 4;
int Th = buffer[0] & 0x0f;
if (Tc > 1 || Th > 3) {
ok_jpg_error(jpg, OK_JPG_ERROR_INVALID, "Invalid JPEG (Bad DHT Tc/Th)");
return false;
}
ok_jpg_huffman_table *tables = (Tc == 0 ? decoder->dc_huffman_tables :
decoder->ac_huffman_tables);
ok_jpg_huffman_table *table = tables + Th;
ok_jpg_generate_huffman_table(table, buffer);
if (table->count > 0) {
if (table->count > 256 || table->count > length) {
ok_jpg_error(jpg, OK_JPG_ERROR_INVALID, "Invalid DHT segment length");
return false;
}
if (!ok_read(decoder, table->val, (size_t)table->count)) {
return false;
}
length -= table->count;
}
bool is_ac_table = Tc == 1;
ok_jpg_generate_huffman_table_lookups(table, is_ac_table);
}
if (length != 0) {
ok_jpg_error(jpg, OK_JPG_ERROR_INVALID, "Invalid DHT segment length");
return false;
} else {
return true;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'ok_jpg: Fix invalid DHT (#11)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ompl::geometric::VFRRT::Motion *ompl::geometric::VFRRT::extendTree(Motion *m, base::State *rstate,
const Eigen::VectorXd &v)
{
base::State *newState = si_->allocState();
si_->copyState(newState, m->state);
double d = si_->distance(m->state, rstate);
if (d > maxDistance_)
d = maxDistance_;
const base::StateSpacePtr &space = si_->getStateSpace();
for (unsigned int i = 0; i < vfdim_; i++)
*space->getValueAddressAtIndex(newState, i) += d * v[i];
if (!v.hasNaN() && si_->checkMotion(m->state, newState))
{
auto *motion = new Motion(si_);
motion->state = newState;
motion->parent = m;
updateExplorationEfficiency(motion);
nn_->add(motion);
return motion;
}
else
{
si_->freeState(newState);
inefficientCount_++;
return nullptr;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'fix memory leak in VFRRT. closes #839'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2,
int fragmented)
{
char *cp;
const struct icmp *dp;
const struct icmp_ext_t *ext_dp;
const struct ip *ip;
const char *str, *fmt;
const struct ip *oip;
const struct udphdr *ouh;
const uint8_t *obj_tptr;
uint32_t raw_label;
const u_char *snapend_save;
const struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header;
u_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype;
char buf[MAXHOSTNAMELEN + 100];
struct cksum_vec vec[1];
dp = (const struct icmp *)bp;
ext_dp = (const struct icmp_ext_t *)bp;
ip = (const struct ip *)bp2;
str = buf;
ND_TCHECK(dp->icmp_code);
switch (dp->icmp_type) {
case ICMP_ECHO:
case ICMP_ECHOREPLY:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf), "echo %s, id %u, seq %u",
dp->icmp_type == ICMP_ECHO ?
"request" : "reply",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_UNREACH:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_UNREACH_PROTOCOL:
ND_TCHECK(dp->icmp_ip.ip_p);
(void)snprintf(buf, sizeof(buf),
"%s protocol %d unreachable",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
dp->icmp_ip.ip_p);
break;
case ICMP_UNREACH_PORT:
ND_TCHECK(dp->icmp_ip.ip_p);
oip = &dp->icmp_ip;
hlen = IP_HL(oip) * 4;
ouh = (const struct udphdr *)(((const u_char *)oip) + hlen);
ND_TCHECK(ouh->uh_dport);
dport = EXTRACT_16BITS(&ouh->uh_dport);
switch (oip->ip_p) {
case IPPROTO_TCP:
(void)snprintf(buf, sizeof(buf),
"%s tcp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
tcpport_string(ndo, dport));
break;
case IPPROTO_UDP:
(void)snprintf(buf, sizeof(buf),
"%s udp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
udpport_string(ndo, dport));
break;
default:
(void)snprintf(buf, sizeof(buf),
"%s protocol %d port %d unreachable",
ipaddr_string(ndo, &oip->ip_dst),
oip->ip_p, dport);
break;
}
break;
case ICMP_UNREACH_NEEDFRAG:
{
register const struct mtu_discovery *mp;
mp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void;
mtu = EXTRACT_16BITS(&mp->nexthopmtu);
if (mtu) {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag (mtu %d)",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu);
} else {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
}
}
break;
default:
fmt = tok2str(unreach2str, "#%d %%s unreachable",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
break;
}
break;
case ICMP_REDIRECT:
ND_TCHECK(dp->icmp_ip.ip_dst);
fmt = tok2str(type2str, "redirect-#%d %%s to net %%s",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
ipaddr_string(ndo, &dp->icmp_gwaddr));
break;
case ICMP_ROUTERADVERT:
{
register const struct ih_rdiscovery *ihp;
register const struct id_rdiscovery *idp;
u_int lifetime, num, size;
(void)snprintf(buf, sizeof(buf), "router advertisement");
cp = buf + strlen(buf);
ihp = (const struct ih_rdiscovery *)&dp->icmp_void;
ND_TCHECK(*ihp);
(void)strncpy(cp, " lifetime ", sizeof(buf) - (cp - buf));
cp = buf + strlen(buf);
lifetime = EXTRACT_16BITS(&ihp->ird_lifetime);
if (lifetime < 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u",
lifetime);
} else if (lifetime < 60 * 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u",
lifetime / 60, lifetime % 60);
} else {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
"%u:%02u:%02u",
lifetime / 3600,
(lifetime % 3600) / 60,
lifetime % 60);
}
cp = buf + strlen(buf);
num = ihp->ird_addrnum;
(void)snprintf(cp, sizeof(buf) - (cp - buf), " %d:", num);
cp = buf + strlen(buf);
size = ihp->ird_addrsiz;
if (size != 2) {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
" [size %d]", size);
break;
}
idp = (const struct id_rdiscovery *)&dp->icmp_data;
while (num-- > 0) {
ND_TCHECK(*idp);
(void)snprintf(cp, sizeof(buf) - (cp - buf), " {%s %u}",
ipaddr_string(ndo, &idp->ird_addr),
EXTRACT_32BITS(&idp->ird_pref));
cp = buf + strlen(buf);
++idp;
}
}
break;
case ICMP_TIMXCEED:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_TIMXCEED_INTRANS:
str = "time exceeded in-transit";
break;
case ICMP_TIMXCEED_REASS:
str = "ip reassembly time exceeded";
break;
default:
(void)snprintf(buf, sizeof(buf), "time exceeded-#%d",
dp->icmp_code);
break;
}
break;
case ICMP_PARAMPROB:
if (dp->icmp_code)
(void)snprintf(buf, sizeof(buf),
"parameter problem - code %d", dp->icmp_code);
else {
ND_TCHECK(dp->icmp_pptr);
(void)snprintf(buf, sizeof(buf),
"parameter problem - octet %d", dp->icmp_pptr);
}
break;
case ICMP_MASKREPLY:
ND_TCHECK(dp->icmp_mask);
(void)snprintf(buf, sizeof(buf), "address mask is 0x%08x",
EXTRACT_32BITS(&dp->icmp_mask));
break;
case ICMP_TSTAMP:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf),
"time stamp query id %u seq %u",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_TSTAMPREPLY:
ND_TCHECK(dp->icmp_ttime);
(void)snprintf(buf, sizeof(buf),
"time stamp reply id %u seq %u: org %s",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq),
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", recv %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", xmit %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime)));
break;
default:
str = tok2str(icmp2str, "type-#%d", dp->icmp_type);
break;
}
ND_PRINT((ndo, "ICMP %s, length %u", str, plen));
if (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */
uint16_t sum, icmp_sum;
if (ND_TTEST2(*bp, plen)) {
vec[0].ptr = (const uint8_t *)(const void *)dp;
vec[0].len = plen;
sum = in_cksum(vec, 1);
if (sum != 0) {
icmp_sum = EXTRACT_16BITS(&dp->icmp_cksum);
ND_PRINT((ndo, " (wrong icmp cksum %x (->%x)!)",
icmp_sum,
in_cksum_shouldbe(icmp_sum, sum)));
}
}
}
/*
* print the remnants of the IP packet.
* save the snaplength as this may get overidden in the IP printer.
*/
if (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) {
bp += 8;
ND_PRINT((ndo, "\n\t"));
ip = (const struct ip *)bp;
snapend_save = ndo->ndo_snapend;
ip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len));
ndo->ndo_snapend = snapend_save;
}
/*
* Attempt to decode the MPLS extensions only for some ICMP types.
*/
if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) {
ND_TCHECK(*ext_dp);
/*
* Check first if the mpls extension header shows a non-zero length.
* If the length field is not set then silently verify the checksum
* to check if an extension header is present. This is expedient,
* however not all implementations set the length field proper.
*/
if (!ext_dp->icmp_length &&
ND_TTEST2(ext_dp->icmp_ext_version_res, plen - ICMP_EXTD_MINLEN)) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = plen - ICMP_EXTD_MINLEN;
if (in_cksum(vec, 1)) {
return;
}
}
ND_PRINT((ndo, "\n\tMPLS extension v%u",
ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res))));
/*
* Sanity checking of the header.
*/
if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) !=
ICMP_MPLS_EXT_VERSION) {
ND_PRINT((ndo, " packet not supported"));
return;
}
hlen = plen - ICMP_EXTD_MINLEN;
if (ND_TTEST2(ext_dp->icmp_ext_version_res, hlen)) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = hlen;
ND_PRINT((ndo, ", checksum 0x%04x (%scorrect), length %u",
EXTRACT_16BITS(ext_dp->icmp_ext_checksum),
in_cksum(vec, 1) ? "in" : "",
hlen));
}
hlen -= 4; /* subtract common header size */
obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data;
while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) {
icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr;
ND_TCHECK(*icmp_mpls_ext_object_header);
obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length);
obj_class_num = icmp_mpls_ext_object_header->class_num;
obj_ctype = icmp_mpls_ext_object_header->ctype;
obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t);
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %u, length %u",
tok2str(icmp_mpls_ext_obj_values,"unknown",obj_class_num),
obj_class_num,
obj_ctype,
obj_tlen));
hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */
/* infinite loop protection */
if ((obj_class_num == 0) ||
(obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) {
return;
}
obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t);
switch (obj_class_num) {
case 1:
switch(obj_ctype) {
case 1:
ND_TCHECK2(*obj_tptr, 4);
raw_label = EXTRACT_32BITS(obj_tptr);
ND_PRINT((ndo, "\n\t label %u, exp %u", MPLS_LABEL(raw_label), MPLS_EXP(raw_label)));
if (MPLS_STACK(raw_label))
ND_PRINT((ndo, ", [S]"));
ND_PRINT((ndo, ", ttl %u", MPLS_TTL(raw_label)));
break;
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
}
break;
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case 2:
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
break;
}
if (hlen < obj_tlen)
break;
hlen -= obj_tlen;
obj_tptr += obj_tlen;
}
}
return;
trunc:
ND_PRINT((ndo, "[|icmp]"));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13012/ICMP: Add a missing bounds check.
Check before fetching the length from the included packet's IPv4 header.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void show_object(struct object *object, struct strbuf *path,
const char *last, void *data)
{
struct bitmap *base = data;
bitmap_set(base, find_object_pos(object->oid.hash));
mark_as_seen(object);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], '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 <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
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);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], '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 <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int credential_from_url_gently(struct credential *c, const char *url,
int quiet)
{
const char *at, *colon, *cp, *slash, *host, *proto_end;
credential_clear(c);
/*
* Match one of:
* (1) proto://<host>/...
* (2) proto://<user>@<host>/...
* (3) proto://<user>:<pass>@<host>/...
*/
proto_end = strstr(url, "://");
if (!proto_end)
return 0;
cp = proto_end + 3;
at = strchr(cp, '@');
colon = strchr(cp, ':');
slash = strchrnul(cp, '/');
if (!at || slash <= at) {
/* Case (1) */
host = cp;
}
else if (!colon || at <= colon) {
/* Case (2) */
c->username = url_decode_mem(cp, at - cp);
host = at + 1;
} else {
/* Case (3) */
c->username = url_decode_mem(cp, colon - cp);
c->password = url_decode_mem(colon + 1, at - (colon + 1));
host = at + 1;
}
if (proto_end - url > 0)
c->protocol = xmemdupz(url, proto_end - url);
c->host = url_decode_mem(host, slash - host);
/* Trim leading and trailing slashes from path */
while (*slash == '/')
slash++;
if (*slash) {
char *p;
c->path = url_decode(slash);
p = c->path + strlen(c->path) - 1;
while (p > c->path && *p == '/')
*p-- = '\0';
}
if (check_url_component(url, quiet, "username", c->username) < 0 ||
check_url_component(url, quiet, "password", c->password) < 0 ||
check_url_component(url, quiet, "protocol", c->protocol) < 0 ||
check_url_component(url, quiet, "host", c->host) < 0 ||
check_url_component(url, quiet, "path", c->path) < 0)
return -1;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-522'], 'message': 'credential: treat URL without scheme as invalid
libcurl permits making requests without a URL scheme specified. In
this case, it guesses the URL from the hostname, so I can run
git ls-remote http::ftp.example.com/path/to/repo
and it would make an FTP request.
Any user intentionally using such a URL is likely to have made a typo.
Unfortunately, credential_from_url is not able to determine the host and
protocol in order to determine appropriate credentials to send, and
until "credential: refuse to operate when missing host or protocol",
this resulted in another host's credentials being leaked to the named
host.
Teach credential_from_url_gently to consider such a URL to be invalid
so that fsck can detect and block gitmodules files with such URLs,
allowing server operators to avoid serving them to downstream users
running older versions of Git.
This also means that when such URLs are passed on the command line, Git
will print a clearer error so affected users can switch to the simpler
URL that explicitly specifies the host and protocol they intend.
One subtlety: .gitmodules files can contain relative URLs, representing
a URL relative to the URL they were cloned from. The relative URL
resolver used for .gitmodules can follow ".." components out of the path
part and past the host part of a URL, meaning that such a relative URL
can be used to traverse from a https://foo.example.com/innocent
superproject to a https::attacker.example.com/exploit submodule.
Fortunately a leading ':' in the first path component after a series of
leading './' and '../' components is unlikely to show up in other
contexts, so we can catch this by detecting that pattern.
Reported-by: Jeff King <peff@peff.net>
Signed-off-by: Jonathan Nieder <jrnieder@gmail.com>
Reviewed-by: Jeff King <peff@peff.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static apr_status_t parse_chunk_size(http_ctx_t *ctx, const char *buffer,
apr_size_t len, int linelimit)
{
apr_size_t i = 0;
while (i < len) {
char c = buffer[i];
ap_xlate_proto_from_ascii(&c, 1);
/* handle CRLF after the chunk */
if (ctx->state == BODY_CHUNK_END) {
if (c == LF) {
ctx->state = BODY_CHUNK;
}
i++;
continue;
}
/* handle start of the chunk */
if (ctx->state == BODY_CHUNK) {
if (!apr_isxdigit(c)) {
/*
* Detect invalid character at beginning. This also works for empty
* chunk size lines.
*/
return APR_EGENERAL;
}
else {
ctx->state = BODY_CHUNK_PART;
}
ctx->remaining = 0;
ctx->chunkbits = sizeof(long) * 8;
ctx->chunk_used = 0;
}
/* handle a chunk part, or a chunk extension */
/*
* In theory, we are supposed to expect CRLF only, but our
* test suite sends LF only. Tolerate a missing CR.
*/
if (c == ';' || c == CR) {
ctx->state = BODY_CHUNK_EXT;
}
else if (c == LF) {
if (ctx->remaining) {
ctx->state = BODY_CHUNK_DATA;
}
else {
ctx->state = BODY_CHUNK_TRAILER;
}
}
else if (ctx->state != BODY_CHUNK_EXT) {
int xvalue = 0;
/* ignore leading zeros */
if (!ctx->remaining && c == '0') {
i++;
continue;
}
if (c >= '0' && c <= '9') {
xvalue = c - '0';
}
else if (c >= 'A' && c <= 'F') {
xvalue = c - 'A' + 0xa;
}
else if (c >= 'a' && c <= 'f') {
xvalue = c - 'a' + 0xa;
}
else {
/* bogus character */
return APR_EGENERAL;
}
ctx->remaining = (ctx->remaining << 4) | xvalue;
ctx->chunkbits -= 4;
if (ctx->chunkbits <= 0 || ctx->remaining < 0) {
/* overflow */
return APR_ENOSPC;
}
}
i++;
}
/* sanity check */
ctx->chunk_used += len;
if (ctx->chunk_used < 0 || ctx->chunk_used > linelimit) {
return APR_ENOSPC;
}
return APR_SUCCESS;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Limit accepted chunk-size to 2^63-1 and be strict about chunk-ext
authorized characters.
Submitted by: Yann Ylavic
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1684513 13f79535-47bb-0310-9956-ffa450edef68'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int l2tp_packet_send(int sock, struct l2tp_packet_t *pack)
{
uint8_t *buf = mempool_alloc(buf_pool);
struct l2tp_avp_t *avp;
struct l2tp_attr_t *attr;
uint8_t *ptr;
int n;
int len = sizeof(pack->hdr);
if (!buf) {
log_emerg("l2tp: out of memory\n");
return -1;
}
memset(buf, 0, L2TP_MAX_PACKET_SIZE);
ptr = buf + sizeof(pack->hdr);
list_for_each_entry(attr, &pack->attrs, entry) {
if (len + sizeof(*avp) + attr->length >= L2TP_MAX_PACKET_SIZE) {
log_error("l2tp: cann't send packet (exceeds maximum size)\n");
mempool_free(buf);
return -1;
}
avp = (struct l2tp_avp_t *)ptr;
avp->type = htons(attr->attr->id);
avp->M = attr->M;
avp->H = attr->H;
avp->length = sizeof(*avp) + attr->length;
*(uint16_t *)ptr = htons(*(uint16_t *)ptr);
if (attr->H)
memcpy(avp->val, attr->val.octets, attr->length);
else
switch (attr->attr->type) {
case ATTR_TYPE_INT16:
*(int16_t *)avp->val = htons(attr->val.int16);
break;
case ATTR_TYPE_INT32:
*(int32_t *)avp->val = htonl(attr->val.int32);
break;
case ATTR_TYPE_INT64:
*(uint64_t *)avp->val = htobe64(attr->val.uint64);
break;
case ATTR_TYPE_STRING:
case ATTR_TYPE_OCTETS:
memcpy(avp->val, attr->val.string, attr->length);
break;
}
ptr += sizeof(*avp) + attr->length;
len += sizeof(*avp) + attr->length;
}
pack->hdr.length = htons(len);
memcpy(buf, &pack->hdr, sizeof(pack->hdr));
n = sendto(sock, buf, ntohs(pack->hdr.length), 0,
&pack->addr, sizeof(pack->addr));
mempool_free(buf);
if (n < 0) {
if (errno == EAGAIN) {
if (conf_verbose)
log_warn("l2tp: buffer overflow (packet lost)\n");
} else {
if (conf_verbose)
log_warn("l2tp: sendto: %s\n", strerror(errno));
return -1;
}
}
if (n != ntohs(pack->hdr.length)) {
if (conf_verbose)
log_warn("l2tp: short write (%i/%i)\n", n, ntohs(pack->hdr.length));
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-125', 'CWE-120'], 'message': 'l2tp: fix RCE through buffer overflow & fix LE/BE compatibility
Unsufficent checks of valid l2tp header & avp length cause possible
RCE through buffer overflow, reported by https://github.com/WinMin
swings & leommxj, Chaitin Security Research Lab. Add missed header
length and avp length validation to fix the issue.
Order of struct bitfields is implementation-defined so current code
doesn't play well with big-endian arch. switch to explicit flag bit
checking/gathering to fix the issue.
RFC 2661 and 3931 requires that length, seqeuence flags must be set
and offset flag must not be set, so avp-premissive can't help in
this cases.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void swoole_serialize_arr(seriaString *buffer, zend_array *zvalue)
{
zval *data;
zend_string *key;
zend_ulong index;
swPoolstr *swStr = NULL;
zend_uchar is_pack = zvalue->u.flags & HASH_FLAG_PACKED;
ZEND_HASH_FOREACH_KEY_VAL(zvalue, index, key, data)
{
SBucketType type = {0};
type.data_type = Z_TYPE_P(data);
//start point
size_t p = buffer->offset;
if (is_pack && zvalue->nNextFreeElement == zvalue->nNumOfElements)
{
type.key_type = KEY_TYPE_INDEX;
type.key_len = 0;
SERIA_SET_ENTRY_TYPE(buffer, type);
}
else
{
//seria key
if (key)
{
type.key_type = KEY_TYPE_STRING;
if ((swStr = swoole_mini_filter_find(key)))
{
type.key_len = 3; //means use same string
SERIA_SET_ENTRY_TYPE(buffer, type);
if (swStr->offset & 4)
{
SERIA_SET_ENTRY_SIZE4(buffer, swStr->offset);
}
else
{
SERIA_SET_ENTRY_SHORT(buffer, swStr->offset);
}
}
else
{
if (key->len <= 0xff)
{
type.key_len = 1;
SERIA_SET_ENTRY_TYPE(buffer, type);
swoole_mini_filter_add(key, buffer->offset, 1);
SERIA_SET_ENTRY_TYPE(buffer, key->len);
swoole_string_cpy(buffer, key->val, key->len);
}
else if (key->len <= 0xffff)
{//if more than this don't need optimize
type.key_len = 2;
SERIA_SET_ENTRY_TYPE(buffer, type);
swoole_mini_filter_add(key, buffer->offset, 2);
SERIA_SET_ENTRY_SHORT(buffer, key->len);
swoole_string_cpy(buffer, key->val, key->len);
}
else
{
type.key_len = 0;
SERIA_SET_ENTRY_TYPE(buffer, type);
swoole_mini_filter_add(key, buffer->offset, 3);
swoole_string_cpy(buffer, key + XtOffsetOf(zend_string, len), sizeof (size_t) + key->len);
}
}
}
else
{
type.key_type = KEY_TYPE_INDEX;
if (index <= 0xff)
{
type.key_len = 1;
SERIA_SET_ENTRY_TYPE(buffer, type);
SERIA_SET_ENTRY_TYPE(buffer, index);
}
else if (index <= 0xffff)
{
type.key_len = 2;
SERIA_SET_ENTRY_TYPE(buffer, type);
SERIA_SET_ENTRY_SHORT(buffer, index);
}
else
{
type.key_len = 3;
SERIA_SET_ENTRY_TYPE(buffer, type);
SERIA_SET_ENTRY_ULONG(buffer, index);
}
}
}
//seria data
try_again:
switch (Z_TYPE_P(data))
{
case IS_STRING:
{
if ((swStr = swoole_mini_filter_find(Z_STR_P(data))))
{
((SBucketType*) (buffer->buffer + p))->data_len = 3; //means use same string
if (swStr->offset & 4)
{
SERIA_SET_ENTRY_SIZE4(buffer, swStr->offset);
}
else
{
SERIA_SET_ENTRY_SHORT(buffer, swStr->offset);
}
}
else
{
if (Z_STRLEN_P(data) <= 0xff)
{
((SBucketType*) (buffer->buffer + p))->data_len = 1;
swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 1);
SERIA_SET_ENTRY_TYPE(buffer, Z_STRLEN_P(data));
swoole_string_cpy(buffer, Z_STRVAL_P(data), Z_STRLEN_P(data));
}
else if (Z_STRLEN_P(data) <= 0xffff)
{
((SBucketType*) (buffer->buffer + p))->data_len = 2;
swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 2);
SERIA_SET_ENTRY_SHORT(buffer, Z_STRLEN_P(data));
swoole_string_cpy(buffer, Z_STRVAL_P(data), Z_STRLEN_P(data));
}
else
{//if more than this don't need optimize
((SBucketType*) (buffer->buffer + p))->data_len = 0;
swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 3);
swoole_string_cpy(buffer, (char*) Z_STR_P(data) + XtOffsetOf(zend_string, len), sizeof (size_t) + Z_STRLEN_P(data));
}
}
break;
}
case IS_LONG:
{
SBucketType* long_type = (SBucketType*) (buffer->buffer + p);
swoole_serialize_long(buffer, data, long_type);
break;
}
case IS_DOUBLE:
swoole_set_zend_value(buffer, &(data->value));
break;
case IS_REFERENCE:
data = Z_REFVAL_P(data);
((SBucketType*) (buffer->buffer + p))->data_type = Z_TYPE_P(data);
goto try_again;
break;
case IS_ARRAY:
{
zend_array *ht = Z_ARRVAL_P(data);
if (GC_IS_RECURSIVE(ht))
{
((SBucketType*) (buffer->buffer + p))->data_type = IS_NULL;//reset type null
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "the array has cycle ref");
}
else
{
seria_array_type(ht, buffer, p, buffer->offset);
if (ZEND_HASH_APPLY_PROTECTION(ht))
{
GC_PROTECT_RECURSION(ht);
swoole_serialize_arr(buffer, ht);
GC_UNPROTECT_RECURSION(ht);
}
else
{
swoole_serialize_arr(buffer, ht);
}
}
break;
}
//object propterty table is this type
case IS_INDIRECT:
data = Z_INDIRECT_P(data);
zend_uchar type = Z_TYPE_P(data);
((SBucketType*) (buffer->buffer + p))->data_type = (type == IS_UNDEF ? IS_NULL : type);
goto try_again;
break;
case IS_OBJECT:
{
/*
* layout
* type | key | namelen | name | bucket len |buckets
*/
((SBucketType*) (buffer->buffer + p))->data_type = IS_UNDEF;
if (ZEND_HASH_APPLY_PROTECTION(Z_OBJPROP_P(data)))
{
GC_PROTECT_RECURSION(Z_OBJPROP_P(data));
swoole_serialize_object(buffer, data, p);
GC_UNPROTECT_RECURSION(Z_OBJPROP_P(data));
}
else
{
swoole_serialize_object(buffer, data, p);
}
break;
}
default://
break;
}
}
ZEND_HASH_FOREACH_END();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-502'], 'message': 'add buffer end check'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MagickExport void RegisterStaticModules(void)
{
size_t
extent;
ssize_t
i;
extent=sizeof(MagickModules)/sizeof(MagickModules[0]);
for (i=0; i < (ssize_t) extent; i++)
{
if (MagickModules[i].registered == MagickFalse)
{
(void) (MagickModules[i].register_module)();
MagickModules[i].registered=MagickTrue;
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-362'], 'message': 'Added missing policy checks in RegisterStaticModules.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int f2fs_read_single_page(struct inode *inode, struct page *page,
unsigned nr_pages,
struct f2fs_map_blocks *map,
struct bio **bio_ret,
sector_t *last_block_in_bio,
bool is_readahead)
{
struct bio *bio = *bio_ret;
const unsigned blkbits = inode->i_blkbits;
const unsigned blocksize = 1 << blkbits;
sector_t block_in_file;
sector_t last_block;
sector_t last_block_in_file;
sector_t block_nr;
int ret = 0;
block_in_file = (sector_t)page->index;
last_block = block_in_file + nr_pages;
last_block_in_file = (i_size_read(inode) + blocksize - 1) >>
blkbits;
if (last_block > last_block_in_file)
last_block = last_block_in_file;
/* just zeroing out page which is beyond EOF */
if (block_in_file >= last_block)
goto zero_out;
/*
* Map blocks using the previous result first.
*/
if ((map->m_flags & F2FS_MAP_MAPPED) &&
block_in_file > map->m_lblk &&
block_in_file < (map->m_lblk + map->m_len))
goto got_it;
/*
* Then do more f2fs_map_blocks() calls until we are
* done with this page.
*/
map->m_lblk = block_in_file;
map->m_len = last_block - block_in_file;
ret = f2fs_map_blocks(inode, map, 0, F2FS_GET_BLOCK_DEFAULT);
if (ret)
goto out;
got_it:
if ((map->m_flags & F2FS_MAP_MAPPED)) {
block_nr = map->m_pblk + block_in_file - map->m_lblk;
SetPageMappedToDisk(page);
if (!PageUptodate(page) && !cleancache_get_page(page)) {
SetPageUptodate(page);
goto confused;
}
if (!f2fs_is_valid_blkaddr(F2FS_I_SB(inode), block_nr,
DATA_GENERIC_ENHANCE_READ)) {
ret = -EFSCORRUPTED;
goto out;
}
} else {
zero_out:
zero_user_segment(page, 0, PAGE_SIZE);
if (!PageUptodate(page))
SetPageUptodate(page);
unlock_page(page);
goto out;
}
/*
* This page will go to BIO. Do we need to send this
* BIO off first?
*/
if (bio && (*last_block_in_bio != block_nr - 1 ||
!__same_bdev(F2FS_I_SB(inode), block_nr, bio))) {
submit_and_realloc:
__submit_bio(F2FS_I_SB(inode), bio, DATA);
bio = NULL;
}
if (bio == NULL) {
bio = f2fs_grab_read_bio(inode, block_nr, nr_pages,
is_readahead ? REQ_RAHEAD : 0);
if (IS_ERR(bio)) {
ret = PTR_ERR(bio);
bio = NULL;
goto out;
}
}
/*
* If the page is under writeback, we need to wait for
* its completion to see the correct decrypted data.
*/
f2fs_wait_on_block_writeback(inode, block_nr);
if (bio_add_page(bio, page, blocksize, 0) < blocksize)
goto submit_and_realloc;
inc_page_count(F2FS_I_SB(inode), F2FS_RD_DATA);
ClearPageError(page);
*last_block_in_bio = block_nr;
goto out;
confused:
if (bio) {
__submit_bio(F2FS_I_SB(inode), bio, DATA);
bio = NULL;
}
unlock_page(page);
out:
*bio_ret = bio;
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'f2fs: support swap file w/ DIO
Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void gf_m2ts_process_pmt(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *pmt, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
u32 info_length, pos, desc_len, evt_type, nb_es,i;
u32 nb_sections;
u32 data_size;
u32 nb_hevc, nb_hevc_temp, nb_shvc, nb_shvc_temp, nb_mhvc, nb_mhvc_temp;
unsigned char *data;
GF_M2TS_Section *section;
GF_Err e = GF_OK;
/*wait for the last section */
if (!(status&GF_M2TS_TABLE_END)) return;
nb_es = 0;
/*skip if already received but no update detected (eg same data) */
if ((status&GF_M2TS_TABLE_REPEAT) && !(status&GF_M2TS_TABLE_UPDATE)) {
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program);
return;
}
if (pmt->sec->demux_restarted) {
pmt->sec->demux_restarted = 0;
return;
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PMT Found or updated\n"));
nb_sections = gf_list_count(sections);
if (nb_sections > 1) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("PMT on multiple sections not supported\n"));
}
section = (GF_M2TS_Section *)gf_list_get(sections, 0);
data = section->data;
data_size = section->data_size;
pmt->program->pcr_pid = ((data[0] & 0x1f) << 8) | data[1];
info_length = ((data[2]&0xf)<<8) | data[3];
if (info_length != 0) {
/* ...Read Descriptors ... */
u8 tag, len;
u32 first_loop_len = 0;
tag = data[4];
len = data[5];
while (info_length > first_loop_len) {
if (tag == GF_M2TS_MPEG4_IOD_DESCRIPTOR) {
u32 size;
GF_BitStream *iod_bs;
iod_bs = gf_bs_new((char *)data+8, len-2, GF_BITSTREAM_READ);
if (pmt->program->pmt_iod) gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod);
e = gf_odf_parse_descriptor(iod_bs , (GF_Descriptor **) &pmt->program->pmt_iod, &size);
gf_bs_del(iod_bs );
if (e==GF_OK) {
/*remember program number for service/program selection*/
if (pmt->program->pmt_iod) pmt->program->pmt_iod->ServiceID = pmt->program->number;
/*if empty IOD (freebox case), discard it and use dynamic declaration of object*/
if (!gf_list_count(pmt->program->pmt_iod->ESDescriptors)) {
gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod);
pmt->program->pmt_iod = NULL;
}
}
} else if (tag == GF_M2TS_METADATA_POINTER_DESCRIPTOR) {
GF_BitStream *metadatapd_bs;
GF_M2TS_MetadataPointerDescriptor *metapd;
metadatapd_bs = gf_bs_new((char *)data+6, len, GF_BITSTREAM_READ);
metapd = gf_m2ts_read_metadata_pointer_descriptor(metadatapd_bs, len);
gf_bs_del(metadatapd_bs);
if (metapd->application_format_identifier == GF_M2TS_META_ID3 &&
metapd->format_identifier == GF_M2TS_META_ID3 &&
metapd->carriage_flag == METADATA_CARRIAGE_SAME_TS) {
/*HLS ID3 Metadata */
pmt->program->metadata_pointer_descriptor = metapd;
} else {
/* don't know what to do with it for now, delete */
gf_m2ts_metadata_pointer_descriptor_del(metapd);
}
} else {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Skipping descriptor (0x%x) and others not supported\n", tag));
}
first_loop_len += 2 + len;
}
}
if (data_size <= 4 + info_length) return;
data += 4 + info_length;
data_size -= 4 + info_length;
pos = 0;
/* count de number of program related PMT received */
for(i=0; i<gf_list_count(ts->programs); i++) {
GF_M2TS_Program *prog = (GF_M2TS_Program *)gf_list_get(ts->programs,i);
if(prog->pmt_pid == pmt->pid) {
break;
}
}
nb_hevc = nb_hevc_temp = nb_shvc = nb_shvc_temp = nb_mhvc = nb_mhvc_temp = 0;
while (pos<data_size) {
GF_M2TS_PES *pes = NULL;
GF_M2TS_SECTION_ES *ses = NULL;
GF_M2TS_ES *es = NULL;
Bool inherit_pcr = 0;
u32 pid, stream_type, reg_desc_format;
if (pos + 5 > data_size) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Broken PMT! size %d but position %d and need at least 5 bytes to declare es\n", data_size, pos));
break;
}
stream_type = data[0];
pid = ((data[1] & 0x1f) << 8) | data[2];
desc_len = ((data[3] & 0xf) << 8) | data[4];
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("stream_type :%d \n",stream_type));
switch (stream_type) {
/* PES */
case GF_M2TS_VIDEO_MPEG1:
case GF_M2TS_VIDEO_MPEG2:
case GF_M2TS_VIDEO_DCII:
case GF_M2TS_VIDEO_MPEG4:
case GF_M2TS_SYSTEMS_MPEG4_PES:
case GF_M2TS_VIDEO_H264:
case GF_M2TS_VIDEO_SVC:
case GF_M2TS_VIDEO_MVCD:
case GF_M2TS_VIDEO_HEVC:
case GF_M2TS_VIDEO_HEVC_MCTS:
case GF_M2TS_VIDEO_HEVC_TEMPORAL:
case GF_M2TS_VIDEO_SHVC:
case GF_M2TS_VIDEO_SHVC_TEMPORAL:
case GF_M2TS_VIDEO_MHVC:
case GF_M2TS_VIDEO_MHVC_TEMPORAL:
inherit_pcr = 1;
case GF_M2TS_AUDIO_MPEG1:
case GF_M2TS_AUDIO_MPEG2:
case GF_M2TS_AUDIO_AAC:
case GF_M2TS_AUDIO_LATM_AAC:
case GF_M2TS_AUDIO_AC3:
case GF_M2TS_AUDIO_DTS:
case GF_M2TS_MHAS_MAIN:
case GF_M2TS_MHAS_AUX:
case GF_M2TS_SUBTITLE_DVB:
case GF_M2TS_METADATA_PES:
GF_SAFEALLOC(pes, GF_M2TS_PES);
if (!pes) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
pes->cc = -1;
pes->flags = GF_M2TS_ES_IS_PES;
if (inherit_pcr)
pes->flags |= GF_M2TS_INHERIT_PCR;
es = (GF_M2TS_ES *)pes;
break;
case GF_M2TS_PRIVATE_DATA:
GF_SAFEALLOC(pes, GF_M2TS_PES);
if (!pes) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
pes->cc = -1;
pes->flags = GF_M2TS_ES_IS_PES;
es = (GF_M2TS_ES *)pes;
break;
/* Sections */
case GF_M2TS_SYSTEMS_MPEG4_SECTIONS:
GF_SAFEALLOC(ses, GF_M2TS_SECTION_ES);
if (!ses) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
es = (GF_M2TS_ES *)ses;
es->flags |= GF_M2TS_ES_IS_SECTION;
/* carriage of ISO_IEC_14496 data in sections */
if (stream_type == GF_M2TS_SYSTEMS_MPEG4_SECTIONS) {
/*MPEG-4 sections need to be fully checked: if one section is lost, this means we lost
one SL packet in the AU so we must wait for the complete section again*/
ses->sec = gf_m2ts_section_filter_new(gf_m2ts_process_mpeg4section, 0);
/*create OD container*/
if (!pmt->program->additional_ods) {
pmt->program->additional_ods = gf_list_new();
ts->has_4on2 = 1;
}
}
break;
case GF_M2TS_13818_6_ANNEX_A:
case GF_M2TS_13818_6_ANNEX_B:
case GF_M2TS_13818_6_ANNEX_C:
case GF_M2TS_13818_6_ANNEX_D:
case GF_M2TS_PRIVATE_SECTION:
case GF_M2TS_QUALITY_SEC:
case GF_M2TS_MORE_SEC:
GF_SAFEALLOC(ses, GF_M2TS_SECTION_ES);
if (!ses) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
es = (GF_M2TS_ES *)ses;
es->flags |= GF_M2TS_ES_IS_SECTION;
es->pid = pid;
es->service_id = pmt->program->number;
if (stream_type == GF_M2TS_PRIVATE_SECTION) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("AIT sections on pid %d\n", pid));
} else if (stream_type == GF_M2TS_QUALITY_SEC) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("Quality metadata sections on pid %d\n", pid));
} else if (stream_type == GF_M2TS_MORE_SEC) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("MORE sections on pid %d\n", pid));
} else {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("stream type DSM CC user private sections on pid %d \n", pid));
}
/* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */
ses->sec = gf_m2ts_section_filter_new(NULL, 1);
//ses->sec->service_id = pmt->program->number;
break;
case GF_M2TS_MPE_SECTIONS:
if (! ts->prefix_present) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("stream type MPE found : pid = %d \n", pid));
#ifdef GPAC_ENABLE_MPE
es = gf_dvb_mpe_section_new();
if (es->flags & GF_M2TS_ES_IS_SECTION) {
/* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */
((GF_M2TS_SECTION_ES*)es)->sec = gf_m2ts_section_filter_new(NULL, 1);
}
#endif
break;
}
default:
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) );
//GF_LOG(/*GF_LOG_WARNING*/GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) );
break;
}
if (es) {
es->stream_type = (stream_type==GF_M2TS_PRIVATE_DATA) ? 0 : stream_type;
es->program = pmt->program;
es->pid = pid;
es->component_tag = -1;
}
pos += 5;
data += 5;
while (desc_len) {
if (pos + 2 > data_size) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Broken PMT descriptor! size %d but position %d and need at least 2 bytes to parse descritpor\n", data_size, pos));
break;
}
u8 tag = data[0];
u32 len = data[1];
if (pos + 2 + len > data_size) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Broken PMT descriptor! size %d, desc size %d but position %d\n", data_size, len, pos));
break;
}
if (es) {
switch (tag) {
case GF_M2TS_ISO_639_LANGUAGE_DESCRIPTOR:
if (pes && (len>=3) )
pes->lang = GF_4CC(' ', data[2], data[3], data[4]);
break;
case GF_M2TS_MPEG4_SL_DESCRIPTOR:
if (len>=2) {
es->mpeg4_es_id = ( (u32) data[2] & 0x1f) << 8 | data[3];
es->flags |= GF_M2TS_ES_IS_SL;
}
break;
case GF_M2TS_REGISTRATION_DESCRIPTOR:
if (len>=4) {
reg_desc_format = GF_4CC(data[2], data[3], data[4], data[5]);
/*cf http://www.smpte-ra.org/mpegreg/mpegreg.html*/
switch (reg_desc_format) {
case GF_M2TS_RA_STREAM_AC3:
es->stream_type = GF_M2TS_AUDIO_AC3;
break;
case GF_M2TS_RA_STREAM_VC1:
es->stream_type = GF_M2TS_VIDEO_VC1;
break;
case GF_M2TS_RA_STREAM_GPAC:
if (len==8) {
es->stream_type = GF_4CC(data[6], data[7], data[8], data[9]);
es->flags |= GF_M2TS_GPAC_CODEC_ID;
break;
}
default:
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("Unknown registration descriptor %s\n", gf_4cc_to_str(reg_desc_format) ));
break;
}
}
break;
case GF_M2TS_DVB_EAC3_DESCRIPTOR:
es->stream_type = GF_M2TS_AUDIO_EC3;
break;
case GF_M2TS_DVB_DATA_BROADCAST_ID_DESCRIPTOR:
if (len>=2) {
u32 id = data[2]<<8 | data[3];
if ((id == 0xB) && ses && !ses->sec) {
ses->sec = gf_m2ts_section_filter_new(NULL, 1);
}
}
break;
case GF_M2TS_DVB_SUBTITLING_DESCRIPTOR:
if (pes && (len>=8)) {
pes->sub.language[0] = data[2];
pes->sub.language[1] = data[3];
pes->sub.language[2] = data[4];
pes->sub.type = data[5];
pes->sub.composition_page_id = (data[6]<<8) | data[7];
pes->sub.ancillary_page_id = (data[8]<<8) | data[9];
}
es->stream_type = GF_M2TS_DVB_SUBTITLE;
break;
case GF_M2TS_DVB_STREAM_IDENTIFIER_DESCRIPTOR:
if (len>=1) {
es->component_tag = data[2];
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("Component Tag: %d on Program %d\n", es->component_tag, es->program->number));
}
break;
case GF_M2TS_DVB_TELETEXT_DESCRIPTOR:
es->stream_type = GF_M2TS_DVB_TELETEXT;
break;
case GF_M2TS_DVB_VBI_DATA_DESCRIPTOR:
es->stream_type = GF_M2TS_DVB_VBI;
break;
case GF_M2TS_HIERARCHY_DESCRIPTOR:
if (pes && (len>=4)) {
u8 hierarchy_embedded_layer_index;
GF_BitStream *hbs = gf_bs_new((const char *)data, data_size, GF_BITSTREAM_READ);
/*u32 skip = */gf_bs_read_int(hbs, 16);
/*u8 res1 = */gf_bs_read_int(hbs, 1);
/*u8 temp_scal = */gf_bs_read_int(hbs, 1);
/*u8 spatial_scal = */gf_bs_read_int(hbs, 1);
/*u8 quality_scal = */gf_bs_read_int(hbs, 1);
/*u8 hierarchy_type = */gf_bs_read_int(hbs, 4);
/*u8 res2 = */gf_bs_read_int(hbs, 2);
/*u8 hierarchy_layer_index = */gf_bs_read_int(hbs, 6);
/*u8 tref_not_present = */gf_bs_read_int(hbs, 1);
/*u8 res3 = */gf_bs_read_int(hbs, 1);
hierarchy_embedded_layer_index = gf_bs_read_int(hbs, 6);
/*u8 res4 = */gf_bs_read_int(hbs, 2);
/*u8 hierarchy_channel = */gf_bs_read_int(hbs, 6);
gf_bs_del(hbs);
pes->depends_on_pid = 1+hierarchy_embedded_layer_index;
}
break;
case GF_M2TS_METADATA_DESCRIPTOR:
{
GF_BitStream *metadatad_bs;
GF_M2TS_MetadataDescriptor *metad;
metadatad_bs = gf_bs_new((char *)data+2, len, GF_BITSTREAM_READ);
metad = gf_m2ts_read_metadata_descriptor(metadatad_bs, len);
gf_bs_del(metadatad_bs);
if (metad->application_format_identifier == GF_M2TS_META_ID3 &&
metad->format_identifier == GF_M2TS_META_ID3) {
/*HLS ID3 Metadata */
if (pes) {
pes->metadata_descriptor = metad;
pes->stream_type = GF_M2TS_METADATA_ID3_HLS;
}
} else {
/* don't know what to do with it for now, delete */
gf_m2ts_metadata_descriptor_del(metad);
}
}
break;
default:
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] skipping descriptor (0x%x) not supported\n", tag));
break;
}
}
data += len+2;
pos += len+2;
if (desc_len < len+2) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Invalid PMT es descriptor size for PID %d\n", pid ) );
break;
}
desc_len-=len+2;
}
if (es && !es->stream_type) {
gf_free(es);
es = NULL;
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Private Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) );
}
if (!es) continue;
if (ts->ess[pid]) {
//this is component reuse across programs, overwrite the previously declared stream ...
if (status & GF_M2TS_TABLE_FOUND) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d reused across programs %d and %d, not completely supported\n", pid, ts->ess[pid]->program->number, es->program->number ) );
//add stream to program but don't reassign the pid table until the stream is playing (>GF_M2TS_PES_FRAMING_SKIP)
gf_list_add(pmt->program->streams, es);
if (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP);
nb_es++;
//skip assignment below
es = NULL;
}
/*watchout for pmt update - FIXME this likely won't work in most cases*/
else {
GF_M2TS_ES *o_es = ts->ess[es->pid];
if ((o_es->stream_type == es->stream_type)
&& ((o_es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK) == (es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK))
&& (o_es->mpeg4_es_id == es->mpeg4_es_id)
&& ((o_es->flags & GF_M2TS_ES_IS_SECTION) || ((GF_M2TS_PES *)o_es)->lang == ((GF_M2TS_PES *)es)->lang)
) {
gf_free(es);
es = NULL;
} else {
gf_m2ts_es_del(o_es, ts);
ts->ess[es->pid] = NULL;
}
}
}
if (es) {
ts->ess[es->pid] = es;
gf_list_add(pmt->program->streams, es);
if (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP);
nb_es++;
if (es->stream_type == GF_M2TS_VIDEO_HEVC) nb_hevc++;
else if (es->stream_type == GF_M2TS_VIDEO_HEVC_TEMPORAL) nb_hevc_temp++;
else if (es->stream_type == GF_M2TS_VIDEO_SHVC) nb_shvc++;
else if (es->stream_type == GF_M2TS_VIDEO_SHVC_TEMPORAL) nb_shvc_temp++;
else if (es->stream_type == GF_M2TS_VIDEO_MHVC) nb_mhvc++;
else if (es->stream_type == GF_M2TS_VIDEO_MHVC_TEMPORAL) nb_mhvc_temp++;
}
}
//Table 2-139, implied hierarchy indexes
if (nb_hevc_temp + nb_shvc + nb_shvc_temp + nb_mhvc+ nb_mhvc_temp) {
for (i=0; i<gf_list_count(pmt->program->streams); i++) {
GF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i);
if ( !(es->flags & GF_M2TS_ES_IS_PES)) continue;
if (es->depends_on_pid) continue;
switch (es->stream_type) {
case GF_M2TS_VIDEO_HEVC_TEMPORAL:
es->depends_on_pid = 1;
break;
case GF_M2TS_VIDEO_SHVC:
if (!nb_hevc_temp) es->depends_on_pid = 1;
else es->depends_on_pid = 2;
break;
case GF_M2TS_VIDEO_SHVC_TEMPORAL:
es->depends_on_pid = 3;
break;
case GF_M2TS_VIDEO_MHVC:
if (!nb_hevc_temp) es->depends_on_pid = 1;
else es->depends_on_pid = 2;
break;
case GF_M2TS_VIDEO_MHVC_TEMPORAL:
if (!nb_hevc_temp) es->depends_on_pid = 2;
else es->depends_on_pid = 3;
break;
}
}
}
if (nb_es) {
u32 i;
//translate hierarchy descriptors indexes into PIDs - check whether the PMT-index rules are the same for HEVC
for (i=0; i<gf_list_count(pmt->program->streams); i++) {
GF_M2TS_PES *an_es = NULL;
GF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i);
if ( !(es->flags & GF_M2TS_ES_IS_PES)) continue;
if (!es->depends_on_pid) continue;
//fixeme we are not always assured that hierarchy_layer_index matches the stream index...
//+1 is because our first stream is the PMT
an_es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, es->depends_on_pid);
if (an_es) {
es->depends_on_pid = an_es->pid;
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[M2TS] Wrong dependency index in hierarchy descriptor, assuming non-scalable stream\n"));
es->depends_on_pid = 0;
}
}
evt_type = (status&GF_M2TS_TABLE_FOUND) ? GF_M2TS_EVT_PMT_FOUND : GF_M2TS_EVT_PMT_UPDATE;
if (ts->on_event) ts->on_event(ts, evt_type, pmt->program);
} else {
/* if we found no new ES it's simply a repeat of the PMT */
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-125'], 'message': 'fixed potential crash on PMT IOD parse - cf #1268 #1269'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: l2tp_result_code_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
const uint16_t *ptr = (const uint16_t *)dat;
ND_PRINT((ndo, "%u", EXTRACT_16BITS(ptr))); ptr++; /* Result Code */
if (length > 2) { /* Error Code (opt) */
ND_PRINT((ndo, "/%u", EXTRACT_16BITS(ptr))); ptr++;
}
if (length > 4) { /* Error Message (opt) */
ND_PRINT((ndo, " "));
print_string(ndo, (const u_char *)ptr, length - 4);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length.
It's not good enough to check whether all the data specified by the AVP
length was captured - you also have to check whether that length is
large enough for all the required data in the AVP.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteIntArray* TfLiteIntArrayCreate(int size) {
TfLiteIntArray* ret =
(TfLiteIntArray*)malloc(TfLiteIntArrayGetSizeInBytes(size));
ret->size = size;
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'Fix a dangerous integer overflow and a malloc of negative size.
PiperOrigin-RevId: 371254154
Change-Id: I250a98a3df26328770167025670235a963a72da0'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool Router::MatchView(const std::string& method, const std::string& url,
bool* stream) {
assert(stream != nullptr);
*stream = false;
for (auto& route : routes_) {
if (std::find(route.methods.begin(), route.methods.end(), method) ==
route.methods.end()) {
continue;
}
if (route.url.empty()) {
std::smatch match;
if (std::regex_match(url, match, route.url_regex)) {
*stream = route.view->Stream(method);
return true;
}
} else {
if (boost::iequals(route.url, url)) {
*stream = route.view->Stream(method);
return true;
}
}
}
return false;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-22'], 'message': 'fix static file serving security issue; fix url path encoding issue'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static GSList *caps_to_list(uint8_t *data, int size,
struct avdtp_service_capability **codec,
gboolean *delay_reporting)
{
GSList *caps;
int processed;
if (delay_reporting)
*delay_reporting = FALSE;
for (processed = 0, caps = NULL; processed + 2 <= size;) {
struct avdtp_service_capability *cap;
uint8_t length, category;
category = data[0];
length = data[1];
if (processed + 2 + length > size) {
error("Invalid capability data in getcap resp");
break;
}
cap = g_malloc(sizeof(struct avdtp_service_capability) +
length);
memcpy(cap, data, 2 + length);
processed += 2 + length;
data += 2 + length;
caps = g_slist_append(caps, cap);
if (category == AVDTP_MEDIA_CODEC &&
length >=
sizeof(struct avdtp_media_codec_capability))
*codec = cap;
else if (category == AVDTP_DELAY_REPORTING && delay_reporting)
*delay_reporting = TRUE;
}
return caps;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'avdtp: Fix accepting invalid/malformed capabilities
Check if capabilities are valid before attempting to copy them.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: process_plane(uint8 * in, int width, int height, uint8 * out, int size)
{
UNUSED(size);
int indexw;
int indexh;
int code;
int collen;
int replen;
int color;
int x;
int revcode;
uint8 * last_line;
uint8 * this_line;
uint8 * org_in;
uint8 * org_out;
org_in = in;
org_out = out;
last_line = 0;
indexh = 0;
while (indexh < height)
{
out = (org_out + width * height * 4) - ((indexh + 1) * width * 4);
color = 0;
this_line = out;
indexw = 0;
if (last_line == 0)
{
while (indexw < width)
{
code = CVAL(in);
replen = code & 0xf;
collen = (code >> 4) & 0xf;
revcode = (replen << 4) | collen;
if ((revcode <= 47) && (revcode >= 16))
{
replen = revcode;
collen = 0;
}
while (collen > 0)
{
color = CVAL(in);
*out = color;
out += 4;
indexw++;
collen--;
}
while (replen > 0)
{
*out = color;
out += 4;
indexw++;
replen--;
}
}
}
else
{
while (indexw < width)
{
code = CVAL(in);
replen = code & 0xf;
collen = (code >> 4) & 0xf;
revcode = (replen << 4) | collen;
if ((revcode <= 47) && (revcode >= 16))
{
replen = revcode;
collen = 0;
}
while (collen > 0)
{
x = CVAL(in);
if (x & 1)
{
x = x >> 1;
x = x + 1;
color = -x;
}
else
{
x = x >> 1;
color = x;
}
x = last_line[indexw * 4] + color;
*out = x;
out += 4;
indexw++;
collen--;
}
while (replen > 0)
{
x = last_line[indexw * 4] + color;
*out = x;
out += 4;
indexw++;
replen--;
}
}
}
indexh++;
last_line = this_line;
}
return (int) (in - org_in);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-125', 'CWE-703', 'CWE-787'], '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'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ikev2_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
const struct ikev2_n *p;
struct ikev2_n n;
const u_char *cp;
u_char showspi, showdata, showsomedata;
const char *notify_name;
uint32_t type;
p = (const struct ikev2_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical);
showspi = 1;
showdata = 0;
showsomedata=0;
notify_name=NULL;
ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id)));
type = ntohs(n.type);
/* notify space is annoying sparse */
switch(type) {
case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD:
notify_name = "unsupported_critical_payload";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_IKE_SPI:
notify_name = "invalid_ike_spi";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_MAJOR_VERSION:
notify_name = "invalid_major_version";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_SYNTAX:
notify_name = "invalid_syntax";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_MESSAGE_ID:
notify_name = "invalid_message_id";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_SPI:
notify_name = "invalid_spi";
showspi = 1;
break;
case IV2_NOTIFY_NO_PROPOSAL_CHOSEN:
notify_name = "no_protocol_chosen";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_KE_PAYLOAD:
notify_name = "invalid_ke_payload";
showspi = 1;
break;
case IV2_NOTIFY_AUTHENTICATION_FAILED:
notify_name = "authentication_failed";
showspi = 1;
break;
case IV2_NOTIFY_SINGLE_PAIR_REQUIRED:
notify_name = "single_pair_required";
showspi = 1;
break;
case IV2_NOTIFY_NO_ADDITIONAL_SAS:
notify_name = "no_additional_sas";
showspi = 0;
break;
case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE:
notify_name = "internal_address_failure";
showspi = 0;
break;
case IV2_NOTIFY_FAILED_CP_REQUIRED:
notify_name = "failed:cp_required";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_SELECTORS:
notify_name = "invalid_selectors";
showspi = 0;
break;
case IV2_NOTIFY_INITIAL_CONTACT:
notify_name = "initial_contact";
showspi = 0;
break;
case IV2_NOTIFY_SET_WINDOW_SIZE:
notify_name = "set_window_size";
showspi = 0;
break;
case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE:
notify_name = "additional_ts_possible";
showspi = 0;
break;
case IV2_NOTIFY_IPCOMP_SUPPORTED:
notify_name = "ipcomp_supported";
showspi = 0;
break;
case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP:
notify_name = "nat_detection_source_ip";
showspi = 1;
break;
case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP:
notify_name = "nat_detection_destination_ip";
showspi = 1;
break;
case IV2_NOTIFY_COOKIE:
notify_name = "cookie";
showspi = 1;
showsomedata= 1;
showdata= 0;
break;
case IV2_NOTIFY_USE_TRANSPORT_MODE:
notify_name = "use_transport_mode";
showspi = 0;
break;
case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED:
notify_name = "http_cert_lookup_supported";
showspi = 0;
break;
case IV2_NOTIFY_REKEY_SA:
notify_name = "rekey_sa";
showspi = 1;
break;
case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED:
notify_name = "tfc_padding_not_supported";
showspi = 0;
break;
case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO:
notify_name = "non_first_fragment_also";
showspi = 0;
break;
default:
if (type < 8192) {
notify_name="error";
} else if(type < 16384) {
notify_name="private-error";
} else if(type < 40960) {
notify_name="status";
} else {
notify_name="private-status";
}
}
if(notify_name) {
ND_PRINT((ndo," type=%u(%s)", type, notify_name));
}
if (showspi && n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
if(3 < ndo->ndo_vflag) {
showdata = 1;
}
if ((showdata || (showsomedata && ep-cp < 30)) && cp < ep) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else if(showsomedata && cp < ep) {
if(!ike_show_somedata(ndo, cp, ep)) goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-835'], 'message': 'CVE-2017-12990/Fix printing of ISAKMPv1 Notification payload data.
The closest thing to a specification for the contents of the payload
data is draft-ietf-ipsec-notifymsg-04, and nothing in there says that it
is ever a complete ISAKMP message, so don't dissect types we don't have
specific code for as a complete ISAKMP message.
While we're at it, fix a comment, and clean up printing of V1 Nonce,
V2 Authentication payloads, and v2 Notice payloads.
This fixes an infinite loop discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void Compute(OpKernelContext* context) override {
const Tensor& indices = context->input(0);
const Tensor& values = context->input(1);
const Tensor& shape = context->input(2);
const Tensor& weights = context->input(3);
bool use_weights = weights.NumElements() > 0;
OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices.shape()),
errors::InvalidArgument(
"Input indices must be a 2-dimensional tensor. Got: ",
indices.shape().DebugString()));
if (use_weights) {
OP_REQUIRES(
context, weights.shape() == values.shape(),
errors::InvalidArgument(
"Weights and values must have the same shape. Weight shape: ",
weights.shape().DebugString(),
"; values shape: ", values.shape().DebugString()));
}
OP_REQUIRES(context, shape.NumElements() != 0,
errors::InvalidArgument(
"The shape argument requires at least one element."));
bool is_1d = shape.NumElements() == 1;
int num_batches = is_1d ? 1 : shape.flat<int64>()(0);
int num_values = values.NumElements();
OP_REQUIRES(context, num_values == indices.shape().dim_size(0),
errors::InvalidArgument(
"Number of values must match first dimension of indices.",
"Got ", num_values,
" values, indices shape: ", indices.shape().DebugString()));
const auto indices_values = indices.matrix<int64>();
const auto values_values = values.flat<T>();
const auto weight_values = weights.flat<W>();
auto per_batch_counts = BatchedMap<W>(num_batches);
T max_value = 0;
for (int idx = 0; idx < num_values; ++idx) {
int batch = is_1d ? 0 : indices_values(idx, 0);
if (batch >= num_batches) {
OP_REQUIRES(context, batch < num_batches,
errors::InvalidArgument(
"Indices value along the first dimension must be ",
"lower than the first index of the shape.", "Got ",
batch, " as batch and ", num_batches,
" as the first dimension of the shape."));
}
const auto& value = values_values(idx);
if (value >= 0 && (maxlength_ <= 0 || value < maxlength_)) {
if (binary_output_) {
per_batch_counts[batch][value] = 1;
} else if (use_weights) {
per_batch_counts[batch][value] += weight_values(idx);
} else {
per_batch_counts[batch][value]++;
}
if (value > max_value) {
max_value = value;
}
}
}
int num_output_values = GetOutputSize(max_value, maxlength_, minlength_);
OP_REQUIRES_OK(context, OutputSparse<W>(per_batch_counts, num_output_values,
is_1d, context));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-131'], 'message': 'Fix the segfault in `tf.raw_ops.SparseCountSparseOutput`.
PiperOrigin-RevId: 369264941
Change-Id: I23a96a15b8370c01ee21ba3841e1c7dcbf55e93d'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int crypto_rng_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_rng rrng;
snprintf(rrng.type, CRYPTO_MAX_ALG_NAME, "%s", "rng");
rrng.seedsize = alg->cra_rng.seedsize;
if (nla_put(skb, CRYPTOCFGA_REPORT_RNG,
sizeof(struct crypto_report_rng), &rrng))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'crypto: user - fix info leaks in report API
Three errors resulting in kernel memory disclosure:
1/ The structures used for the netlink based crypto algorithm report API
are located on the stack. As snprintf() does not fill the remainder of
the buffer with null bytes, those stack bytes will be disclosed to users
of the API. Switch to strncpy() to fix this.
2/ crypto_report_one() does not initialize all field of struct
crypto_user_alg. Fix this to fix the heap info leak.
3/ For the module name we should copy only as many bytes as
module_name() returns -- not as much as the destination buffer could
hold. But the current code does not and therefore copies random data
from behind the end of the module name, as the module name is always
shorter than CRYPTO_MAX_ALG_NAME.
Also switch to use strncpy() to copy the algorithm's name and
driver_name. They are strings, after all.
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Cc: Steffen Klassert <steffen.klassert@secunet.com>
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int crypto_ahash_report(struct sk_buff *skb, struct crypto_alg *alg)
{
return -ENOSYS;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'crypto: user - fix info leaks in report API
Three errors resulting in kernel memory disclosure:
1/ The structures used for the netlink based crypto algorithm report API
are located on the stack. As snprintf() does not fill the remainder of
the buffer with null bytes, those stack bytes will be disclosed to users
of the API. Switch to strncpy() to fix this.
2/ crypto_report_one() does not initialize all field of struct
crypto_user_alg. Fix this to fix the heap info leak.
3/ For the module name we should copy only as many bytes as
module_name() returns -- not as much as the destination buffer could
hold. But the current code does not and therefore copies random data
from behind the end of the module name, as the module name is always
shorter than CRYPTO_MAX_ALG_NAME.
Also switch to use strncpy() to copy the algorithm's name and
driver_name. They are strings, after all.
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Cc: Steffen Klassert <steffen.klassert@secunet.com>
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: enum_func_status
php_mysqlnd_rowp_read_text_protocol_aux(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zval ** fields,
unsigned int field_count, const MYSQLND_FIELD * fields_metadata,
zend_bool as_int_or_float, zend_bool copy_data, MYSQLND_STATS * stats TSRMLS_DC)
{
unsigned int i;
zend_bool last_field_was_string = FALSE;
zval **current_field, **end_field, **start_field;
zend_uchar * p = row_buffer->ptr;
size_t data_size = row_buffer->app;
zend_uchar * bit_area = (zend_uchar*) row_buffer->ptr + data_size + 1; /* we allocate from here */
DBG_ENTER("php_mysqlnd_rowp_read_text_protocol_aux");
if (!fields) {
DBG_RETURN(FAIL);
}
end_field = (start_field = fields) + field_count;
for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) {
DBG_INF("Directly creating zval");
MAKE_STD_ZVAL(*current_field);
if (!*current_field) {
DBG_RETURN(FAIL);
}
}
for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) {
/* Don't reverse the order. It is significant!*/
zend_uchar *this_field_len_pos = p;
/* php_mysqlnd_net_field_length() call should be after *this_field_len_pos = p; */
unsigned long len = php_mysqlnd_net_field_length(&p);
if (copy_data == FALSE && current_field > start_field && last_field_was_string) {
/*
Normal queries:
We have to put \0 now to the end of the previous field, if it was
a string. IS_NULL doesn't matter. Because we have already read our
length, then we can overwrite it in the row buffer.
This statement terminates the previous field, not the current one.
NULL_LENGTH is encoded in one byte, so we can stick a \0 there.
Any string's length is encoded in at least one byte, so we can stick
a \0 there.
*/
*this_field_len_pos = '\0';
}
/* NULL or NOT NULL, this is the question! */
if (len == MYSQLND_NULL_LENGTH) {
ZVAL_NULL(*current_field);
last_field_was_string = FALSE;
} else {
#if defined(MYSQLND_STRING_TO_INT_CONVERSION)
struct st_mysqlnd_perm_bind perm_bind =
mysqlnd_ps_fetch_functions[fields_metadata[i].type];
#endif
if (MYSQLND_G(collect_statistics)) {
enum_mysqlnd_collected_stats statistic;
switch (fields_metadata[i].type) {
case MYSQL_TYPE_DECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break;
case MYSQL_TYPE_TINY: statistic = STAT_TEXT_TYPE_FETCHED_INT8; break;
case MYSQL_TYPE_SHORT: statistic = STAT_TEXT_TYPE_FETCHED_INT16; break;
case MYSQL_TYPE_LONG: statistic = STAT_TEXT_TYPE_FETCHED_INT32; break;
case MYSQL_TYPE_FLOAT: statistic = STAT_TEXT_TYPE_FETCHED_FLOAT; break;
case MYSQL_TYPE_DOUBLE: statistic = STAT_TEXT_TYPE_FETCHED_DOUBLE; break;
case MYSQL_TYPE_NULL: statistic = STAT_TEXT_TYPE_FETCHED_NULL; break;
case MYSQL_TYPE_TIMESTAMP: statistic = STAT_TEXT_TYPE_FETCHED_TIMESTAMP; break;
case MYSQL_TYPE_LONGLONG: statistic = STAT_TEXT_TYPE_FETCHED_INT64; break;
case MYSQL_TYPE_INT24: statistic = STAT_TEXT_TYPE_FETCHED_INT24; break;
case MYSQL_TYPE_DATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break;
case MYSQL_TYPE_TIME: statistic = STAT_TEXT_TYPE_FETCHED_TIME; break;
case MYSQL_TYPE_DATETIME: statistic = STAT_TEXT_TYPE_FETCHED_DATETIME; break;
case MYSQL_TYPE_YEAR: statistic = STAT_TEXT_TYPE_FETCHED_YEAR; break;
case MYSQL_TYPE_NEWDATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break;
case MYSQL_TYPE_VARCHAR: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break;
case MYSQL_TYPE_BIT: statistic = STAT_TEXT_TYPE_FETCHED_BIT; break;
case MYSQL_TYPE_NEWDECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break;
case MYSQL_TYPE_ENUM: statistic = STAT_TEXT_TYPE_FETCHED_ENUM; break;
case MYSQL_TYPE_SET: statistic = STAT_TEXT_TYPE_FETCHED_SET; break;
case MYSQL_TYPE_JSON: statistic = STAT_TEXT_TYPE_FETCHED_JSON; break;
case MYSQL_TYPE_TINY_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;
case MYSQL_TYPE_MEDIUM_BLOB:statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;
case MYSQL_TYPE_LONG_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;
case MYSQL_TYPE_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;
case MYSQL_TYPE_VAR_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break;
case MYSQL_TYPE_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break;
case MYSQL_TYPE_GEOMETRY: statistic = STAT_TEXT_TYPE_FETCHED_GEOMETRY; break;
default: statistic = STAT_TEXT_TYPE_FETCHED_OTHER; break;
}
MYSQLND_INC_CONN_STATISTIC_W_VALUE2(stats, statistic, 1, STAT_BYTES_RECEIVED_PURE_DATA_TEXT, len);
}
#ifdef MYSQLND_STRING_TO_INT_CONVERSION
if (as_int_or_float && perm_bind.php_type == IS_LONG) {
zend_uchar save = *(p + len);
/* We have to make it ASCIIZ temporarily */
*(p + len) = '\0';
if (perm_bind.pack_len < SIZEOF_LONG) {
/* direct conversion */
int64_t v =
#ifndef PHP_WIN32
atoll((char *) p);
#else
_atoi64((char *) p);
#endif
ZVAL_LONG(*current_field, (long) v); /* the cast is safe */
} else {
uint64_t v =
#ifndef PHP_WIN32
(uint64_t) atoll((char *) p);
#else
(uint64_t) _atoi64((char *) p);
#endif
zend_bool uns = fields_metadata[i].flags & UNSIGNED_FLAG? TRUE:FALSE;
/* We have to make it ASCIIZ temporarily */
#if SIZEOF_LONG==8
if (uns == TRUE && v > 9223372036854775807L)
#elif SIZEOF_LONG==4
if ((uns == TRUE && v > L64(2147483647)) ||
(uns == FALSE && (( L64(2147483647) < (int64_t) v) ||
(L64(-2147483648) > (int64_t) v))))
#else
#error Need fix for this architecture
#endif /* SIZEOF */
{
ZVAL_STRINGL(*current_field, (char *)p, len, 0);
} else {
ZVAL_LONG(*current_field, (long) v); /* the cast is safe */
}
}
*(p + len) = save;
} else if (as_int_or_float && perm_bind.php_type == IS_DOUBLE) {
zend_uchar save = *(p + len);
/* We have to make it ASCIIZ temporarily */
*(p + len) = '\0';
ZVAL_DOUBLE(*current_field, atof((char *) p));
*(p + len) = save;
} else
#endif /* MYSQLND_STRING_TO_INT_CONVERSION */
if (fields_metadata[i].type == MYSQL_TYPE_BIT) {
/*
BIT fields are specially handled. As they come as bit mask, we have
to convert it to human-readable representation. As the bits take
less space in the protocol than the numbers they represent, we don't
have enough space in the packet buffer to overwrite inside.
Thus, a bit more space is pre-allocated at the end of the buffer,
see php_mysqlnd_rowp_read(). And we add the strings at the end.
Definitely not nice, _hackish_ :(, but works.
*/
zend_uchar *start = bit_area;
ps_fetch_from_1_to_8_bytes(*current_field, &(fields_metadata[i]), 0, &p, len TSRMLS_CC);
/*
We have advanced in ps_fetch_from_1_to_8_bytes. We should go back because
later in this function there will be an advancement.
*/
p -= len;
if (Z_TYPE_PP(current_field) == IS_LONG) {
bit_area += 1 + sprintf((char *)start, "%ld", Z_LVAL_PP(current_field));
ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data);
} else if (Z_TYPE_PP(current_field) == IS_STRING){
memcpy(bit_area, Z_STRVAL_PP(current_field), Z_STRLEN_PP(current_field));
bit_area += Z_STRLEN_PP(current_field);
*bit_area++ = '\0';
zval_dtor(*current_field);
ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data);
}
} else {
ZVAL_STRINGL(*current_field, (char *)p, len, copy_data);
}
p += len;
last_field_was_string = TRUE;
}
}
if (copy_data == FALSE && last_field_was_string) {
/* Normal queries: The buffer has one more byte at the end, because we need it */
row_buffer->ptr[data_size] = '\0';
}
DBG_RETURN(PASS); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #72293 - Heap overflow in mysqlnd related to BIT fields'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static ssize_t aio_setup_single_vector(struct kiocb *kiocb)
{
kiocb->ki_iovec = &kiocb->ki_inline_vec;
kiocb->ki_iovec->iov_base = kiocb->ki_buf;
kiocb->ki_iovec->iov_len = kiocb->ki_left;
kiocb->ki_nr_segs = 1;
kiocb->ki_cur_seg = 0;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'vfs: make AIO use the proper rw_verify_area() area helpers
We had for some reason overlooked the AIO interface, and it didn't use
the proper rw_verify_area() helper function that checks (for example)
mandatory locking on the file, and that the size of the access doesn't
cause us to overflow the provided offset limits etc.
Instead, AIO did just the security_file_permission() thing (that
rw_verify_area() also does) directly.
This fixes it to do all the proper helper functions, which not only
means that now mandatory file locking works with AIO too, we can
actually remove lines of code.
Reported-by: Manish Honap <manish_honap_vit@yahoo.co.in>
Cc: stable@vger.kernel.org
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: char* _multi_string_alloc_and_copy( LPCWSTR in )
{
char *chr;
int len = 0;
if ( !in )
{
return in;
}
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
len ++;
}
chr = malloc( len + 2 );
len = 0;
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
chr[ len ] = 0xFF & in[ len ];
len ++;
}
chr[ len ++ ] = '\0';
chr[ len ++ ] = '\0';
return chr;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-369'], 'message': 'New Pre Source'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code:
GF_Err trak_box_size(GF_Box *s)
{
u32 pos=0;
GF_TrackBox *ptr = (GF_TrackBox *)s;
if (ptr->sample_encryption && ptr->sample_encryption->load_needed) {
GF_Err e = senc_Parse(ptr->moov->mov->movieFileMap->bs, ptr, NULL, ptr->sample_encryption);
if (e) return e;
}
gf_isom_check_position(s, (GF_Box *)ptr->Header, &pos);
gf_isom_check_position(s, (GF_Box *)ptr->Aperture, &pos);
gf_isom_check_position(s, (GF_Box *)ptr->References, &pos);
gf_isom_check_position(s, (GF_Box *)ptr->editBox, &pos);
gf_isom_check_position(s, (GF_Box *)ptr->Media, &pos);
gf_isom_check_position(s, (GF_Box *)ptr->meta, &pos);
gf_isom_check_position(s, (GF_Box *)ptr->groups, &pos);
gf_isom_check_position(s, (GF_Box *)ptr->udta, &pos);
return GF_OK; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476', 'CWE-787'], 'message': 'fixed #1757'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MONGO_EXPORT int bson_append_element( bson *b, const char *name_or_null, const bson_iterator *elem ) {
bson_iterator next = *elem;
int size;
bson_iterator_next( &next );
size = next.cur - elem->cur;
if ( name_or_null == NULL ) {
if( bson_ensure_space( b, size ) == BSON_ERROR )
return BSON_ERROR;
bson_append( b, elem->cur, size );
}
else {
int data_size = size - 2 - strlen( bson_iterator_key( elem ) );
bson_append_estart( b, elem->cur[0], name_or_null, data_size );
bson_append( b, bson_iterator_value( elem ), data_size );
}
return BSON_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'don't mix up int and size_t (first pass to fix that)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MONGO_EXPORT int bson_append_binary( bson *b, const char *name, char type, const char *str, int len ) {
if ( type == BSON_BIN_BINARY_OLD ) {
int subtwolen = len + 4;
if ( bson_append_estart( b, BSON_BINDATA, name, 4+1+4+len ) == BSON_ERROR )
return BSON_ERROR;
bson_append32( b, &subtwolen );
bson_append_byte( b, type );
bson_append32( b, &len );
bson_append( b, str, len );
}
else {
if ( bson_append_estart( b, BSON_BINDATA, name, 4+1+len ) == BSON_ERROR )
return BSON_ERROR;
bson_append32( b, &len );
bson_append_byte( b, type );
bson_append( b, str, len );
}
return BSON_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'don't mix up int and size_t (first pass to fix that)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MONGO_EXPORT int mongo_run_command( mongo *conn, const char *db, const bson *command,
bson *out ) {
int ret = MONGO_OK;
bson response = {NULL, 0};
bson fields;
int sl = strlen( db );
char *ns = bson_malloc( sl + 5 + 1 ); /* ".$cmd" + nul */
int res, success = 0;
strcpy( ns, db );
strcpy( ns+sl, ".$cmd" );
res = mongo_find_one( conn, ns, command, bson_empty( &fields ), &response );
bson_free( ns );
if( res != MONGO_OK )
ret = MONGO_ERROR;
else {
bson_iterator it;
if( bson_find( &it, &response, "ok" ) )
success = bson_iterator_bool( &it );
if( !success ) {
conn->err = MONGO_COMMAND_FAILED;
bson_destroy( &response );
ret = MONGO_ERROR;
}
else {
if( out )
*out = response;
else
bson_destroy( &response );
}
}
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'don't mix up int and size_t (first pass to fix that)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MONGO_EXPORT void gridfile_write_buffer( gridfile *gfile, const char *data,
gridfs_offset length ) {
int bytes_left = 0;
int data_partial_len = 0;
int chunks_to_write = 0;
char *buffer;
bson *oChunk;
gridfs_offset to_write = length + gfile->pending_len;
if ( to_write < DEFAULT_CHUNK_SIZE ) { /* Less than one chunk to write */
if( gfile->pending_data ) {
gfile->pending_data = ( char * )bson_realloc( ( void * )gfile->pending_data, gfile->pending_len + to_write );
memcpy( gfile->pending_data + gfile->pending_len, data, length );
}
else if ( to_write > 0 ) {
gfile->pending_data = ( char * )bson_malloc( to_write );
memcpy( gfile->pending_data, data, length );
}
gfile->pending_len += length;
}
else { /* At least one chunk of data to write */
chunks_to_write = to_write / DEFAULT_CHUNK_SIZE;
bytes_left = to_write % DEFAULT_CHUNK_SIZE;
/* If there's a pending chunk to be written, we need to combine
* the buffer provided up to DEFAULT_CHUNK_SIZE.
*/
if ( gfile->pending_len > 0 ) {
data_partial_len = DEFAULT_CHUNK_SIZE - gfile->pending_len;
buffer = ( char * )bson_malloc( DEFAULT_CHUNK_SIZE );
memcpy( buffer, gfile->pending_data, gfile->pending_len );
memcpy( buffer + gfile->pending_len, data, data_partial_len );
oChunk = chunk_new( gfile->id, gfile->chunk_num, buffer, DEFAULT_CHUNK_SIZE );
mongo_insert( gfile->gfs->client, gfile->gfs->chunks_ns, oChunk, NULL );
chunk_free( oChunk );
gfile->chunk_num++;
gfile->length += DEFAULT_CHUNK_SIZE;
data += data_partial_len;
chunks_to_write--;
bson_free( buffer );
}
while( chunks_to_write > 0 ) {
oChunk = chunk_new( gfile->id, gfile->chunk_num, data, DEFAULT_CHUNK_SIZE );
mongo_insert( gfile->gfs->client, gfile->gfs->chunks_ns, oChunk, NULL );
chunk_free( oChunk );
gfile->chunk_num++;
chunks_to_write--;
gfile->length += DEFAULT_CHUNK_SIZE;
data += DEFAULT_CHUNK_SIZE;
}
bson_free( gfile->pending_data );
/* If there are any leftover bytes, store them as pending data. */
if( bytes_left == 0 )
gfile->pending_data = NULL;
else {
gfile->pending_data = ( char * )bson_malloc( bytes_left );
memcpy( gfile->pending_data, data, bytes_left );
}
gfile->pending_len = bytes_left;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'don't mix up int and size_t (first pass to fix that)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void Np_toString(js_State *J)
{
char buf[32];
js_Object *self = js_toobject(J, 0);
int radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1);
if (self->type != JS_CNUMBER)
js_typeerror(J, "not a number");
if (radix == 10) {
js_pushstring(J, jsV_numbertostring(J, buf, self->u.number));
return;
}
if (radix < 2 || radix > 36)
js_rangeerror(J, "invalid radix");
/* lame number to string conversion for any radix from 2 to 36 */
{
static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
char buf[100];
double number = self->u.number;
int sign = self->u.number < 0;
js_Buffer *sb = NULL;
uint64_t u, limit = ((uint64_t)1<<52);
int ndigits, exp, point;
if (number == 0) { js_pushstring(J, "0"); return; }
if (isnan(number)) { js_pushstring(J, "NaN"); return; }
if (isinf(number)) { js_pushstring(J, sign ? "-Infinity" : "Infinity"); return; }
if (sign)
number = -number;
/* fit as many digits as we want in an int */
exp = 0;
while (number * pow(radix, exp) > limit)
--exp;
while (number * pow(radix, exp+1) < limit)
++exp;
u = number * pow(radix, exp) + 0.5;
/* trim trailing zeros */
while (u > 0 && (u % radix) == 0) {
u /= radix;
--exp;
}
/* serialize digits */
ndigits = 0;
while (u > 0) {
buf[ndigits++] = digits[u % radix];
u /= radix;
}
point = ndigits - exp;
if (js_try(J)) {
js_free(J, sb);
js_throw(J);
}
if (sign)
js_putc(J, &sb, '-');
if (point <= 0) {
js_putc(J, &sb, '0');
js_putc(J, &sb, '.');
while (point++ < 0)
js_putc(J, &sb, '0');
while (ndigits-- > 0)
js_putc(J, &sb, buf[ndigits]);
} else {
while (ndigits-- > 0) {
js_putc(J, &sb, buf[ndigits]);
if (--point == 0 && ndigits > 0)
js_putc(J, &sb, '.');
}
while (point-- > 0)
js_putc(J, &sb, '0');
}
js_putc(J, &sb, 0);
js_pushstring(J, sb->s);
js_endtry(J);
js_free(J, sb);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-295', 'CWE-787'], 'message': 'Bug 700938: Fix stack overflow in numtostr as used by Number#toFixed().
32 is not enough to fit sprintf("%.20f", 1e20).
We need at least 43 bytes to fit that format.
Bump the static buffer size.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void operator()(const CPUDevice& d, typename TTypes<T, 4>::ConstTensor input,
typename TTypes<T, 3>::ConstTensor filter,
typename TTypes<T, 4>::ConstTensor out_backprop,
int stride_rows, int stride_cols, int rate_rows,
int rate_cols, int pad_top, int pad_left,
typename TTypes<T, 3>::Tensor filter_backprop) {
const int batch = input.dimension(0);
const int input_rows = input.dimension(1);
const int input_cols = input.dimension(2);
const int depth = input.dimension(3);
const int filter_rows = filter.dimension(0);
const int filter_cols = filter.dimension(1);
const int output_rows = out_backprop.dimension(1);
const int output_cols = out_backprop.dimension(2);
// Initialize gradient with all zeros.
filter_backprop.setZero();
// This is a reference implementation, likely to be slow.
// TODO(gpapan): Write multi-threaded implementation.
// In the case of multiple argmax branches, we only back-propagate along the
// last branch, i.e., the one with largest value of `h * filter_cols + w`,
// similarly to the max-pooling backward routines.
for (int b = 0; b < batch; ++b) {
for (int h_out = 0; h_out < output_rows; ++h_out) {
int h_beg = h_out * stride_rows - pad_top;
for (int w_out = 0; w_out < output_cols; ++w_out) {
int w_beg = w_out * stride_cols - pad_left;
for (int d = 0; d < depth; ++d) {
T cur_val = Eigen::NumTraits<T>::lowest();
int h_max = 0;
int w_max = 0;
for (int h = 0; h < filter_rows; ++h) {
const int h_in = h_beg + h * rate_rows;
if (h_in >= 0 && h_in < input_rows) {
for (int w = 0; w < filter_cols; ++w) {
const int w_in = w_beg + w * rate_cols;
if (w_in >= 0 && w_in < input_cols) {
const T val = input(b, h_in, w_in, d) + filter(h, w, d);
if (val > cur_val) {
cur_val = val;
h_max = h;
w_max = w;
}
}
}
}
}
filter_backprop(h_max, w_max, d) +=
out_backprop(b, h_out, w_out, d);
}
}
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Add missing validations in dillation ops.
PiperOrigin-RevId: 372037158
Change-Id: I4ee304c84a02550c030288a6534000b934fc1599'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code:
static JSValue js_sys_basecode_ex(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, Bool is_dec, Bool is_16)
{
u32 out_size=0;
u8 *out_ptr = NULL;
JSValue res;
GF_Err e;
if (!argc) return GF_JS_EXCEPTION(ctx);
if (is_dec) {
u32 len;
const char *str = JS_ToCString(ctx, argv[0]);
if (!str) return GF_JS_EXCEPTION(ctx);
len = (u32) strlen(str);
out_ptr = gf_malloc(sizeof(u8) * len);
if (!out_ptr) {
e = GF_OUT_OF_MEM;
} else if (is_16) {
out_size = gf_base16_decode((u8*) str, (u32) len, out_ptr, len);
e = out_size ? GF_OK : GF_NON_COMPLIANT_BITSTREAM;
} else {
out_size = gf_base64_decode((u8*) str, (u32) len, out_ptr, len);
e = out_size ? GF_OK : GF_NON_COMPLIANT_BITSTREAM;
}
JS_FreeCString(ctx, str);
} else {
const u8 *data;
size_t data_size;
data = JS_GetArrayBuffer(ctx, &data_size, argv[0] );
if (!data) return GF_JS_EXCEPTION(ctx);
out_ptr = gf_malloc(sizeof(u8) * (1 + data_size * 2) );
if (!out_ptr) {
e = GF_OUT_OF_MEM;
} else if (is_16) {
out_size = gf_base16_encode((u8*) data, (u32) data_size, out_ptr, 1 + (u32) data_size * 2);
e = out_size ? GF_OK : GF_NON_COMPLIANT_BITSTREAM;
} else {
out_size = gf_base64_encode((u8*) data, (u32) data_size, out_ptr, 1 + (u32) data_size * 2);
e = out_size ? GF_OK : GF_NON_COMPLIANT_BITSTREAM;
}
}
if (e) return js_throw_err(ctx, e);
if (is_dec) {
res = JS_NewArrayBuffer(ctx, out_ptr, out_size, js_gpac_free, NULL, 0);
} else {
out_ptr[out_size] = 0;
res = JS_NewString(ctx, out_ptr);
gf_free(out_ptr);
}
return res; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'fixed #2138'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: aodv_extension(netdissect_options *ndo,
const struct aodv_ext *ep, u_int length)
{
const struct aodv_hello *ah;
switch (ep->type) {
case AODV_EXT_HELLO:
ah = (const struct aodv_hello *)(const void *)ep;
ND_TCHECK(*ah);
if (length < sizeof(struct aodv_hello))
goto trunc;
ND_PRINT((ndo, "\n\text HELLO %ld ms",
(unsigned long)EXTRACT_32BITS(&ah->interval)));
break;
default:
ND_PRINT((ndo, "\n\text %u %u", ep->type, ep->length));
break;
}
return;
trunc:
ND_PRINT((ndo, " [|hello]"));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13002/AODV: Add some missing bounds checks.
In aodv_extension() do a bounds check on the extension header before we
look at it.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add a test using the capture file supplied by the reporter(s).
While we're at it, add the RFC number, and check the validity of the
length for the Hello extension.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int kvm_ioctl_create_device(struct kvm *kvm,
struct kvm_create_device *cd)
{
struct kvm_device_ops *ops = NULL;
struct kvm_device *dev;
bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
int ret;
if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
return -ENODEV;
ops = kvm_device_ops_table[cd->type];
if (ops == NULL)
return -ENODEV;
if (test)
return 0;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
dev->ops = ops;
dev->kvm = kvm;
mutex_lock(&kvm->lock);
ret = ops->create(dev, cd->type);
if (ret < 0) {
mutex_unlock(&kvm->lock);
kfree(dev);
return ret;
}
list_add(&dev->vm_node, &kvm->devices);
mutex_unlock(&kvm->lock);
if (ops->init)
ops->init(dev);
ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
if (ret < 0) {
mutex_lock(&kvm->lock);
list_del(&dev->vm_node);
mutex_unlock(&kvm->lock);
ops->destroy(dev);
return ret;
}
kvm_get_kvm(kvm);
cd->fd = ret;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'kvm: fix kvm_ioctl_create_device() reference counting (CVE-2019-6974)
kvm_ioctl_create_device() does the following:
1. creates a device that holds a reference to the VM object (with a borrowed
reference, the VM's refcount has not been bumped yet)
2. initializes the device
3. transfers the reference to the device to the caller's file descriptor table
4. calls kvm_get_kvm() to turn the borrowed reference to the VM into a real
reference
The ownership transfer in step 3 must not happen before the reference to the VM
becomes a proper, non-borrowed reference, which only happens in step 4.
After step 3, an attacker can close the file descriptor and drop the borrowed
reference, which can cause the refcount of the kvm object to drop to zero.
This means that we need to grab a reference for the device before
anon_inode_getfd(), otherwise the VM can disappear from under us.
Fixes: 852b6d57dc7f ("kvm: add device control API")
Cc: stable@kernel.org
Signed-off-by: Jann Horn <jannh@google.com>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int rose_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct rose_sock *rose = rose_sk(sk);
struct sockaddr_rose *srose = (struct sockaddr_rose *)msg->msg_name;
size_t copied;
unsigned char *asmptr;
struct sk_buff *skb;
int n, er, qbit;
/*
* This works for seqpacket too. The receiver has ordered the queue for
* us! We do one quick check first though
*/
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
/* Now we can treat all alike */
if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL)
return er;
qbit = (skb->data[0] & ROSE_Q_BIT) == ROSE_Q_BIT;
skb_pull(skb, ROSE_MIN_LEN);
if (rose->qbitincl) {
asmptr = skb_push(skb, 1);
*asmptr = qbit;
}
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (srose != NULL) {
srose->srose_family = AF_ROSE;
srose->srose_addr = rose->dest_addr;
srose->srose_call = rose->dest_call;
srose->srose_ndigis = rose->dest_ndigis;
if (msg->msg_namelen >= sizeof(struct full_sockaddr_rose)) {
struct full_sockaddr_rose *full_srose = (struct full_sockaddr_rose *)msg->msg_name;
for (n = 0 ; n < rose->dest_ndigis ; n++)
full_srose->srose_digis[n] = rose->dest_digis[n];
msg->msg_namelen = sizeof(struct full_sockaddr_rose);
} else {
if (rose->dest_ndigis >= 1) {
srose->srose_ndigis = 1;
srose->srose_digi = rose->dest_digis[0];
}
msg->msg_namelen = sizeof(struct sockaddr_rose);
}
}
skb_free_datagram(sk, skb);
return copied;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'rose: fix info leak via msg_name in rose_recvmsg()
The code in rose_recvmsg() does not initialize all of the members of
struct sockaddr_rose/full_sockaddr_rose when filling the sockaddr info.
Nor does it initialize the padding bytes of the structure inserted by
the compiler for alignment. This will lead to leaking uninitialized
kernel stack bytes in net/socket.c.
Fix the issue by initializing the memory used for sockaddr info with
memset(0).
Cc: Ralf Baechle <ralf@linux-mips.org>
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static inline void vma_adjust_trans_huge(struct vm_area_struct *vma,
unsigned long start,
unsigned long end,
long adjust_next)
{
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'mm: thp: fix /dev/zero MAP_PRIVATE and vm_flags cleanups
The huge_memory.c THP page fault was allowed to run if vm_ops was null
(which would succeed for /dev/zero MAP_PRIVATE, as the f_op->mmap wouldn't
setup a special vma->vm_ops and it would fallback to regular anonymous
memory) but other THP logics weren't fully activated for vmas with vm_file
not NULL (/dev/zero has a not NULL vma->vm_file).
So this removes the vm_file checks so that /dev/zero also can safely use
THP (the other albeit safer approach to fix this bug would have been to
prevent the THP initial page fault to run if vm_file was set).
After removing the vm_file checks, this also makes huge_memory.c stricter
in khugepaged for the DEBUG_VM=y case. It doesn't replace the vm_file
check with a is_pfn_mapping check (but it keeps checking for VM_PFNMAP
under VM_BUG_ON) because for a is_cow_mapping() mapping VM_PFNMAP should
only be allowed to exist before the first page fault, and in turn when
vma->anon_vma is null (so preventing khugepaged registration). So I tend
to think the previous comment saying if vm_file was set, VM_PFNMAP might
have been set and we could still be registered in khugepaged (despite
anon_vma was not NULL to be registered in khugepaged) was too paranoid.
The is_linear_pfn_mapping check is also I think superfluous (as described
by comment) but under DEBUG_VM it is safe to stay.
Addresses https://bugzilla.kernel.org/show_bug.cgi?id=33682
Signed-off-by: Andrea Arcangeli <aarcange@redhat.com>
Reported-by: Caspar Zhang <bugs@casparzhang.com>
Acked-by: Mel Gorman <mel@csn.ul.ie>
Acked-by: Rik van Riel <riel@redhat.com>
Cc: <stable@kernel.org> [2.6.38.x]
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
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);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], '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 <mattd@bugfuzz.com> for report and troubleshoot this
problem.
Signed-off-by: Eduardo Silva <eduardo@monkey.io>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: coolkey_find_attribute(sc_card_t *card, sc_cardctl_coolkey_attribute_t *attribute)
{
u8 object_record_type;
CK_ATTRIBUTE_TYPE attr_type = attribute->attribute_type;
const u8 *obj = attribute->object->data;
const u8 *attr = NULL;
size_t buf_len = attribute->object->length;
coolkey_object_header_t *object_head;
int attribute_count,i;
attribute->attribute_data_type = SC_CARDCTL_COOLKEY_ATTR_TYPE_STRING;
attribute->attribute_length = 0;
attribute->attribute_value = NULL;
if (obj == NULL) {
/* cast away const so we can cache the data value */
int r = coolkey_fill_object(card, (sc_cardctl_coolkey_object_t *)attribute->object);
if (r < 0) {
return r;
}
obj = attribute->object->data;
}
/* should be a static assert so we catch this at compile time */
assert(sizeof(coolkey_object_header_t) >= sizeof(coolkey_v0_object_header_t));
/* make sure we have enough of the object to read the record_type */
if (buf_len <= sizeof(coolkey_v0_object_header_t)) {
return SC_ERROR_CORRUPTED_DATA;
}
object_head = (coolkey_object_header_t *)obj;
object_record_type = object_head->record_type;
/* make sure it's a type we recognize */
if ((object_record_type != COOLKEY_V1_OBJECT) && (object_record_type != COOLKEY_V0_OBJECT)) {
return SC_ERROR_CORRUPTED_DATA;
}
/*
* now loop through all the attributes in the list. first find the start of the list
*/
attr = coolkey_attribute_start(obj, object_record_type, buf_len);
if (attr == NULL) {
return SC_ERROR_CORRUPTED_DATA;
}
buf_len -= (attr-obj);
/* now get the count */
attribute_count = coolkey_get_attribute_count(obj, object_record_type, buf_len);
for (i=0; i < attribute_count; i++) {
size_t record_len = coolkey_get_attribute_record_len(attr, object_record_type, buf_len);
/* make sure we have the complete record */
if (buf_len < record_len) {
return SC_ERROR_CORRUPTED_DATA;
}
/* does the attribute match the one we are looking for */
if (attr_type == coolkey_get_attribute_type(attr, object_record_type, record_len)) {
/* yup, return it */
return coolkey_get_attribute_data(attr, object_record_type, record_len, attribute);
}
/* go to the next attribute on the list */
buf_len -= record_len;
attr += record_len;
}
/* not find in attribute list, check the fixed attribute record */
if (object_record_type == COOLKEY_V1_OBJECT) {
unsigned long fixed_attributes = bebytes2ulong(object_head->fixed_attributes_values);
return coolkey_get_attribute_data_fixed(attr_type, fixed_attributes, attribute);
}
return SC_ERROR_DATA_OBJECT_NOT_FOUND;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: auth_read_binary(struct sc_card *card, unsigned int offset,
unsigned char *buf, size_t count, unsigned long flags)
{
int rv;
struct sc_pkcs15_bignum bn[2];
unsigned char *out = NULL;
bn[0].data = NULL;
bn[1].data = NULL;
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx,
"offset %i; size %"SC_FORMAT_LEN_SIZE_T"u; flags 0x%lX",
offset, count, flags);
sc_log(card->ctx,"last selected : magic %X; ef %X",
auth_current_ef->magic, auth_current_ef->ef_structure);
if (offset & ~0x7FFF)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid file offset");
if (auth_current_ef->magic==SC_FILE_MAGIC &&
auth_current_ef->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC) {
int jj;
unsigned char resp[256];
size_t resp_len, out_len;
struct sc_pkcs15_pubkey_rsa key;
resp_len = sizeof(resp);
rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC,
2, resp, resp_len);
LOG_TEST_RET(card->ctx, rv, "read component failed");
for (jj=0; jj<rv && *(resp+jj)==0; jj++)
;
bn[0].data = calloc(1, rv - jj);
if (!bn[0].data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
bn[0].len = rv - jj;
memcpy(bn[0].data, resp + jj, rv - jj);
rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC,
1, resp, resp_len);
LOG_TEST_GOTO_ERR(card->ctx, rv, "Cannot read RSA public key component");
bn[1].data = calloc(1, rv);
if (!bn[1].data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
bn[1].len = rv;
memcpy(bn[1].data, resp, rv);
key.exponent = bn[0];
key.modulus = bn[1];
if (sc_pkcs15_encode_pubkey_rsa(card->ctx, &key, &out, &out_len)) {
rv = SC_ERROR_INVALID_ASN1_OBJECT;
LOG_TEST_GOTO_ERR(card->ctx, rv, "cannot encode RSA public key");
}
else {
rv = out_len - offset > count ? count : out_len - offset;
memcpy(buf, out + offset, rv);
sc_log_hex(card->ctx, "write_publickey", buf, rv);
}
}
else {
rv = iso_ops->read_binary(card, offset, buf, count, 0);
}
err:
free(bn[0].data);
free(bn[1].data);
free(out);
LOG_FUNC_RETURN(card->ctx, rv);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ModuleSQL::~ModuleSQL()
{
if (Dispatcher)
{
Dispatcher->join();
Dispatcher->OnNotify();
delete Dispatcher;
}
for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
{
delete i->second;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Initialise and deallocate the MySQL library correctly.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: SWFShape_setLeftFillStyle(SWFShape shape, SWFFillStyle fill)
{
ShapeRecord record;
int idx;
if ( shape->isEnded || shape->isMorph )
return;
if(fill == NOFILL)
{
record = addStyleRecord(shape);
record.record.stateChange->leftFill = 0;
record.record.stateChange->flags |= SWF_SHAPE_FILLSTYLE0FLAG;
return;
}
idx = getFillIdx(shape, fill);
if(idx == 0) // fill not present in array
{
SWFFillStyle_addDependency(fill, (SWFCharacter)shape);
if(addFillStyle(shape, fill) < 0)
return;
idx = getFillIdx(shape, fill);
}
record = addStyleRecord(shape);
record.record.stateChange->leftFill = idx;
record.record.stateChange->flags |= SWF_SHAPE_FILLSTYLE0FLAG;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'SWFShape_setLeftFillStyle: prevent fill overflow'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int64 CSteamNetworkConnectionBase::SNP_SendMessage( CSteamNetworkingMessage *pSendMessage, SteamNetworkingMicroseconds usecNow, bool *pbThinkImmediately )
{
int cbData = (int)pSendMessage->m_cbSize;
// Assume we won't want to wake up immediately
if ( pbThinkImmediately )
*pbThinkImmediately = false;
// Check if we're full
if ( m_senderState.PendingBytesTotal() + cbData > m_connectionConfig.m_SendBufferSize.Get() )
{
SpewWarningRateLimited( usecNow, "Connection already has %u bytes pending, cannot queue any more messages\n", m_senderState.PendingBytesTotal() );
pSendMessage->Release();
return -k_EResultLimitExceeded;
}
// Check if they try to send a really large message
if ( cbData > k_cbMaxUnreliableMsgSize && !( pSendMessage->m_nFlags & k_nSteamNetworkingSend_Reliable ) )
{
SpewWarningRateLimited( usecNow, "Trying to send a very large (%d bytes) unreliable message. Sending as reliable instead.\n", cbData );
pSendMessage->m_nFlags |= k_nSteamNetworkingSend_Reliable;
}
if ( pSendMessage->m_nFlags & k_nSteamNetworkingSend_NoDelay )
{
// FIXME - need to check how much data is currently pending, and return
// k_EResultIgnored if we think it's going to be a while before this
// packet goes on the wire.
}
// First, accumulate tokens, and also limit to reasonable burst
// if we weren't already waiting to send
SNP_ClampSendRate();
SNP_TokenBucket_Accumulate( usecNow );
// Assign a message number
pSendMessage->m_nMessageNumber = ++m_senderState.m_nLastSentMsgNum;
// Reliable, or unreliable?
if ( pSendMessage->m_nFlags & k_nSteamNetworkingSend_Reliable )
{
pSendMessage->SNPSend_SetReliableStreamPos( m_senderState.m_nReliableStreamPos );
// Generate the header
byte *hdr = pSendMessage->SNPSend_ReliableHeader();
hdr[0] = 0;
byte *hdrEnd = hdr+1;
int64 nMsgNumGap = pSendMessage->m_nMessageNumber - m_senderState.m_nLastSendMsgNumReliable;
Assert( nMsgNumGap >= 1 );
if ( nMsgNumGap > 1 )
{
hdrEnd = SerializeVarInt( hdrEnd, (uint64)nMsgNumGap );
hdr[0] |= 0x40;
}
if ( cbData < 0x20 )
{
hdr[0] |= (byte)cbData;
}
else
{
hdr[0] |= (byte)( 0x20 | ( cbData & 0x1f ) );
hdrEnd = SerializeVarInt( hdrEnd, cbData>>5U );
}
pSendMessage->m_cbSNPSendReliableHeader = hdrEnd - hdr;
// Grow the total size of the message by the header
pSendMessage->m_cbSize += pSendMessage->m_cbSNPSendReliableHeader;
// Advance stream pointer
m_senderState.m_nReliableStreamPos += pSendMessage->m_cbSize;
// Update stats
++m_senderState.m_nMessagesSentReliable;
m_senderState.m_cbPendingReliable += pSendMessage->m_cbSize;
// Remember last sent reliable message number, so we can know how to
// encode the next one
m_senderState.m_nLastSendMsgNumReliable = pSendMessage->m_nMessageNumber;
Assert( pSendMessage->SNPSend_IsReliable() );
}
else
{
pSendMessage->SNPSend_SetReliableStreamPos( 0 );
pSendMessage->m_cbSNPSendReliableHeader = 0;
++m_senderState.m_nMessagesSentUnreliable;
m_senderState.m_cbPendingUnreliable += pSendMessage->m_cbSize;
Assert( !pSendMessage->SNPSend_IsReliable() );
}
// Add to pending list
m_senderState.m_messagesQueued.push_back( pSendMessage );
SpewVerboseGroup( m_connectionConfig.m_LogLevel_Message.Get(), "[%s] SendMessage %s: MsgNum=%lld sz=%d\n",
GetDescription(),
pSendMessage->SNPSend_IsReliable() ? "RELIABLE" : "UNRELIABLE",
(long long)pSendMessage->m_nMessageNumber,
pSendMessage->m_cbSize );
// Use Nagle?
// We always set the Nagle timer, even if we immediately clear it. This makes our clearing code simpler,
// since we can always safely assume that once we find a message with the nagle timer cleared, all messages
// queued earlier than this also have it cleared.
// FIXME - Don't think this works if the configuration value is changing. Since changing the
// config value could violate the assumption that nagle times are increasing. Probably not worth
// fixing.
pSendMessage->SNPSend_SetUsecNagle( usecNow + m_connectionConfig.m_NagleTime.Get() );
if ( pSendMessage->m_nFlags & k_nSteamNetworkingSend_NoNagle )
m_senderState.ClearNagleTimers();
// Save the message number. The code below might end up deleting the message we just queued
int64 result = pSendMessage->m_nMessageNumber;
// Schedule wakeup at the appropriate time. (E.g. right now, if we're ready to send,
// or at the Nagle time, if Nagle is active.)
//
// NOTE: Right now we might not actually be capable of sending end to end data.
// But that case is relatievly rare, and nothing will break if we try to right now.
// On the other hand, just asking the question involved a virtual function call,
// and it will return success most of the time, so let's not make the check here.
if ( GetState() == k_ESteamNetworkingConnectionState_Connected )
{
SteamNetworkingMicroseconds usecNextThink = SNP_GetNextThinkTime( usecNow );
// Ready to send now?
if ( usecNextThink > usecNow )
{
// We are rate limiting. Spew about it?
if ( m_senderState.m_messagesQueued.m_pFirst->SNPSend_UsecNagle() == 0 )
{
SpewVerbose( "[%s] RATELIM QueueTime is %.1fms, SendRate=%.1fk, BytesQueued=%d\n",
GetDescription(),
m_senderState.CalcTimeUntilNextSend() * 1e-3,
m_senderState.m_n_x * ( 1.0/1024.0),
m_senderState.PendingBytesTotal()
);
}
// Set a wakeup call.
EnsureMinThinkTime( usecNextThink );
}
else
{
// We're ready to send right now. Check if we should!
if ( pSendMessage->m_nFlags & k_nSteamNetworkingSend_UseCurrentThread )
{
// We should send in this thread, before the API entry point
// that the app used returns. Is the caller gonna handle this?
if ( pbThinkImmediately )
{
// Caller says they will handle it
*pbThinkImmediately = true;
}
else
{
// Caller wants us to just do it here.
CheckConnectionStateAndSetNextThinkTime( usecNow );
}
}
else
{
// Wake up the service thread ASAP to send this in the background thread
SetNextThinkTimeASAP();
}
}
}
return result;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Drop unreliable segments with weird offset/size.
And be more deliberate about limits of unreliable message/segment sizes.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int download(struct SPDBDownloader *pd) {
SPDBDownloaderOpt *opt = pd->opt;
char *curl_cmd = NULL;
char *extractor_cmd = NULL;
char *abspath_to_archive = NULL;
char *abspath_to_file = NULL;
char *archive_name = NULL;
size_t archive_name_len = 0;
char *symbol_store_path = NULL;
char *dbg_file = NULL;
char *guid = NULL;
char *archive_name_escaped = NULL;
char *user_agent = NULL;
char *symbol_server = NULL;
int res = 0;
int cmd_ret;
if (!opt->dbg_file || !*opt->dbg_file) {
// no pdb debug file
return 0;
}
if (!checkCurl ()) {
return 0;
}
// dbg_file len is > 0
archive_name_len = strlen (opt->dbg_file);
archive_name = malloc (archive_name_len + 1);
if (!archive_name) {
return 0;
}
memcpy (archive_name, opt->dbg_file, archive_name_len + 1);
archive_name[archive_name_len - 1] = '_';
symbol_store_path = r_str_escape (opt->symbol_store_path);
dbg_file = r_str_escape (opt->dbg_file);
guid = r_str_escape (opt->guid);
archive_name_escaped = r_str_escape (archive_name);
user_agent = r_str_escape (opt->user_agent);
symbol_server = r_str_escape (opt->symbol_server);
abspath_to_archive = r_str_newf ("%s%s%s%s%s%s%s",
symbol_store_path, R_SYS_DIR,
dbg_file, R_SYS_DIR,
guid, R_SYS_DIR,
archive_name_escaped);
abspath_to_file = strdup (abspath_to_archive);
abspath_to_file[strlen (abspath_to_file) - 1] = 'b';
if (r_file_exists (abspath_to_file)) {
eprintf ("File already downloaded.\n");
R_FREE (user_agent);
R_FREE (abspath_to_archive);
R_FREE (archive_name_escaped);
R_FREE (symbol_store_path);
R_FREE (dbg_file);
R_FREE (guid);
R_FREE (archive_name);
R_FREE (abspath_to_file);
R_FREE (symbol_server);
return 1;
}
if (checkExtract () || opt->extract == 0) {
res = 1;
curl_cmd = r_str_newf ("curl -sfLA \"%s\" \"%s/%s/%s/%s\" --create-dirs -o \"%s\"",
user_agent,
symbol_server,
dbg_file,
guid,
archive_name_escaped,
abspath_to_archive);
#if __WINDOWS__
const char *cabextractor = "expand";
const char *format = "%s %s %s";
// extractor_cmd -> %1 %2 %3
// %1 - 'expand'
// %2 - absolute path to archive
// %3 - absolute path to file that will be dearchive
extractor_cmd = r_str_newf (format, cabextractor,
abspath_to_archive, abspath_to_file);
#else
const char *cabextractor = "cabextract";
const char *format = "%s -d \"%s\" \"%s\"";
char *abspath_to_dir = r_file_dirname (abspath_to_archive);
// cabextract -d %1 %2
// %1 - path to directory where to extract all files from cab archive
// %2 - absolute path to cab archive
extractor_cmd = r_str_newf (format, cabextractor, abspath_to_dir, abspath_to_archive);
R_FREE (abspath_to_dir);
#endif
eprintf ("Attempting to download compressed pdb in %s\n", abspath_to_archive);
if ((cmd_ret = r_sys_cmd (curl_cmd) != 0)) {
eprintf("curl exited with error %d\n", cmd_ret);
res = 0;
}
eprintf ("Attempting to decompress pdb\n");
if (opt->extract > 0) {
if (res && ((cmd_ret = r_sys_cmd (extractor_cmd)) != 0)) {
eprintf ("cab extractor exited with error %d\n", cmd_ret);
res = 0;
}
r_file_rm (abspath_to_archive);
}
R_FREE (curl_cmd);
}
if (res == 0) {
eprintf ("Falling back to uncompressed pdb\n");
res = 1;
archive_name_escaped[strlen (archive_name_escaped) - 1] = 'b';
curl_cmd = r_str_newf ("curl -sfLA \"%s\" \"%s/%s/%s/%s\" --create-dirs -o \"%s\"",
opt->user_agent,
opt->symbol_server,
opt->dbg_file,
opt->guid,
archive_name_escaped,
abspath_to_file);
eprintf ("Attempting to download uncompressed pdb in %s\n", abspath_to_file);
if ((cmd_ret = r_sys_cmd (curl_cmd) != 0)) {
eprintf("curl exited with error %d\n", cmd_ret);
res = 0;
}
R_FREE (curl_cmd);
}
R_FREE (abspath_to_archive);
R_FREE (abspath_to_file);
R_FREE (archive_name);
R_FREE (extractor_cmd);
R_FREE (symbol_store_path);
R_FREE (dbg_file);
R_FREE (guid);
R_FREE (archive_name_escaped);
R_FREE (user_agent);
R_FREE (symbol_server);
return res;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-78'], 'message': 'Fix command injection on PDB download (#16966)
* Fix r_sys_mkdirp with absolute path on Windows
* Fix build with --with-openssl
* Use RBuffer in r_socket_http_answer()
* r_socket_http_answer: Fix read for big responses
* Implement r_str_escape_sh()
* Cleanup r_socket_connect() on Windows
* Fix socket being created without a protocol
* Fix socket connect with SSL ##socket
* Use select() in r_socket_ready()
* Fix read failing if received only protocol answer
* Fix double-free
* r_socket_http_get: Fail if req. SSL with no support
* Follow redirects in r_socket_http_answer()
* Fix r_socket_http_get result length with R2_CURL=1
* Also follow redirects
* Avoid using curl for downloading PDBs
* Use r_socket_http_get() on UNIXs
* Use WinINet API on Windows for r_socket_http_get()
* Fix command injection
* Fix r_sys_cmd_str_full output for binary data
* Validate GUID on PDB download
* Pass depth to socket_http_get_recursive()
* Remove 'r_' and '__' from static function names
* Fix is_valid_guid
* Fix for comments'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: R_API int r_socket_read(RSocket *s, unsigned char *buf, int len) {
return -1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-78'], 'message': 'Fix command injection on PDB download (#16966)
* Fix r_sys_mkdirp with absolute path on Windows
* Fix build with --with-openssl
* Use RBuffer in r_socket_http_answer()
* r_socket_http_answer: Fix read for big responses
* Implement r_str_escape_sh()
* Cleanup r_socket_connect() on Windows
* Fix socket being created without a protocol
* Fix socket connect with SSL ##socket
* Use select() in r_socket_ready()
* Fix read failing if received only protocol answer
* Fix double-free
* r_socket_http_get: Fail if req. SSL with no support
* Follow redirects in r_socket_http_answer()
* Fix r_socket_http_get result length with R2_CURL=1
* Also follow redirects
* Avoid using curl for downloading PDBs
* Use r_socket_http_get() on UNIXs
* Use WinINet API on Windows for r_socket_http_get()
* Fix command injection
* Fix r_sys_cmd_str_full output for binary data
* Validate GUID on PDB download
* Pass depth to socket_http_get_recursive()
* Remove 'r_' and '__' from static function names
* Fix is_valid_guid
* Fix for comments'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: R_API int r_socket_ready(RSocket *s, int secs, int usecs) {
return -1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-78'], 'message': 'Fix command injection on PDB download (#16966)
* Fix r_sys_mkdirp with absolute path on Windows
* Fix build with --with-openssl
* Use RBuffer in r_socket_http_answer()
* r_socket_http_answer: Fix read for big responses
* Implement r_str_escape_sh()
* Cleanup r_socket_connect() on Windows
* Fix socket being created without a protocol
* Fix socket connect with SSL ##socket
* Use select() in r_socket_ready()
* Fix read failing if received only protocol answer
* Fix double-free
* r_socket_http_get: Fail if req. SSL with no support
* Follow redirects in r_socket_http_answer()
* Fix r_socket_http_get result length with R2_CURL=1
* Also follow redirects
* Avoid using curl for downloading PDBs
* Use r_socket_http_get() on UNIXs
* Use WinINet API on Windows for r_socket_http_get()
* Fix command injection
* Fix r_sys_cmd_str_full output for binary data
* Validate GUID on PDB download
* Pass depth to socket_http_get_recursive()
* Remove 'r_' and '__' from static function names
* Fix is_valid_guid
* Fix for comments'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void IOBuf::allocExtBuffer(
std::size_t minCapacity,
uint8_t** bufReturn,
SharedInfo** infoReturn,
std::size_t* capacityReturn) {
size_t mallocSize = goodExtBufferSize(minCapacity);
auto buf = static_cast<uint8_t*>(checkedMalloc(mallocSize));
initExtBuffer(buf, mallocSize, infoReturn, capacityReturn);
// the userData and the freeFn are nullptr here
// just store the mallocSize in userData
(*infoReturn)->userData = reinterpret_cast<void*>(mallocSize);
if (io_buf_alloc_cb) {
io_buf_alloc_cb(buf, mallocSize);
}
*bufReturn = buf;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': '[folly] Add additional overflow checks to IOBuf - CVE-2021-24036
Summary:
As per title
CVE-2021-24036
Reviewed By: jan
Differential Revision: D27938605
fbshipit-source-id: 7481c54ae6fbb7b67b15b3631d5357c2f7043f9c'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void Sp_replace_regexp(js_State *J)
{
js_Regexp *re;
const char *source, *s, *r;
js_Buffer *sb = NULL;
int n, x;
Resub m;
source = checkstring(J, 0);
re = js_toregexp(J, 1);
if (js_regexec(re->prog, source, &m, 0)) {
js_copy(J, 0);
return;
}
re->last = 0;
loop:
s = m.sub[0].sp;
n = m.sub[0].ep - m.sub[0].sp;
if (js_iscallable(J, 2)) {
js_copy(J, 2);
js_pushundefined(J);
for (x = 0; m.sub[x].sp; ++x) /* arg 0..x: substring and subexps that matched */
js_pushlstring(J, m.sub[x].sp, m.sub[x].ep - m.sub[x].sp);
js_pushnumber(J, s - source); /* arg x+2: offset within search string */
js_copy(J, 0); /* arg x+3: search string */
js_call(J, 2 + x);
r = js_tostring(J, -1);
js_putm(J, &sb, source, s);
js_puts(J, &sb, r);
js_pop(J, 1);
} else {
r = js_tostring(J, 2);
js_putm(J, &sb, source, s);
while (*r) {
if (*r == '$') {
switch (*(++r)) {
case 0: --r; /* end of string; back up */
/* fallthrough */
case '$': js_putc(J, &sb, '$'); break;
case '`': js_putm(J, &sb, source, s); break;
case '\'': js_puts(J, &sb, s + n); break;
case '&':
js_putm(J, &sb, s, s + n);
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
x = *r - '0';
if (r[1] >= '0' && r[1] <= '9')
x = x * 10 + *(++r) - '0';
if (x > 0 && x < m.nsub) {
js_putm(J, &sb, m.sub[x].sp, m.sub[x].ep);
} else {
js_putc(J, &sb, '$');
if (x > 10) {
js_putc(J, &sb, '0' + x / 10);
js_putc(J, &sb, '0' + x % 10);
} else {
js_putc(J, &sb, '0' + x);
}
}
break;
default:
js_putc(J, &sb, '$');
js_putc(J, &sb, *r);
break;
}
++r;
} else {
js_putc(J, &sb, *r++);
}
}
}
if (re->flags & JS_REGEXP_G) {
source = m.sub[0].ep;
if (n == 0) {
if (*source)
js_putc(J, &sb, *source++);
else
goto end;
}
if (!js_regexec(re->prog, source, &m, REG_NOTBOL))
goto loop;
}
end:
js_puts(J, &sb, s + n);
js_putc(J, &sb, 0);
if (js_try(J)) {
js_free(J, sb);
js_throw(J);
}
js_pushstring(J, sb ? sb->s : "");
js_endtry(J);
js_free(J, sb);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-674', 'CWE-787'], 'message': 'Bug 700937: Limit recursion in regexp matcher.
Also handle negative return code as an error in the JS bindings.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int linear_ioctl(struct dm_target *ti, unsigned int cmd,
unsigned long arg)
{
struct linear_c *lc = (struct linear_c *) ti->private;
return __blkdev_driver_ioctl(lc->dev->bdev, lc->dev->mode, cmd, arg);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'dm: do not forward ioctls from logical volumes to the underlying device
A logical volume can map to just part of underlying physical volume.
In this case, it must be treated like a partition.
Based on a patch from Alasdair G Kergon.
Cc: Alasdair G Kergon <agk@redhat.com>
Cc: dm-devel@redhat.com
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: GF_Err gf_isom_box_parse_ex(GF_Box **outBox, GF_BitStream *bs, u32 parent_type, Bool is_root_box)
{
u32 type, uuid_type, hdr_size, restore_type;
u64 size, start, comp_start, payload_start, end;
char uuid[16];
GF_Err e;
GF_BitStream *uncomp_bs = NULL;
u8 *uncomp_data = NULL;
u32 compressed_size=0;
GF_Box *newBox;
Bool skip_logs = (gf_bs_get_cookie(bs) & GF_ISOM_BS_COOKIE_NO_LOGS ) ? GF_TRUE : GF_FALSE;
Bool is_special = GF_TRUE;
if ((bs == NULL) || (outBox == NULL) ) return GF_BAD_PARAM;
*outBox = NULL;
if (gf_bs_available(bs) < 8) {
return GF_ISOM_INCOMPLETE_FILE;
}
comp_start = start = gf_bs_get_position(bs);
uuid_type = 0;
size = (u64) gf_bs_read_u32(bs);
hdr_size = 4;
/*fix for some boxes found in some old hinted files*/
if ((size >= 2) && (size <= 4)) {
size = 4;
type = GF_ISOM_BOX_TYPE_VOID;
} else {
type = gf_bs_read_u32(bs);
hdr_size += 4;
/*no size means till end of file - EXCEPT FOR some old QuickTime boxes...*/
if (type == GF_ISOM_BOX_TYPE_TOTL)
size = 12;
if (!size) {
if (is_root_box) {
if (!skip_logs) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[iso file] Warning Read Box type %s (0x%08X) size 0 reading till the end of file\n", gf_4cc_to_str(type), type));
}
size = gf_bs_available(bs) + 8;
} else {
if (!skip_logs) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Read Box type %s (0x%08X) at position "LLU" has size 0 but is not at root/file level, skipping\n", gf_4cc_to_str(type), type, start));
}
return GF_OK;
}
}
if (is_root_box && (size>=8)) {
Bool do_uncompress = GF_FALSE;
u8 *compb = NULL;
u32 osize = 0;
u32 otype = type;
if (type==GF_4CC('!', 'm', 'o', 'f')) {
do_uncompress = GF_TRUE;
type = GF_ISOM_BOX_TYPE_MOOF;
}
else if (type==GF_4CC('!', 'm', 'o', 'v')) {
do_uncompress = GF_TRUE;
type = GF_ISOM_BOX_TYPE_MOOV;
}
else if (type==GF_4CC('!', 's', 'i', 'x')) {
do_uncompress = GF_TRUE;
type = GF_ISOM_BOX_TYPE_SIDX;
}
else if (type==GF_4CC('!', 's', 's', 'x')) {
do_uncompress = GF_TRUE;
type = GF_ISOM_BOX_TYPE_SSIX;
}
if (do_uncompress) {
compb = gf_malloc((u32) (size-8));
compressed_size = (u32) (size - 8);
gf_bs_read_data(bs, compb, compressed_size);
e = gf_gz_decompress_payload(compb, compressed_size, &uncomp_data, &osize);
if (e) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Failed to uncompress payload for box type %s (0x%08X)\n", gf_4cc_to_str(otype), otype));
return e;
}
//keep size as complete box size for tests below
size = osize + 8;
uncomp_bs = gf_bs_new(uncomp_data, osize, GF_BITSTREAM_READ);
bs = uncomp_bs;
start = 0;
gf_free(compb);
}
}
}
/*handle uuid*/
memset(uuid, 0, 16);
if (type == GF_ISOM_BOX_TYPE_UUID ) {
if (gf_bs_available(bs) < 16) {
return GF_ISOM_INCOMPLETE_FILE;
}
gf_bs_read_data(bs, uuid, 16);
hdr_size += 16;
uuid_type = gf_isom_solve_uuid_box(uuid);
}
//handle large box
if (size == 1) {
if (gf_bs_available(bs) < 8) {
return GF_ISOM_INCOMPLETE_FILE;
}
size = gf_bs_read_u64(bs);
hdr_size += 8;
}
if (!skip_logs)
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[iso file] Read Box type %s size "LLD" start "LLD"\n", gf_4cc_to_str(type), size, start));
if ( size < hdr_size ) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[iso file] Box size "LLD" less than box header size %d\n", size, hdr_size));
return GF_ISOM_INVALID_FILE;
}
restore_type = 0;
if ((parent_type==GF_ISOM_BOX_TYPE_STSD) && (type==GF_QT_SUBTYPE_RAW) ) {
u64 cookie = gf_bs_get_cookie(bs);
restore_type = type;
if (cookie & GF_ISOM_BS_COOKIE_VISUAL_TRACK)
type = GF_QT_SUBTYPE_RAW_VID;
else
type = GF_QT_SUBTYPE_RAW_AUD;
}
//some special boxes (references and track groups) are handled by a single generic box with an associated ref/group type
if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_TREF)) {
newBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_REFT);
if (!newBox) return GF_OUT_OF_MEM;
((GF_TrackReferenceTypeBox*)newBox)->reference_type = type;
} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_IREF)) {
newBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_REFI);
if (!newBox) return GF_OUT_OF_MEM;
((GF_ItemReferenceTypeBox*)newBox)->reference_type = type;
} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_TRGR)) {
newBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_TRGT);
if (!newBox) return GF_OUT_OF_MEM;
((GF_TrackGroupTypeBox*)newBox)->group_type = type;
} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_GRPL)) {
newBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_GRPT);
if (!newBox) return GF_OUT_OF_MEM;
((GF_EntityToGroupTypeBox*)newBox)->grouping_type = type;
} else {
//OK, create the box based on the type
is_special = GF_FALSE;
newBox = gf_isom_box_new_ex(uuid_type ? uuid_type : type, parent_type, skip_logs, is_root_box);
if (!newBox) return GF_OUT_OF_MEM;
}
//OK, init and read this box
if (type==GF_ISOM_BOX_TYPE_UUID && !is_special) {
memcpy(((GF_UUIDBox *)newBox)->uuid, uuid, 16);
((GF_UUIDBox *)newBox)->internal_4cc = uuid_type;
}
if (!newBox->type) newBox->type = type;
if (restore_type)
newBox->type = restore_type;
payload_start = gf_bs_get_position(bs);
retry_unknown_box:
end = gf_bs_available(bs);
if (size - hdr_size > end ) {
newBox->size = size - hdr_size - end;
*outBox = newBox;
return GF_ISOM_INCOMPLETE_FILE;
}
newBox->size = size - hdr_size;
e = gf_isom_full_box_read(newBox, bs);
if (!e) e = gf_isom_box_read(newBox, bs);
if (e) {
if (gf_opts_get_bool("core", "no-check"))
e = GF_OK;
}
newBox->size = size;
end = gf_bs_get_position(bs);
if (uncomp_bs) {
gf_free(uncomp_data);
gf_bs_del(uncomp_bs);
if (e) {
gf_isom_box_del(newBox);
*outBox = NULL;
return e;
}
//move size to real bitstream offsets for tests below
size -= 8;
//remember compressed vs real size info for moof in order to properly recompute data_offset/base_data_offset
if (type==GF_ISOM_BOX_TYPE_MOOF) {
((GF_MovieFragmentBox *)newBox)->compressed_diff = (s32)size - (s32)compressed_size;
}
//remember compressed vs real size info for moov in order to properly recompute chunk offset
else if (type==GF_ISOM_BOX_TYPE_MOOV) {
((GF_MovieBox *)newBox)->compressed_diff = (s32)size - (s32)compressed_size;
((GF_MovieBox *)newBox)->file_offset = comp_start;
}
//remember compressed vs real size info for dump
else if (type==GF_ISOM_BOX_TYPE_SIDX) {
((GF_SegmentIndexBox *)newBox)->compressed_diff = (s32)size - (s32)compressed_size;
}
//remember compressed vs real size info for dump
else if (type==GF_ISOM_BOX_TYPE_SSIX) {
((GF_SubsegmentIndexBox *)newBox)->compressed_diff = (s32)size - (s32)compressed_size;
}
newBox->internal_flags = GF_ISOM_BOX_COMPRESSED;
}
if (e && (e != GF_ISOM_INCOMPLETE_FILE)) {
gf_isom_box_del(newBox);
*outBox = NULL;
if (parent_type==GF_ISOM_BOX_TYPE_STSD) {
newBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_UNKNOWN);
if (!newBox) return GF_OUT_OF_MEM;
((GF_UnknownBox *)newBox)->original_4cc = type;
newBox->size = size;
gf_bs_seek(bs, payload_start);
goto retry_unknown_box;
}
if (!skip_logs) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Read Box \"%s\" (start "LLU") failed (%s) - skipping\n", gf_4cc_to_str(type), start, gf_error_to_string(e)));
}
//we don't try to reparse known boxes that have been failing (too dangerous)
return e;
}
if (end-start > size) {
if (!skip_logs) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Box \"%s\" size "LLU" (start "LLU") invalid (read "LLU")\n", gf_4cc_to_str(type), size, start, (end-start) ));
}
/*let's still try to load the file since no error was notified*/
gf_bs_seek(bs, start+size);
} else if (end-start < size) {
u32 to_skip = (u32) (size-(end-start));
if (!skip_logs) {
if ((to_skip!=4) || gf_bs_peek_bits(bs, 32, 0)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Box \"%s\" (start "LLU") has %u extra bytes\n", gf_4cc_to_str(type), start, to_skip));
}
}
gf_bs_skip_bytes(bs, to_skip);
}
*outBox = newBox;
return e;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'fixed #1768'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void md5_transform(u32 *hash, u32 const *in)
{
u32 a, b, c, d;
a = hash[0];
b = hash[1];
c = hash[2];
d = hash[3];
MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
hash[0] += a;
hash[1] += b;
hash[2] += c;
hash[3] += d;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'crypto: Move md5_transform to lib/md5.c
We are going to use this for TCP/IP sequence number and fragment ID
generation.
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int mbochs_probe(struct mdev_device *mdev)
{
const struct mbochs_type *type =
&mbochs_types[mdev_get_type_group_id(mdev)];
struct device *dev = mdev_dev(mdev);
struct mdev_state *mdev_state;
int ret = -ENOMEM;
if (type->mbytes + mbochs_used_mbytes > max_mbytes)
return -ENOMEM;
mdev_state = kzalloc(sizeof(struct mdev_state), GFP_KERNEL);
if (mdev_state == NULL)
return -ENOMEM;
vfio_init_group_dev(&mdev_state->vdev, &mdev->dev, &mbochs_dev_ops);
mdev_state->vconfig = kzalloc(MBOCHS_CONFIG_SPACE_SIZE, GFP_KERNEL);
if (mdev_state->vconfig == NULL)
goto err_mem;
mdev_state->memsize = type->mbytes * 1024 * 1024;
mdev_state->pagecount = mdev_state->memsize >> PAGE_SHIFT;
mdev_state->pages = kcalloc(mdev_state->pagecount,
sizeof(struct page *),
GFP_KERNEL);
if (!mdev_state->pages)
goto err_mem;
dev_info(dev, "%s: %s, %d MB, %ld pages\n", __func__,
type->name, type->mbytes, mdev_state->pagecount);
mutex_init(&mdev_state->ops_lock);
mdev_state->mdev = mdev;
INIT_LIST_HEAD(&mdev_state->dmabufs);
mdev_state->next_id = 1;
mdev_state->type = type;
mdev_state->edid_regs.max_xres = type->max_x;
mdev_state->edid_regs.max_yres = type->max_y;
mdev_state->edid_regs.edid_offset = MBOCHS_EDID_BLOB_OFFSET;
mdev_state->edid_regs.edid_max_size = sizeof(mdev_state->edid_blob);
mbochs_create_config_space(mdev_state);
mbochs_reset(mdev_state);
mbochs_used_mbytes += type->mbytes;
ret = vfio_register_group_dev(&mdev_state->vdev);
if (ret)
goto err_mem;
dev_set_drvdata(&mdev->dev, mdev_state);
return 0;
err_mem:
kfree(mdev_state->vconfig);
kfree(mdev_state);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-401'], 'message': 'vfio/mbochs: Fix missing error unwind of mbochs_used_mbytes
Convert mbochs to use an atomic scheme for this like mtty was changed
into. The atomic fixes various race conditions with probing. Add the
missing error unwind. Also add the missing kfree of mdev_state->pages.
Fixes: 681c1615f891 ("vfio/mbochs: Convert to use vfio_register_group_dev()")
Reported-by: Cornelia Huck <cohuck@redhat.com>
Co-developed-by: Alex Williamson <alex.williamson@redhat.com>
Reviewed-by: Christoph Hellwig <hch@lst.de>
Signed-off-by: Jason Gunthorpe <jgg@nvidia.com>
Reviewed-by: Cornelia Huck <cohuck@redhat.com>
Link: https://lore.kernel.org/r/2-v4-9ea22c5e6afb+1adf-vfio_reflck_jgg@nvidia.com
Signed-off-by: Alex Williamson <alex.williamson@redhat.com>'</s> |