text
stringlengths 478
483k
|
---|
<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 timed_out_busy_iter(void *data, void *val)
{
stream_iter_ctx *ctx = data;
h2_stream *stream = val;
if (stream->task && !stream->task->worker_done
&& (ctx->now - stream->task->started_at) > stream->task->timeout) {
/* timed out stream occupying a worker, found */
ctx->stream = stream;
return 0;
}
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now,
mpm event backport to 2.4.x up for vote).
* Fixes stream cleanup when connection throttling is in place.
* Counts stream resets by client on streams initiated by client as cause
for connection throttling.
* Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann)
* Header length is checked also on the merged value from several header instances
and results in a 431 response.'</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 h2_mplx_task_done(h2_mplx *m, h2_task *task, h2_task **ptask)
{
H2_MPLX_ENTER_ALWAYS(m);
task_done(m, task);
--m->tasks_active;
if (m->join_wait) {
apr_thread_cond_signal(m->join_wait);
}
if (ptask) {
/* caller wants another task */
*ptask = next_stream_task(m);
}
register_if_needed(m);
H2_MPLX_LEAVE(m);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now,
mpm event backport to 2.4.x up for vote).
* Fixes stream cleanup when connection throttling is in place.
* Counts stream resets by client on streams initiated by client as cause
for connection throttling.
* Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann)
* Header length is checked also on the merged value from several header instances
and results in a 431 response.'</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 task_done(h2_mplx *m, h2_task *task)
{
h2_stream *stream;
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, m->c,
"h2_mplx(%ld): task(%s) done", m->id, task->id);
out_close(m, task);
task->worker_done = 1;
task->done_at = apr_time_now();
ap_log_cerror(APLOG_MARK, APLOG_TRACE2, 0, m->c,
"h2_mplx(%s): request done, %f ms elapsed", task->id,
(task->done_at - task->started_at) / 1000.0);
if (task->started_at > m->last_idle_block) {
/* this task finished without causing an 'idle block', e.g.
* a block by flow control.
*/
if (task->done_at- m->last_limit_change >= m->limit_change_interval
&& m->limit_active < m->max_active) {
/* Well behaving stream, allow it more workers */
m->limit_active = H2MIN(m->limit_active * 2,
m->max_active);
m->last_limit_change = task->done_at;
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, m->c,
"h2_mplx(%ld): increase worker limit to %d",
m->id, m->limit_active);
}
}
ap_assert(task->done_done == 0);
stream = h2_ihash_get(m->streams, task->stream_id);
if (stream) {
/* stream not done yet. */
if (!m->aborted && h2_ihash_get(m->sredo, stream->id)) {
/* reset and schedule again */
task->worker_done = 0;
h2_task_redo(task);
h2_ihash_remove(m->sredo, stream->id);
h2_iq_add(m->q, stream->id, NULL, NULL);
ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, m->c,
H2_STRM_MSG(stream, "redo, added to q"));
}
else {
/* stream not cleaned up, stay around */
task->done_done = 1;
ap_log_cerror(APLOG_MARK, APLOG_TRACE2, 0, m->c,
H2_STRM_MSG(stream, "task_done, stream open"));
if (stream->input) {
h2_beam_leave(stream->input);
}
/* more data will not arrive, resume the stream */
check_data_for(m, stream, 0);
}
}
else if ((stream = h2_ihash_get(m->shold, task->stream_id)) != NULL) {
/* stream is done, was just waiting for this. */
task->done_done = 1;
ap_log_cerror(APLOG_MARK, APLOG_TRACE2, 0, m->c,
H2_STRM_MSG(stream, "task_done, in hold"));
if (stream->input) {
h2_beam_leave(stream->input);
}
stream_joined(m, stream);
}
else if ((stream = h2_ihash_get(m->spurge, task->stream_id)) != NULL) {
ap_log_cerror(APLOG_MARK, APLOG_WARNING, 0, m->c,
H2_STRM_LOG(APLOGNO(03517), stream, "already in spurge"));
ap_assert("stream should not be in spurge" == NULL);
}
else {
ap_log_cerror(APLOG_MARK, APLOG_WARNING, 0, m->c, APLOGNO(03518)
"h2_mplx(%s): task_done, stream not found",
task->id);
ap_assert("stream should still be available" == NULL);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now,
mpm event backport to 2.4.x up for vote).
* Fixes stream cleanup when connection throttling is in place.
* Counts stream resets by client on streams initiated by client as cause
for connection throttling.
* Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann)
* Header length is checked also on the merged value from several header instances
and results in a 431 response.'</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 pdf_summarize(
FILE *fp,
const pdf_t *pdf,
const char *name,
pdf_flag_t flags)
{
int i, j, page, n_versions, n_entries;
FILE *dst, *out;
char *dst_name, *c;
dst = NULL;
dst_name = NULL;
if (name)
{
dst_name = malloc(strlen(name) * 2 + 16);
sprintf(dst_name, "%s/%s", name, name);
if ((c = strrchr(dst_name, '.')) && (strncmp(c, ".pdf", 4) == 0))
*c = '\0';
strcat(dst_name, ".summary");
if (!(dst = fopen(dst_name, "w")))
{
ERR("Could not open file '%s' for writing\n", dst_name);
return;
}
}
/* Send output to file or stdout */
out = (dst) ? dst : stdout;
/* Count versions */
n_versions = pdf->n_xrefs;
if (n_versions && pdf->xrefs[0].is_linear)
--n_versions;
/* Ignore bad xref entry */
for (i=1; i<pdf->n_xrefs; ++i)
if (pdf->xrefs[i].end == 0)
--n_versions;
/* If we have no valid versions but linear, count that */
if (!pdf->n_xrefs || (!n_versions && pdf->xrefs[0].is_linear))
n_versions = 1;
/* Compare each object (if we dont have xref streams) */
n_entries = 0;
for (i=0; !(const int)pdf->has_xref_streams && i<pdf->n_xrefs; i++)
{
if (flags & PDF_FLAG_QUIET)
continue;
for (j=0; j<pdf->xrefs[i].n_entries; j++)
{
++n_entries;
fprintf(out,
"%s: --%c-- Version %d -- Object %d (%s)",
pdf->name,
pdf_get_object_status(pdf, i, j),
pdf->xrefs[i].version,
pdf->xrefs[i].entries[j].obj_id,
get_type(fp, pdf->xrefs[i].entries[j].obj_id,
&pdf->xrefs[i]));
/* TODO
page = get_page(pdf->xrefs[i].entries[j].obj_id, &pdf->xrefs[i]);
*/
if (0 /*page*/)
fprintf(out, " Page(%d)\n", page);
else
fprintf(out, "\n");
}
}
/* Trailing summary */
if (!(flags & PDF_FLAG_QUIET))
{
/* Let the user know that we cannot we print a per-object summary.
* If we have a 1.5 PDF using streams for xref, we have not objects
* to display, so let the user know whats up.
*/
if (pdf->has_xref_streams || !n_entries)
fprintf(out,
"%s: This PDF contains potential cross reference streams.\n"
"%s: An object summary is not available.\n",
pdf->name,
pdf->name);
fprintf(out,
"---------- %s ----------\n"
"Versions: %d\n",
pdf->name,
n_versions);
/* Count entries for summary */
if (!pdf->has_xref_streams)
for (i=0; i<pdf->n_xrefs; i++)
{
if (pdf->xrefs[i].is_linear)
continue;
n_entries = pdf->xrefs[i].n_entries;
/* If we are a linearized PDF, all versions are made from those
* objects too. So count em'
*/
if (pdf->xrefs[0].is_linear)
n_entries += pdf->xrefs[0].n_entries;
if (pdf->xrefs[i].version && n_entries)
fprintf(out,
"Version %d -- %d objects\n",
pdf->xrefs[i].version,
n_entries);
}
}
else /* Quiet output */
fprintf(out, "%s: %d\n", pdf->name, n_versions);
if (dst)
{
fclose(dst);
free(dst_name);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf'</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 pdf_load_xrefs(FILE *fp, pdf_t *pdf)
{
int i, ver, is_linear;
long pos, pos_count;
char x, *c, buf[256];
c = NULL;
/* Count number of xrefs */
pdf->n_xrefs = 0;
fseek(fp, 0, SEEK_SET);
while (get_next_eof(fp) >= 0)
++pdf->n_xrefs;
if (!pdf->n_xrefs)
return 0;
/* Load in the start/end positions */
fseek(fp, 0, SEEK_SET);
pdf->xrefs = calloc(1, sizeof(xref_t) * pdf->n_xrefs);
ver = 1;
for (i=0; i<pdf->n_xrefs; i++)
{
/* Seek to %%EOF */
if ((pos = get_next_eof(fp)) < 0)
break;
/* Set and increment the version */
pdf->xrefs[i].version = ver++;
/* Rewind until we find end of "startxref" */
pos_count = 0;
while (SAFE_F(fp, ((x = fgetc(fp)) != 'f')))
fseek(fp, pos - (++pos_count), SEEK_SET);
/* Suck in end of "startxref" to start of %%EOF */
if (pos_count >= sizeof(buf)) {
ERR("Failed to locate the startxref token. "
"This might be a corrupt PDF.\n");
return -1;
}
memset(buf, 0, sizeof(buf));
SAFE_E(fread(buf, 1, pos_count, fp), pos_count,
"Failed to read startxref.\n");
c = buf;
while (*c == ' ' || *c == '\n' || *c == '\r')
++c;
/* xref start position */
pdf->xrefs[i].start = atol(c);
/* If xref is 0 handle linear xref table */
if (pdf->xrefs[i].start == 0)
get_xref_linear_skipped(fp, &pdf->xrefs[i]);
/* Non-linear, normal operation, so just find the end of the xref */
else
{
/* xref end position */
pos = ftell(fp);
fseek(fp, pdf->xrefs[i].start, SEEK_SET);
pdf->xrefs[i].end = get_next_eof(fp);
/* Look for next EOF and xref data */
fseek(fp, pos, SEEK_SET);
}
/* Check validity */
if (!is_valid_xref(fp, pdf, &pdf->xrefs[i]))
{
is_linear = pdf->xrefs[i].is_linear;
memset(&pdf->xrefs[i], 0, sizeof(xref_t));
pdf->xrefs[i].is_linear = is_linear;
rewind(fp);
get_next_eof(fp);
continue;
}
/* Load the entries from the xref */
load_xref_entries(fp, &pdf->xrefs[i]);
}
/* Now we have all xref tables, if this is linearized, we need
* to make adjustments so that things spit out properly
*/
if (pdf->xrefs[0].is_linear)
resolve_linearized_pdf(pdf);
/* Ok now we have all xref data. Go through those versions of the
* PDF and try to obtain creator information
*/
load_creator(fp, pdf);
return pdf->n_xrefs;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf'</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 char *get_object(
FILE *fp,
int obj_id,
const xref_t *xref,
size_t *size,
int *is_stream)
{
static const int blk_sz = 256;
int i, total_sz, read_sz, n_blks, search, stream;
size_t obj_sz;
char *c, *data;
long start;
const xref_entry_t *entry;
if (size)
*size = 0;
if (is_stream)
*is_stream = 0;
start = ftell(fp);
/* Find object */
entry = NULL;
for (i=0; i<xref->n_entries; i++)
if (xref->entries[i].obj_id == obj_id)
{
entry = &xref->entries[i];
break;
}
if (!entry)
return NULL;
/* Jump to object start */
fseek(fp, entry->offset, SEEK_SET);
/* Initial allocate */
obj_sz = 0; /* Bytes in object */
total_sz = 0; /* Bytes read in */
n_blks = 1;
data = malloc(blk_sz * n_blks);
memset(data, 0, blk_sz * n_blks);
/* Suck in data */
stream = 0;
while ((read_sz = fread(data+total_sz, 1, blk_sz-1, fp)) && !ferror(fp))
{
total_sz += read_sz;
*(data + total_sz) = '\0';
if (total_sz + blk_sz >= (blk_sz * n_blks))
data = realloc(data, blk_sz * (++n_blks));
search = total_sz - read_sz;
if (search < 0)
search = 0;
if ((c = strstr(data + search, "endobj")))
{
*(c + strlen("endobj") + 1) = '\0';
obj_sz = (void *)strstr(data + search, "endobj") - (void *)data;
obj_sz += strlen("endobj") + 1;
break;
}
else if (strstr(data, "stream"))
stream = 1;
}
clearerr(fp);
fseek(fp, start, SEEK_SET);
if (size)
*size = obj_sz;
if (is_stream)
*is_stream = stream;
return data;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf'</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: pdf_t *pdf_new(const char *name)
{
const char *n;
pdf_t *pdf;
pdf = calloc(1, sizeof(pdf_t));
if (name)
{
/* Just get the file name (not path) */
if ((n = strrchr(name, '/')))
++n;
else
n = name;
pdf->name = malloc(strlen(n) + 1);
strcpy(pdf->name, n);
}
else /* !name */
{
pdf->name = malloc(strlen("Unknown") + 1);
strcpy(pdf->name, "Unknown");
}
return pdf;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf'</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 main(int argc, char **argv)
{
int i, n_valid, do_write, do_scrub;
char *c, *dname, *name;
DIR *dir;
FILE *fp;
pdf_t *pdf;
pdf_flag_t flags;
if (argc < 2)
usage();
/* Args */
do_write = do_scrub = flags = 0;
name = NULL;
for (i=1; i<argc; i++)
{
if (strncmp(argv[i], "-w", 2) == 0)
do_write = 1;
else if (strncmp(argv[i], "-i", 2) == 0)
flags |= PDF_FLAG_DISP_CREATOR;
else if (strncmp(argv[i], "-q", 2) == 0)
flags |= PDF_FLAG_QUIET;
else if (strncmp(argv[i], "-s", 2) == 0)
do_scrub = 1;
else if (argv[i][0] != '-')
name = argv[i];
else if (argv[i][0] == '-')
usage();
}
if (!name)
usage();
if (!(fp = fopen(name, "r")))
{
ERR("Could not open file '%s'\n", argv[1]);
return -1;
}
else if (!pdf_is_pdf(fp))
{
ERR("'%s' specified is not a valid PDF\n", name);
fclose(fp);
return -1;
}
/* Load PDF */
if (!(pdf = init_pdf(fp, name)))
{
fclose(fp);
return -1;
}
/* Count valid xrefs */
for (i=0, n_valid=0; i<pdf->n_xrefs; i++)
if (pdf->xrefs[i].version)
++n_valid;
/* Bail if we only have 1 valid */
if (n_valid < 2)
{
if (!(flags & (PDF_FLAG_QUIET | PDF_FLAG_DISP_CREATOR)))
printf("%s: There is only one version of this PDF\n", pdf->name);
if (do_write)
{
fclose(fp);
pdf_delete(pdf);
return 0;
}
}
dname = NULL;
if (do_write)
{
/* Create directory to place the various versions in */
if ((c = strrchr(name, '/')))
name = c + 1;
if ((c = strrchr(name, '.')))
*c = '\0';
dname = malloc(strlen(name) + 16);
sprintf(dname, "%s-versions", name);
if (!(dir = opendir(dname)))
mkdir(dname, S_IRWXU);
else
{
ERR("This directory already exists, PDF version extraction will "
"not occur.\n");
fclose(fp);
closedir(dir);
free(dname);
pdf_delete(pdf);
return -1;
}
/* Write the pdf as a pervious version */
for (i=0; i<pdf->n_xrefs; i++)
if (pdf->xrefs[i].version)
write_version(fp, name, dname, &pdf->xrefs[i]);
}
/* Generate a per-object summary */
pdf_summarize(fp, pdf, dname, flags);
/* Have we been summoned to scrub history from this PDF */
if (do_scrub)
scrub_document(fp, pdf);
/* Display extra information */
if (flags & PDF_FLAG_DISP_CREATOR)
display_creator(fp, pdf);
fclose(fp);
free(dname);
pdf_delete(pdf);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf'</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 pdf_load_pages_kids(FILE *fp, pdf_t *pdf)
{
int i, id, dummy;
char *buf, *c;
long start, sz;
start = ftell(fp);
/* Load all kids for all xref tables (versions) */
for (i=0; i<pdf->n_xrefs; i++)
{
if (pdf->xrefs[i].version && (pdf->xrefs[i].end != 0))
{
fseek(fp, pdf->xrefs[i].start, SEEK_SET);
while (SAFE_F(fp, (fgetc(fp) != 't')))
; /* Iterate to trailer */
/* Get root catalog */
sz = pdf->xrefs[i].end - ftell(fp);
buf = malloc(sz + 1);
SAFE_E(fread(buf, 1, sz, fp), sz, "Failed to load /Root.\n");
buf[sz] = '\0';
if (!(c = strstr(buf, "/Root")))
{
free(buf);
continue;
}
/* Jump to catalog (root) */
id = atoi(c + strlen("/Root") + 1);
free(buf);
buf = get_object(fp, id, &pdf->xrefs[i], NULL, &dummy);
if (!buf || !(c = strstr(buf, "/Pages")))
{
free(buf);
continue;
}
/* Start at the first Pages obj and get kids */
id = atoi(c + strlen("/Pages") + 1);
load_kids(fp, id, &pdf->xrefs[i]);
free(buf);
}
}
fseek(fp, start, SEEK_SET);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf'</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 f_midi_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
struct f_midi *midi = func_to_midi(f);
unsigned i;
int err;
/* we only set alt for MIDIStreaming interface */
if (intf != midi->ms_id)
return 0;
err = f_midi_start_ep(midi, f, midi->in_ep);
if (err)
return err;
err = f_midi_start_ep(midi, f, midi->out_ep);
if (err)
return err;
/* pre-allocate write usb requests to use on f_midi_transmit. */
while (kfifo_avail(&midi->in_req_fifo)) {
struct usb_request *req =
midi_alloc_ep_req(midi->in_ep, midi->buflen);
if (req == NULL)
return -ENOMEM;
req->length = 0;
req->complete = f_midi_complete;
kfifo_put(&midi->in_req_fifo, req);
}
/* allocate a bunch of read buffers and queue them all at once. */
for (i = 0; i < midi->qlen && err == 0; i++) {
struct usb_request *req =
midi_alloc_ep_req(midi->out_ep, midi->buflen);
if (req == NULL)
return -ENOMEM;
req->complete = f_midi_complete;
err = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC);
if (err) {
ERROR(midi, "%s: couldn't enqueue request: %d\n",
midi->out_ep->name, err);
free_ep_req(midi->out_ep, req);
return err;
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-415'], 'message': 'USB: gadget: f_midi: fixing a possible double-free in f_midi
It looks like there is a possibility of a double-free vulnerability on an
error path of the f_midi_set_alt function in the f_midi driver. If the
path is feasible then free_ep_req gets called twice:
req->complete = f_midi_complete;
err = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC);
=> ...
usb_gadget_giveback_request
=>
f_midi_complete (CALLBACK)
(inside f_midi_complete, for various cases of status)
free_ep_req(ep, req); // first kfree
if (err) {
ERROR(midi, "%s: couldn't enqueue request: %d\n",
midi->out_ep->name, err);
free_ep_req(midi->out_ep, req); // second kfree
return err;
}
The double-free possibility was introduced with commit ad0d1a058eac
("usb: gadget: f_midi: fix leak on failed to enqueue out requests").
Found by MOXCAFE tool.
Signed-off-by: Tuba Yavuz <[email protected]>
Fixes: ad0d1a058eac ("usb: gadget: f_midi: fix leak on failed to enqueue out requests")
Acked-by: Felipe Balbi <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>'</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 __dwc3_gadget_kick_transfer(struct dwc3_ep *dep)
{
struct dwc3_gadget_ep_cmd_params params;
struct dwc3_request *req;
int starting;
int ret;
u32 cmd;
if (!dwc3_calc_trbs_left(dep))
return 0;
starting = !(dep->flags & DWC3_EP_BUSY);
dwc3_prepare_trbs(dep);
req = next_request(&dep->started_list);
if (!req) {
dep->flags |= DWC3_EP_PENDING_REQUEST;
return 0;
}
memset(¶ms, 0, sizeof(params));
if (starting) {
params.param0 = upper_32_bits(req->trb_dma);
params.param1 = lower_32_bits(req->trb_dma);
cmd = DWC3_DEPCMD_STARTTRANSFER;
if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
cmd |= DWC3_DEPCMD_PARAM(dep->frame_number);
} else {
cmd = DWC3_DEPCMD_UPDATETRANSFER |
DWC3_DEPCMD_PARAM(dep->resource_index);
}
ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
if (ret < 0) {
/*
* FIXME we need to iterate over the list of requests
* here and stop, unmap, free and del each of the linked
* requests instead of what we do now.
*/
if (req->trb)
memset(req->trb, 0, sizeof(struct dwc3_trb));
dep->queued_requests--;
dwc3_gadget_giveback(dep, req, ret);
return ret;
}
dep->flags |= DWC3_EP_BUSY;
if (starting) {
dep->resource_index = dwc3_gadget_ep_get_transfer_index(dep);
WARN_ON_ONCE(!dep->resource_index);
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-667', 'CWE-189'], 'message': 'usb: dwc3: gadget: never call ->complete() from ->ep_queue()
This is a requirement which has always existed but, somehow, wasn't
reflected in the documentation and problems weren't found until now
when Tuba Yavuz found a possible deadlock happening between dwc3 and
f_hid. She described the situation as follows:
spin_lock_irqsave(&hidg->write_spinlock, flags); // first acquire
/* we our function has been disabled by host */
if (!hidg->req) {
free_ep_req(hidg->in_ep, hidg->req);
goto try_again;
}
[...]
status = usb_ep_queue(hidg->in_ep, hidg->req, GFP_ATOMIC);
=>
[...]
=> usb_gadget_giveback_request
=>
f_hidg_req_complete
=>
spin_lock_irqsave(&hidg->write_spinlock, flags); // second acquire
Note that this happens because dwc3 would call ->complete() on a
failed usb_ep_queue() due to failed Start Transfer command. This is,
anyway, a theoretical situation because dwc3 currently uses "No
Response Update Transfer" command for Bulk and Interrupt endpoints.
It's still good to make this case impossible to happen even if the "No
Reponse Update Transfer" command is changed.
Reported-by: Tuba Yavuz <[email protected]>
Signed-off-by: Felipe Balbi <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>'</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 ip6_mroute_setsockopt(struct sock *sk, int optname, char __user *optval, unsigned int optlen)
{
int ret, parent = 0;
struct mif6ctl vif;
struct mf6cctl mfc;
mifi_t mifi;
struct net *net = sock_net(sk);
struct mr6_table *mrt;
mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT);
if (!mrt)
return -ENOENT;
if (optname != MRT6_INIT) {
if (sk != mrt->mroute6_sk && !ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EACCES;
}
switch (optname) {
case MRT6_INIT:
if (sk->sk_type != SOCK_RAW ||
inet_sk(sk)->inet_num != IPPROTO_ICMPV6)
return -EOPNOTSUPP;
if (optlen < sizeof(int))
return -EINVAL;
return ip6mr_sk_init(mrt, sk);
case MRT6_DONE:
return ip6mr_sk_done(sk);
case MRT6_ADD_MIF:
if (optlen < sizeof(vif))
return -EINVAL;
if (copy_from_user(&vif, optval, sizeof(vif)))
return -EFAULT;
if (vif.mif6c_mifi >= MAXMIFS)
return -ENFILE;
rtnl_lock();
ret = mif6_add(net, mrt, &vif, sk == mrt->mroute6_sk);
rtnl_unlock();
return ret;
case MRT6_DEL_MIF:
if (optlen < sizeof(mifi_t))
return -EINVAL;
if (copy_from_user(&mifi, optval, sizeof(mifi_t)))
return -EFAULT;
rtnl_lock();
ret = mif6_delete(mrt, mifi, NULL);
rtnl_unlock();
return ret;
/*
* Manipulate the forwarding caches. These live
* in a sort of kernel/user symbiosis.
*/
case MRT6_ADD_MFC:
case MRT6_DEL_MFC:
parent = -1;
case MRT6_ADD_MFC_PROXY:
case MRT6_DEL_MFC_PROXY:
if (optlen < sizeof(mfc))
return -EINVAL;
if (copy_from_user(&mfc, optval, sizeof(mfc)))
return -EFAULT;
if (parent == 0)
parent = mfc.mf6cc_parent;
rtnl_lock();
if (optname == MRT6_DEL_MFC || optname == MRT6_DEL_MFC_PROXY)
ret = ip6mr_mfc_delete(mrt, &mfc, parent);
else
ret = ip6mr_mfc_add(net, mrt, &mfc,
sk == mrt->mroute6_sk, parent);
rtnl_unlock();
return ret;
/*
* Control PIM assert (to activate pim will activate assert)
*/
case MRT6_ASSERT:
{
int v;
if (optlen != sizeof(v))
return -EINVAL;
if (get_user(v, (int __user *)optval))
return -EFAULT;
mrt->mroute_do_assert = v;
return 0;
}
#ifdef CONFIG_IPV6_PIMSM_V2
case MRT6_PIM:
{
int v;
if (optlen != sizeof(v))
return -EINVAL;
if (get_user(v, (int __user *)optval))
return -EFAULT;
v = !!v;
rtnl_lock();
ret = 0;
if (v != mrt->mroute_do_pim) {
mrt->mroute_do_pim = v;
mrt->mroute_do_assert = v;
}
rtnl_unlock();
return ret;
}
#endif
#ifdef CONFIG_IPV6_MROUTE_MULTIPLE_TABLES
case MRT6_TABLE:
{
u32 v;
if (optlen != sizeof(u32))
return -EINVAL;
if (get_user(v, (u32 __user *)optval))
return -EFAULT;
/* "pim6reg%u" should not exceed 16 bytes (IFNAMSIZ) */
if (v != RT_TABLE_DEFAULT && v >= 100000000)
return -EINVAL;
if (sk == mrt->mroute6_sk)
return -EBUSY;
rtnl_lock();
ret = 0;
if (!ip6mr_new_table(net, v))
ret = -ENOMEM;
raw6_sk(sk)->ip6mr_table = v;
rtnl_unlock();
return ret;
}
#endif
/*
* Spurious command, or MRT6_VERSION which you cannot
* set.
*/
default:
return -ENOPROTOOPT;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'ipv6: check sk sk_type and protocol early in ip_mroute_set/getsockopt
Commit 5e1859fbcc3c ("ipv4: ipmr: various fixes and cleanups") fixed
the issue for ipv4 ipmr:
ip_mroute_setsockopt() & ip_mroute_getsockopt() should not
access/set raw_sk(sk)->ipmr_table before making sure the socket
is a raw socket, and protocol is IGMP
The same fix should be done for ipv6 ipmr as well.
This patch can fix the panic caused by overwriting the same offset
as ipmr_table as in raw_sk(sk) when accessing other type's socket
by ip_mroute_setsockopt().
Signed-off-by: Xin Long <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</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: qedi_dbg_warn(struct qedi_dbg_ctx *qedi, const char *func, u32 line,
const char *fmt, ...)
{
va_list va;
struct va_format vaf;
char nfunc[32];
memset(nfunc, 0, sizeof(nfunc));
memcpy(nfunc, func, sizeof(nfunc) - 1);
va_start(va, fmt);
vaf.fmt = fmt;
vaf.va = &va;
if (!(qedi_dbg_log & QEDI_LOG_WARN))
goto ret;
if (likely(qedi) && likely(qedi->pdev))
pr_warn("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev),
nfunc, line, qedi->host_no, &vaf);
else
pr_warn("[0000:00:00.0]:[%s:%d]: %pV", nfunc, line, &vaf);
ret:
va_end(va);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'scsi: qedi: remove memset/memcpy to nfunc and use func instead
KASAN reports this:
BUG: KASAN: global-out-of-bounds in qedi_dbg_err+0xda/0x330 [qedi]
Read of size 31 at addr ffffffffc12b0ae0 by task syz-executor.0/2429
CPU: 0 PID: 2429 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
Call Trace:
__dump_stack lib/dump_stack.c:77 [inline]
dump_stack+0xfa/0x1ce lib/dump_stack.c:113
print_address_description+0x1c4/0x270 mm/kasan/report.c:187
kasan_report+0x149/0x18d mm/kasan/report.c:317
memcpy+0x1f/0x50 mm/kasan/common.c:130
qedi_dbg_err+0xda/0x330 [qedi]
? 0xffffffffc12d0000
qedi_init+0x118/0x1000 [qedi]
? 0xffffffffc12d0000
? 0xffffffffc12d0000
? 0xffffffffc12d0000
do_one_initcall+0xfa/0x5ca init/main.c:887
do_init_module+0x204/0x5f6 kernel/module.c:3460
load_module+0x66b2/0x8570 kernel/module.c:3808
__do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902
do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f2d57e55c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000073bfa0 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 00000000200003c0 RDI: 0000000000000003
RBP: 00007f2d57e55c70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007f2d57e566bc
R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004
The buggy address belongs to the variable:
__func__.67584+0x0/0xffffffffffffd520 [qedi]
Memory state around the buggy address:
ffffffffc12b0980: fa fa fa fa 00 04 fa fa fa fa fa fa 00 00 05 fa
ffffffffc12b0a00: fa fa fa fa 00 00 04 fa fa fa fa fa 00 05 fa fa
> ffffffffc12b0a80: fa fa fa fa 00 06 fa fa fa fa fa fa 00 02 fa fa
^
ffffffffc12b0b00: fa fa fa fa 00 00 04 fa fa fa fa fa 00 00 03 fa
ffffffffc12b0b80: fa fa fa fa 00 00 02 fa fa fa fa fa 00 00 04 fa
Currently the qedi_dbg_* family of functions can overrun the end of the
source string if it is less than the destination buffer length because of
the use of a fixed sized memcpy. Remove the memset/memcpy calls to nfunc
and just use func instead as it is always a null terminated string.
Reported-by: Hulk Robot <[email protected]>
Fixes: ace7f46ba5fd ("scsi: qedi: Add QLogic FastLinQ offload iSCSI driver framework.")
Signed-off-by: YueHaibing <[email protected]>
Reviewed-by: Dan Carpenter <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>'</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: qedi_dbg_info(struct qedi_dbg_ctx *qedi, const char *func, u32 line,
u32 level, const char *fmt, ...)
{
va_list va;
struct va_format vaf;
char nfunc[32];
memset(nfunc, 0, sizeof(nfunc));
memcpy(nfunc, func, sizeof(nfunc) - 1);
va_start(va, fmt);
vaf.fmt = fmt;
vaf.va = &va;
if (!(qedi_dbg_log & level))
goto ret;
if (likely(qedi) && likely(qedi->pdev))
pr_info("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev),
nfunc, line, qedi->host_no, &vaf);
else
pr_info("[0000:00:00.0]:[%s:%d]: %pV", nfunc, line, &vaf);
ret:
va_end(va);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'scsi: qedi: remove memset/memcpy to nfunc and use func instead
KASAN reports this:
BUG: KASAN: global-out-of-bounds in qedi_dbg_err+0xda/0x330 [qedi]
Read of size 31 at addr ffffffffc12b0ae0 by task syz-executor.0/2429
CPU: 0 PID: 2429 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
Call Trace:
__dump_stack lib/dump_stack.c:77 [inline]
dump_stack+0xfa/0x1ce lib/dump_stack.c:113
print_address_description+0x1c4/0x270 mm/kasan/report.c:187
kasan_report+0x149/0x18d mm/kasan/report.c:317
memcpy+0x1f/0x50 mm/kasan/common.c:130
qedi_dbg_err+0xda/0x330 [qedi]
? 0xffffffffc12d0000
qedi_init+0x118/0x1000 [qedi]
? 0xffffffffc12d0000
? 0xffffffffc12d0000
? 0xffffffffc12d0000
do_one_initcall+0xfa/0x5ca init/main.c:887
do_init_module+0x204/0x5f6 kernel/module.c:3460
load_module+0x66b2/0x8570 kernel/module.c:3808
__do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902
do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f2d57e55c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000073bfa0 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 00000000200003c0 RDI: 0000000000000003
RBP: 00007f2d57e55c70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007f2d57e566bc
R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004
The buggy address belongs to the variable:
__func__.67584+0x0/0xffffffffffffd520 [qedi]
Memory state around the buggy address:
ffffffffc12b0980: fa fa fa fa 00 04 fa fa fa fa fa fa 00 00 05 fa
ffffffffc12b0a00: fa fa fa fa 00 00 04 fa fa fa fa fa 00 05 fa fa
> ffffffffc12b0a80: fa fa fa fa 00 06 fa fa fa fa fa fa 00 02 fa fa
^
ffffffffc12b0b00: fa fa fa fa 00 00 04 fa fa fa fa fa 00 00 03 fa
ffffffffc12b0b80: fa fa fa fa 00 00 02 fa fa fa fa fa 00 00 04 fa
Currently the qedi_dbg_* family of functions can overrun the end of the
source string if it is less than the destination buffer length because of
the use of a fixed sized memcpy. Remove the memset/memcpy calls to nfunc
and just use func instead as it is always a null terminated string.
Reported-by: Hulk Robot <[email protected]>
Fixes: ace7f46ba5fd ("scsi: qedi: Add QLogic FastLinQ offload iSCSI driver framework.")
Signed-off-by: YueHaibing <[email protected]>
Reviewed-by: Dan Carpenter <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>'</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 check_input_term(struct mixer_build *state, int id,
struct usb_audio_term *term)
{
int protocol = state->mixer->protocol;
int err;
void *p1;
memset(term, 0, sizeof(*term));
while ((p1 = find_audio_control_unit(state, id)) != NULL) {
unsigned char *hdr = p1;
term->id = id;
if (protocol == UAC_VERSION_1 || protocol == UAC_VERSION_2) {
switch (hdr[2]) {
case UAC_INPUT_TERMINAL:
if (protocol == UAC_VERSION_1) {
struct uac_input_terminal_descriptor *d = p1;
term->type = le16_to_cpu(d->wTerminalType);
term->channels = d->bNrChannels;
term->chconfig = le16_to_cpu(d->wChannelConfig);
term->name = d->iTerminal;
} else { /* UAC_VERSION_2 */
struct uac2_input_terminal_descriptor *d = p1;
/* call recursively to verify that the
* referenced clock entity is valid */
err = check_input_term(state, d->bCSourceID, term);
if (err < 0)
return err;
/* save input term properties after recursion,
* to ensure they are not overriden by the
* recursion calls */
term->id = id;
term->type = le16_to_cpu(d->wTerminalType);
term->channels = d->bNrChannels;
term->chconfig = le32_to_cpu(d->bmChannelConfig);
term->name = d->iTerminal;
}
return 0;
case UAC_FEATURE_UNIT: {
/* the header is the same for v1 and v2 */
struct uac_feature_unit_descriptor *d = p1;
id = d->bSourceID;
break; /* continue to parse */
}
case UAC_MIXER_UNIT: {
struct uac_mixer_unit_descriptor *d = p1;
term->type = UAC3_MIXER_UNIT << 16; /* virtual type */
term->channels = uac_mixer_unit_bNrChannels(d);
term->chconfig = uac_mixer_unit_wChannelConfig(d, protocol);
term->name = uac_mixer_unit_iMixer(d);
return 0;
}
case UAC_SELECTOR_UNIT:
case UAC2_CLOCK_SELECTOR: {
struct uac_selector_unit_descriptor *d = p1;
/* call recursively to retrieve the channel info */
err = check_input_term(state, d->baSourceID[0], term);
if (err < 0)
return err;
term->type = UAC3_SELECTOR_UNIT << 16; /* virtual type */
term->id = id;
term->name = uac_selector_unit_iSelector(d);
return 0;
}
case UAC1_PROCESSING_UNIT:
/* UAC2_EFFECT_UNIT */
if (protocol == UAC_VERSION_1)
term->type = UAC3_PROCESSING_UNIT << 16; /* virtual type */
else /* UAC_VERSION_2 */
term->type = UAC3_EFFECT_UNIT << 16; /* virtual type */
/* fall through */
case UAC1_EXTENSION_UNIT:
/* UAC2_PROCESSING_UNIT_V2 */
if (protocol == UAC_VERSION_1 && !term->type)
term->type = UAC3_EXTENSION_UNIT << 16; /* virtual type */
else if (protocol == UAC_VERSION_2 && !term->type)
term->type = UAC3_PROCESSING_UNIT << 16; /* virtual type */
/* fall through */
case UAC2_EXTENSION_UNIT_V2: {
struct uac_processing_unit_descriptor *d = p1;
if (protocol == UAC_VERSION_2 &&
hdr[2] == UAC2_EFFECT_UNIT) {
/* UAC2/UAC1 unit IDs overlap here in an
* uncompatible way. Ignore this unit for now.
*/
return 0;
}
if (d->bNrInPins) {
id = d->baSourceID[0];
break; /* continue to parse */
}
if (!term->type)
term->type = UAC3_EXTENSION_UNIT << 16; /* virtual type */
term->channels = uac_processing_unit_bNrChannels(d);
term->chconfig = uac_processing_unit_wChannelConfig(d, protocol);
term->name = uac_processing_unit_iProcessing(d, protocol);
return 0;
}
case UAC2_CLOCK_SOURCE: {
struct uac_clock_source_descriptor *d = p1;
term->type = UAC3_CLOCK_SOURCE << 16; /* virtual type */
term->id = id;
term->name = d->iClockSource;
return 0;
}
default:
return -ENODEV;
}
} else { /* UAC_VERSION_3 */
switch (hdr[2]) {
case UAC_INPUT_TERMINAL: {
struct uac3_input_terminal_descriptor *d = p1;
/* call recursively to verify that the
* referenced clock entity is valid */
err = check_input_term(state, d->bCSourceID, term);
if (err < 0)
return err;
/* save input term properties after recursion,
* to ensure they are not overriden by the
* recursion calls */
term->id = id;
term->type = le16_to_cpu(d->wTerminalType);
err = get_cluster_channels_v3(state, le16_to_cpu(d->wClusterDescrID));
if (err < 0)
return err;
term->channels = err;
/* REVISIT: UAC3 IT doesn't have channels cfg */
term->chconfig = 0;
term->name = le16_to_cpu(d->wTerminalDescrStr);
return 0;
}
case UAC3_FEATURE_UNIT: {
struct uac3_feature_unit_descriptor *d = p1;
id = d->bSourceID;
break; /* continue to parse */
}
case UAC3_CLOCK_SOURCE: {
struct uac3_clock_source_descriptor *d = p1;
term->type = UAC3_CLOCK_SOURCE << 16; /* virtual type */
term->id = id;
term->name = le16_to_cpu(d->wClockSourceStr);
return 0;
}
case UAC3_MIXER_UNIT: {
struct uac_mixer_unit_descriptor *d = p1;
err = uac_mixer_unit_get_channels(state, d);
if (err <= 0)
return err;
term->channels = err;
term->type = UAC3_MIXER_UNIT << 16; /* virtual type */
return 0;
}
case UAC3_SELECTOR_UNIT:
case UAC3_CLOCK_SELECTOR: {
struct uac_selector_unit_descriptor *d = p1;
/* call recursively to retrieve the channel info */
err = check_input_term(state, d->baSourceID[0], term);
if (err < 0)
return err;
term->type = UAC3_SELECTOR_UNIT << 16; /* virtual type */
term->id = id;
term->name = 0; /* TODO: UAC3 Class-specific strings */
return 0;
}
case UAC3_PROCESSING_UNIT: {
struct uac_processing_unit_descriptor *d = p1;
if (!d->bNrInPins)
return -EINVAL;
/* call recursively to retrieve the channel info */
err = check_input_term(state, d->baSourceID[0], term);
if (err < 0)
return err;
term->type = UAC3_PROCESSING_UNIT << 16; /* virtual type */
term->id = id;
term->name = 0; /* TODO: UAC3 Class-specific strings */
return 0;
}
default:
return -ENODEV;
}
}
}
return -ENODEV;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-674'], 'message': 'ALSA: usb-audio: Fix a stack buffer overflow bug in check_input_term
`check_input_term` recursively calls itself with input from
device side (e.g., uac_input_terminal_descriptor.bCSourceID)
as argument (id). In `check_input_term`, if `check_input_term`
is called with the same `id` argument as the caller, it triggers
endless recursive call, resulting kernel space stack overflow.
This patch fixes the bug by adding a bitmap to `struct mixer_build`
to keep track of the checked ids and stop the execution if some id
has been checked (similar to how parse_audio_unit handles unitid
argument).
Reported-by: Hui Peng <[email protected]>
Reported-by: Mathias Payer <[email protected]>
Signed-off-by: Hui Peng <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>'</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: xfs_fs_put_super(
struct super_block *sb)
{
struct xfs_mount *mp = XFS_M(sb);
xfs_notice(mp, "Unmounting Filesystem");
xfs_filestream_unmount(mp);
xfs_unmountfs(mp);
xfs_freesb(mp);
free_percpu(mp->m_stats.xs_stats);
xfs_destroy_percpu_counters(mp);
xfs_destroy_mount_workqueues(mp);
xfs_close_devices(mp);
xfs_free_fsname(mp);
kfree(mp);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'xfs: clear sb->s_fs_info on mount failure
We recently had an oops reported on a 4.14 kernel in
xfs_reclaim_inodes_count() where sb->s_fs_info pointed to garbage
and so the m_perag_tree lookup walked into lala land.
Essentially, the machine was under memory pressure when the mount
was being run, xfs_fs_fill_super() failed after allocating the
xfs_mount and attaching it to sb->s_fs_info. It then cleaned up and
freed the xfs_mount, but the sb->s_fs_info field still pointed to
the freed memory. Hence when the superblock shrinker then ran
it fell off the bad pointer.
With the superblock shrinker problem fixed at teh VFS level, this
stale s_fs_info pointer is still a problem - we use it
unconditionally in ->put_super when the superblock is being torn
down, and hence we can still trip over it after a ->fill_super
call failure. Hence we need to clear s_fs_info if
xfs-fs_fill_super() fails, and we need to check if it's valid in
the places it can potentially be dereferenced after a ->fill_super
failure.
Signed-Off-By: Dave Chinner <[email protected]>
Reviewed-by: Darrick J. Wong <[email protected]>
Signed-off-by: Darrick J. Wong <[email protected]>'</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: xfs_fs_fill_super(
struct super_block *sb,
void *data,
int silent)
{
struct inode *root;
struct xfs_mount *mp = NULL;
int flags = 0, error = -ENOMEM;
/*
* allocate mp and do all low-level struct initializations before we
* attach it to the super
*/
mp = xfs_mount_alloc(sb);
if (!mp)
goto out;
sb->s_fs_info = mp;
error = xfs_parseargs(mp, (char *)data);
if (error)
goto out_free_fsname;
sb_min_blocksize(sb, BBSIZE);
sb->s_xattr = xfs_xattr_handlers;
sb->s_export_op = &xfs_export_operations;
#ifdef CONFIG_XFS_QUOTA
sb->s_qcop = &xfs_quotactl_operations;
sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP | QTYPE_MASK_PRJ;
#endif
sb->s_op = &xfs_super_operations;
/*
* Delay mount work if the debug hook is set. This is debug
* instrumention to coordinate simulation of xfs mount failures with
* VFS superblock operations
*/
if (xfs_globals.mount_delay) {
xfs_notice(mp, "Delaying mount for %d seconds.",
xfs_globals.mount_delay);
msleep(xfs_globals.mount_delay * 1000);
}
if (silent)
flags |= XFS_MFSI_QUIET;
error = xfs_open_devices(mp);
if (error)
goto out_free_fsname;
error = xfs_init_mount_workqueues(mp);
if (error)
goto out_close_devices;
error = xfs_init_percpu_counters(mp);
if (error)
goto out_destroy_workqueues;
/* Allocate stats memory before we do operations that might use it */
mp->m_stats.xs_stats = alloc_percpu(struct xfsstats);
if (!mp->m_stats.xs_stats) {
error = -ENOMEM;
goto out_destroy_counters;
}
error = xfs_readsb(mp, flags);
if (error)
goto out_free_stats;
error = xfs_finish_flags(mp);
if (error)
goto out_free_sb;
error = xfs_setup_devices(mp);
if (error)
goto out_free_sb;
error = xfs_filestream_mount(mp);
if (error)
goto out_free_sb;
/*
* we must configure the block size in the superblock before we run the
* full mount process as the mount process can lookup and cache inodes.
*/
sb->s_magic = XFS_SB_MAGIC;
sb->s_blocksize = mp->m_sb.sb_blocksize;
sb->s_blocksize_bits = ffs(sb->s_blocksize) - 1;
sb->s_maxbytes = xfs_max_file_offset(sb->s_blocksize_bits);
sb->s_max_links = XFS_MAXLINK;
sb->s_time_gran = 1;
set_posix_acl_flag(sb);
/* version 5 superblocks support inode version counters. */
if (XFS_SB_VERSION_NUM(&mp->m_sb) == XFS_SB_VERSION_5)
sb->s_flags |= SB_I_VERSION;
if (mp->m_flags & XFS_MOUNT_DAX) {
xfs_warn(mp,
"DAX enabled. Warning: EXPERIMENTAL, use at your own risk");
error = bdev_dax_supported(sb, sb->s_blocksize);
if (error) {
xfs_alert(mp,
"DAX unsupported by block device. Turning off DAX.");
mp->m_flags &= ~XFS_MOUNT_DAX;
}
if (xfs_sb_version_hasreflink(&mp->m_sb)) {
xfs_alert(mp,
"DAX and reflink cannot be used together!");
error = -EINVAL;
goto out_filestream_unmount;
}
}
if (mp->m_flags & XFS_MOUNT_DISCARD) {
struct request_queue *q = bdev_get_queue(sb->s_bdev);
if (!blk_queue_discard(q)) {
xfs_warn(mp, "mounting with \"discard\" option, but "
"the device does not support discard");
mp->m_flags &= ~XFS_MOUNT_DISCARD;
}
}
if (xfs_sb_version_hasreflink(&mp->m_sb) && mp->m_sb.sb_rblocks) {
xfs_alert(mp,
"reflink not compatible with realtime device!");
error = -EINVAL;
goto out_filestream_unmount;
}
if (xfs_sb_version_hasrmapbt(&mp->m_sb) && mp->m_sb.sb_rblocks) {
xfs_alert(mp,
"reverse mapping btree not compatible with realtime device!");
error = -EINVAL;
goto out_filestream_unmount;
}
error = xfs_mountfs(mp);
if (error)
goto out_filestream_unmount;
root = igrab(VFS_I(mp->m_rootip));
if (!root) {
error = -ENOENT;
goto out_unmount;
}
sb->s_root = d_make_root(root);
if (!sb->s_root) {
error = -ENOMEM;
goto out_unmount;
}
return 0;
out_filestream_unmount:
xfs_filestream_unmount(mp);
out_free_sb:
xfs_freesb(mp);
out_free_stats:
free_percpu(mp->m_stats.xs_stats);
out_destroy_counters:
xfs_destroy_percpu_counters(mp);
out_destroy_workqueues:
xfs_destroy_mount_workqueues(mp);
out_close_devices:
xfs_close_devices(mp);
out_free_fsname:
xfs_free_fsname(mp);
kfree(mp);
out:
return error;
out_unmount:
xfs_filestream_unmount(mp);
xfs_unmountfs(mp);
goto out_free_sb;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'xfs: clear sb->s_fs_info on mount failure
We recently had an oops reported on a 4.14 kernel in
xfs_reclaim_inodes_count() where sb->s_fs_info pointed to garbage
and so the m_perag_tree lookup walked into lala land.
Essentially, the machine was under memory pressure when the mount
was being run, xfs_fs_fill_super() failed after allocating the
xfs_mount and attaching it to sb->s_fs_info. It then cleaned up and
freed the xfs_mount, but the sb->s_fs_info field still pointed to
the freed memory. Hence when the superblock shrinker then ran
it fell off the bad pointer.
With the superblock shrinker problem fixed at teh VFS level, this
stale s_fs_info pointer is still a problem - we use it
unconditionally in ->put_super when the superblock is being torn
down, and hence we can still trip over it after a ->fill_super
call failure. Hence we need to clear s_fs_info if
xfs-fs_fill_super() fails, and we need to check if it's valid in
the places it can potentially be dereferenced after a ->fill_super
failure.
Signed-Off-By: Dave Chinner <[email protected]>
Reviewed-by: Darrick J. Wong <[email protected]>
Signed-off-by: Darrick J. Wong <[email protected]>'</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 ath6kl_usb_free_urb_to_pipe(struct ath6kl_usb_pipe *pipe,
struct ath6kl_urb_context *urb_context)
{
unsigned long flags;
spin_lock_irqsave(&pipe->ar_usb->cs_lock, flags);
pipe->urb_cnt++;
list_add(&urb_context->link, &pipe->urb_list_head);
spin_unlock_irqrestore(&pipe->ar_usb->cs_lock, flags);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'ath6kl: fix a NULL-ptr-deref bug in ath6kl_usb_alloc_urb_from_pipe()
The `ar_usb` field of `ath6kl_usb_pipe_usb_pipe` objects
are initialized to point to the containing `ath6kl_usb` object
according to endpoint descriptors read from the device side, as shown
below in `ath6kl_usb_setup_pipe_resources`:
for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
endpoint = &iface_desc->endpoint[i].desc;
// get the address from endpoint descriptor
pipe_num = ath6kl_usb_get_logical_pipe_num(ar_usb,
endpoint->bEndpointAddress,
&urbcount);
......
// select the pipe object
pipe = &ar_usb->pipes[pipe_num];
// initialize the ar_usb field
pipe->ar_usb = ar_usb;
}
The driver assumes that the addresses reported in endpoint
descriptors from device side to be complete. If a device is
malicious and does not report complete addresses, it may trigger
NULL-ptr-deref `ath6kl_usb_alloc_urb_from_pipe` and
`ath6kl_usb_free_urb_to_pipe`.
This patch fixes the bug by preventing potential NULL-ptr-deref
(CVE-2019-15098).
Signed-off-by: Hui Peng <[email protected]>
Reported-by: Hui Peng <[email protected]>
Reported-by: Mathias Payer <[email protected]>
Reviewed-by: Greg Kroah-Hartman <[email protected]>
Signed-off-by: Kalle Valo <[email protected]>'</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: ath10k_usb_alloc_urb_from_pipe(struct ath10k_usb_pipe *pipe)
{
struct ath10k_urb_context *urb_context = NULL;
unsigned long flags;
spin_lock_irqsave(&pipe->ar_usb->cs_lock, flags);
if (!list_empty(&pipe->urb_list_head)) {
urb_context = list_first_entry(&pipe->urb_list_head,
struct ath10k_urb_context, link);
list_del(&urb_context->link);
pipe->urb_cnt--;
}
spin_unlock_irqrestore(&pipe->ar_usb->cs_lock, flags);
return urb_context;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'ath10k: Fix a NULL-ptr-deref bug in ath10k_usb_alloc_urb_from_pipe
The `ar_usb` field of `ath10k_usb_pipe_usb_pipe` objects
are initialized to point to the containing `ath10k_usb` object
according to endpoint descriptors read from the device side, as shown
below in `ath10k_usb_setup_pipe_resources`:
for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
endpoint = &iface_desc->endpoint[i].desc;
// get the address from endpoint descriptor
pipe_num = ath10k_usb_get_logical_pipe_num(ar_usb,
endpoint->bEndpointAddress,
&urbcount);
......
// select the pipe object
pipe = &ar_usb->pipes[pipe_num];
// initialize the ar_usb field
pipe->ar_usb = ar_usb;
}
The driver assumes that the addresses reported in endpoint
descriptors from device side to be complete. If a device is
malicious and does not report complete addresses, it may trigger
NULL-ptr-deref `ath10k_usb_alloc_urb_from_pipe` and
`ath10k_usb_free_urb_to_pipe`.
This patch fixes the bug by preventing potential NULL-ptr-deref.
Signed-off-by: Hui Peng <[email protected]>
Reported-by: Hui Peng <[email protected]>
Reported-by: Mathias Payer <[email protected]>
Reviewed-by: Greg Kroah-Hartman <[email protected]>
[groeck: Add driver tag to subject, fix build warning]
Signed-off-by: Guenter Roeck <[email protected]>
Signed-off-by: Kalle Valo <[email protected]>'</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 dvb_usb_device_exit(struct usb_interface *intf)
{
struct dvb_usb_device *d = usb_get_intfdata(intf);
const char *name = "generic DVB-USB module";
usb_set_intfdata(intf, NULL);
if (d != NULL && d->desc != NULL) {
name = d->desc->name;
dvb_usb_exit(d);
}
info("%s successfully deinitialized and disconnected.", name);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'media: dvb: usb: fix use after free in dvb_usb_device_exit
dvb_usb_device_exit() frees and uses the device name in that order.
Fix by storing the name in a buffer before freeing it.
Signed-off-by: Oliver Neukum <[email protected]>
Reported-by: [email protected]
Signed-off-by: Sean Young <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>'</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: snd_info_create_entry(const char *name, struct snd_info_entry *parent,
struct module *module)
{
struct snd_info_entry *entry;
entry = kzalloc(sizeof(*entry), GFP_KERNEL);
if (entry == NULL)
return NULL;
entry->name = kstrdup(name, GFP_KERNEL);
if (entry->name == NULL) {
kfree(entry);
return NULL;
}
entry->mode = S_IFREG | 0444;
entry->content = SNDRV_INFO_CONTENT_TEXT;
mutex_init(&entry->access);
INIT_LIST_HEAD(&entry->children);
INIT_LIST_HEAD(&entry->list);
entry->parent = parent;
entry->module = module;
if (parent)
list_add_tail(&entry->list, &parent->children);
return entry;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'ALSA: info: Fix racy addition/deletion of nodes
The ALSA proc helper manages the child nodes in a linked list, but its
addition and deletion is done without any lock. This leads to a
corruption if they are operated concurrently. Usually this isn't a
problem because the proc entries are added sequentially in the driver
probe procedure itself. But the card registrations are done often
asynchronously, and the crash could be actually reproduced with
syzkaller.
This patch papers over it by protecting the link addition and deletion
with the parent's mutex. There is "access" mutex that is used for the
file access, and this can be reused for this purpose as well.
Reported-by: [email protected]
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>'</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 radeon_atom_get_tv_timings(struct radeon_device *rdev, int index,
struct drm_display_mode *mode)
{
struct radeon_mode_info *mode_info = &rdev->mode_info;
ATOM_ANALOG_TV_INFO *tv_info;
ATOM_ANALOG_TV_INFO_V1_2 *tv_info_v1_2;
ATOM_DTD_FORMAT *dtd_timings;
int data_index = GetIndexIntoMasterTable(DATA, AnalogTV_Info);
u8 frev, crev;
u16 data_offset, misc;
if (!atom_parse_data_header(mode_info->atom_context, data_index, NULL,
&frev, &crev, &data_offset))
return false;
switch (crev) {
case 1:
tv_info = (ATOM_ANALOG_TV_INFO *)(mode_info->atom_context->bios + data_offset);
if (index > MAX_SUPPORTED_TV_TIMING)
return false;
mode->crtc_htotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Total);
mode->crtc_hdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Disp);
mode->crtc_hsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart);
mode->crtc_hsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart) +
le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncWidth);
mode->crtc_vtotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Total);
mode->crtc_vdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Disp);
mode->crtc_vsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart);
mode->crtc_vsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart) +
le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncWidth);
mode->flags = 0;
misc = le16_to_cpu(tv_info->aModeTimings[index].susModeMiscInfo.usAccess);
if (misc & ATOM_VSYNC_POLARITY)
mode->flags |= DRM_MODE_FLAG_NVSYNC;
if (misc & ATOM_HSYNC_POLARITY)
mode->flags |= DRM_MODE_FLAG_NHSYNC;
if (misc & ATOM_COMPOSITESYNC)
mode->flags |= DRM_MODE_FLAG_CSYNC;
if (misc & ATOM_INTERLACE)
mode->flags |= DRM_MODE_FLAG_INTERLACE;
if (misc & ATOM_DOUBLE_CLOCK_MODE)
mode->flags |= DRM_MODE_FLAG_DBLSCAN;
mode->clock = le16_to_cpu(tv_info->aModeTimings[index].usPixelClock) * 10;
if (index == 1) {
/* PAL timings appear to have wrong values for totals */
mode->crtc_htotal -= 1;
mode->crtc_vtotal -= 1;
}
break;
case 2:
tv_info_v1_2 = (ATOM_ANALOG_TV_INFO_V1_2 *)(mode_info->atom_context->bios + data_offset);
if (index > MAX_SUPPORTED_TV_TIMING_V1_2)
return false;
dtd_timings = &tv_info_v1_2->aModeTimings[index];
mode->crtc_htotal = le16_to_cpu(dtd_timings->usHActive) +
le16_to_cpu(dtd_timings->usHBlanking_Time);
mode->crtc_hdisplay = le16_to_cpu(dtd_timings->usHActive);
mode->crtc_hsync_start = le16_to_cpu(dtd_timings->usHActive) +
le16_to_cpu(dtd_timings->usHSyncOffset);
mode->crtc_hsync_end = mode->crtc_hsync_start +
le16_to_cpu(dtd_timings->usHSyncWidth);
mode->crtc_vtotal = le16_to_cpu(dtd_timings->usVActive) +
le16_to_cpu(dtd_timings->usVBlanking_Time);
mode->crtc_vdisplay = le16_to_cpu(dtd_timings->usVActive);
mode->crtc_vsync_start = le16_to_cpu(dtd_timings->usVActive) +
le16_to_cpu(dtd_timings->usVSyncOffset);
mode->crtc_vsync_end = mode->crtc_vsync_start +
le16_to_cpu(dtd_timings->usVSyncWidth);
mode->flags = 0;
misc = le16_to_cpu(dtd_timings->susModeMiscInfo.usAccess);
if (misc & ATOM_VSYNC_POLARITY)
mode->flags |= DRM_MODE_FLAG_NVSYNC;
if (misc & ATOM_HSYNC_POLARITY)
mode->flags |= DRM_MODE_FLAG_NHSYNC;
if (misc & ATOM_COMPOSITESYNC)
mode->flags |= DRM_MODE_FLAG_CSYNC;
if (misc & ATOM_INTERLACE)
mode->flags |= DRM_MODE_FLAG_INTERLACE;
if (misc & ATOM_DOUBLE_CLOCK_MODE)
mode->flags |= DRM_MODE_FLAG_DBLSCAN;
mode->clock = le16_to_cpu(dtd_timings->usPixClk) * 10;
break;
}
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-193'], 'message': 'drivers/gpu/drm/radeon/radeon_atombios.c: range check issues
This change makes the array larger, "MAX_SUPPORTED_TV_TIMING_V1_2" is 3
and the original size "MAX_SUPPORTED_TV_TIMING" is 2.
Also there were checks that were off by one.
Signed-off-by: Dan Carpenter <[email protected]>
Acked-by: Alex Deucher <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Dave Airlie <[email protected]>'</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 mlx4_register_vlan(struct mlx4_dev *dev, u8 port, u16 vlan, int *index)
{
struct mlx4_vlan_table *table = &mlx4_priv(dev)->port[port].vlan_table;
int i, err = 0;
int free = -1;
mutex_lock(&table->mutex);
for (i = MLX4_VLAN_REGULAR; i < MLX4_MAX_VLAN_NUM; i++) {
if (free < 0 && (table->refs[i] == 0)) {
free = i;
continue;
}
if (table->refs[i] &&
(vlan == (MLX4_VLAN_MASK &
be32_to_cpu(table->entries[i])))) {
/* Vlan already registered, increase refernce count */
*index = i;
++table->refs[i];
goto out;
}
}
if (table->total == table->max) {
/* No free vlan entries */
err = -ENOSPC;
goto out;
}
/* Register new MAC */
table->refs[free] = 1;
table->entries[free] = cpu_to_be32(vlan | MLX4_VLAN_VALID);
err = mlx4_set_port_vlan_table(dev, port, table->entries);
if (unlikely(err)) {
mlx4_warn(dev, "Failed adding vlan: %u\n", vlan);
table->refs[free] = 0;
table->entries[free] = 0;
goto out;
}
*index = free;
++table->total;
out:
mutex_unlock(&table->mutex);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'mlx4_en: Fix out of bounds array access
When searching for a free entry in either mlx4_register_vlan() or
mlx4_register_mac(), and there is no free entry, the loop terminates without
updating the local variable free thus causing out of array bounds access. Fix
this by adding a proper check outside the loop.
Signed-off-by: Eli Cohen <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</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: mwifiex_set_uap_rates(struct mwifiex_uap_bss_param *bss_cfg,
struct cfg80211_ap_settings *params)
{
struct ieee_types_header *rate_ie;
int var_offset = offsetof(struct ieee80211_mgmt, u.beacon.variable);
const u8 *var_pos = params->beacon.head + var_offset;
int len = params->beacon.head_len - var_offset;
u8 rate_len = 0;
rate_ie = (void *)cfg80211_find_ie(WLAN_EID_SUPP_RATES, var_pos, len);
if (rate_ie) {
memcpy(bss_cfg->rates, rate_ie + 1, rate_ie->len);
rate_len = rate_ie->len;
}
rate_ie = (void *)cfg80211_find_ie(WLAN_EID_EXT_SUPP_RATES,
params->beacon.tail,
params->beacon.tail_len);
if (rate_ie)
memcpy(bss_cfg->rates + rate_len, rate_ie + 1, rate_ie->len);
return;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'mwifiex: Fix three heap overflow at parsing element in cfg80211_ap_settings
mwifiex_update_vs_ie(),mwifiex_set_uap_rates() and
mwifiex_set_wmm_params() call memcpy() without checking
the destination size.Since the source is given from
user-space, this may trigger a heap buffer overflow.
Fix them by putting the length check before performing memcpy().
This fix addresses CVE-2019-14814,CVE-2019-14815,CVE-2019-14816.
Signed-off-by: Wen Huang <[email protected]>
Acked-by: Ganapathi Bhat <[email protected]>
Signed-off-by: Kalle Valo <[email protected]>'</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 cpia2_usb_disconnect(struct usb_interface *intf)
{
struct camera_data *cam = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
DBG("Stopping stream\n");
cpia2_usb_stream_stop(cam);
mutex_lock(&cam->v4l2_lock);
DBG("Unregistering camera\n");
cpia2_unregister_camera(cam);
v4l2_device_disconnect(&cam->v4l2_dev);
mutex_unlock(&cam->v4l2_lock);
v4l2_device_put(&cam->v4l2_dev);
if(cam->buffers) {
DBG("Wakeup waiting processes\n");
cam->curbuff->status = FRAME_READY;
cam->curbuff->length = 0;
wake_up_interruptible(&cam->wq_stream);
}
LOG("CPiA2 camera disconnected.\n");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'media: cpia2_usb: first wake up, then free in disconnect
Kasan reported a use after free in cpia2_usb_disconnect()
It first freed everything and then woke up those waiting.
The reverse order is correct.
Fixes: 6c493f8b28c67 ("[media] cpia2: major overhaul to get it in a working state again")
Signed-off-by: Oliver Neukum <[email protected]>
Reported-by: [email protected]
Signed-off-by: Hans Verkuil <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>'</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 zr364xx_vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct zr364xx_camera *cam = video_drvdata(file);
strscpy(cap->driver, DRIVER_DESC, sizeof(cap->driver));
strscpy(cap->card, cam->udev->product, sizeof(cap->card));
strscpy(cap->bus_info, dev_name(&cam->udev->dev),
sizeof(cap->bus_info));
cap->device_caps = V4L2_CAP_VIDEO_CAPTURE |
V4L2_CAP_READWRITE |
V4L2_CAP_STREAMING;
cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'media: usb:zr364xx:Fix KASAN:null-ptr-deref Read in zr364xx_vidioc_querycap
SyzKaller hit the null pointer deref while reading from uninitialized
udev->product in zr364xx_vidioc_querycap().
==================================================================
BUG: KASAN: null-ptr-deref in read_word_at_a_time+0xe/0x20
include/linux/compiler.h:274
Read of size 1 at addr 0000000000000000 by task v4l_id/5287
CPU: 1 PID: 5287 Comm: v4l_id Not tainted 5.1.0-rc3-319004-g43151d6 #6
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS
Google 01/01/2011
Call Trace:
__dump_stack lib/dump_stack.c:77 [inline]
dump_stack+0xe8/0x16e lib/dump_stack.c:113
kasan_report.cold+0x5/0x3c mm/kasan/report.c:321
read_word_at_a_time+0xe/0x20 include/linux/compiler.h:274
strscpy+0x8a/0x280 lib/string.c:207
zr364xx_vidioc_querycap+0xb5/0x210 drivers/media/usb/zr364xx/zr364xx.c:706
v4l_querycap+0x12b/0x340 drivers/media/v4l2-core/v4l2-ioctl.c:1062
__video_do_ioctl+0x5bb/0xb40 drivers/media/v4l2-core/v4l2-ioctl.c:2874
video_usercopy+0x44e/0xf00 drivers/media/v4l2-core/v4l2-ioctl.c:3056
v4l2_ioctl+0x14e/0x1a0 drivers/media/v4l2-core/v4l2-dev.c:364
vfs_ioctl fs/ioctl.c:46 [inline]
file_ioctl fs/ioctl.c:509 [inline]
do_vfs_ioctl+0xced/0x12f0 fs/ioctl.c:696
ksys_ioctl+0xa0/0xc0 fs/ioctl.c:713
__do_sys_ioctl fs/ioctl.c:720 [inline]
__se_sys_ioctl fs/ioctl.c:718 [inline]
__x64_sys_ioctl+0x74/0xb0 fs/ioctl.c:718
do_syscall_64+0xcf/0x4f0 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x7f3b56d8b347
Code: 90 90 90 48 8b 05 f1 fa 2a 00 64 c7 00 26 00 00 00 48 c7 c0 ff ff ff
ff c3 90 90 90 90 90 90 90 90 90 90 b8 10 00 00 00 0f 05 <48> 3d 01 f0 ff
ff 73 01 c3 48 8b 0d c1 fa 2a 00 31 d2 48 29 c2 64
RSP: 002b:00007ffe005d5d68 EFLAGS: 00000202 ORIG_RAX: 0000000000000010
RAX: ffffffffffffffda RBX: 0000000000000003 RCX: 00007f3b56d8b347
RDX: 00007ffe005d5d70 RSI: 0000000080685600 RDI: 0000000000000003
RBP: 0000000000000000 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000202 R12: 0000000000400884
R13: 00007ffe005d5ec0 R14: 0000000000000000 R15: 0000000000000000
==================================================================
For this device udev->product is not initialized and accessing it causes a NULL pointer deref.
The fix is to check for NULL before strscpy() and copy empty string, if
product is NULL
Reported-by: [email protected]
Signed-off-by: Vandana BN <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>'</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 sisusb_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_device *dev = interface_to_usbdev(intf);
struct sisusb_usb_data *sisusb;
int retval = 0, i;
dev_info(&dev->dev, "USB2VGA dongle found at address %d\n",
dev->devnum);
/* Allocate memory for our private */
sisusb = kzalloc(sizeof(*sisusb), GFP_KERNEL);
if (!sisusb)
return -ENOMEM;
kref_init(&sisusb->kref);
mutex_init(&(sisusb->lock));
/* Register device */
retval = usb_register_dev(intf, &usb_sisusb_class);
if (retval) {
dev_err(&sisusb->sisusb_dev->dev,
"Failed to get a minor for device %d\n",
dev->devnum);
retval = -ENODEV;
goto error_1;
}
sisusb->sisusb_dev = dev;
sisusb->minor = intf->minor;
sisusb->vrambase = SISUSB_PCI_MEMBASE;
sisusb->mmiobase = SISUSB_PCI_MMIOBASE;
sisusb->mmiosize = SISUSB_PCI_MMIOSIZE;
sisusb->ioportbase = SISUSB_PCI_IOPORTBASE;
/* Everything else is zero */
/* Allocate buffers */
sisusb->ibufsize = SISUSB_IBUF_SIZE;
sisusb->ibuf = kmalloc(SISUSB_IBUF_SIZE, GFP_KERNEL);
if (!sisusb->ibuf) {
retval = -ENOMEM;
goto error_2;
}
sisusb->numobufs = 0;
sisusb->obufsize = SISUSB_OBUF_SIZE;
for (i = 0; i < NUMOBUFS; i++) {
sisusb->obuf[i] = kmalloc(SISUSB_OBUF_SIZE, GFP_KERNEL);
if (!sisusb->obuf[i]) {
if (i == 0) {
retval = -ENOMEM;
goto error_3;
}
break;
}
sisusb->numobufs++;
}
/* Allocate URBs */
sisusb->sisurbin = usb_alloc_urb(0, GFP_KERNEL);
if (!sisusb->sisurbin) {
retval = -ENOMEM;
goto error_3;
}
sisusb->completein = 1;
for (i = 0; i < sisusb->numobufs; i++) {
sisusb->sisurbout[i] = usb_alloc_urb(0, GFP_KERNEL);
if (!sisusb->sisurbout[i]) {
retval = -ENOMEM;
goto error_4;
}
sisusb->urbout_context[i].sisusb = (void *)sisusb;
sisusb->urbout_context[i].urbindex = i;
sisusb->urbstatus[i] = 0;
}
dev_info(&sisusb->sisusb_dev->dev, "Allocated %d output buffers\n",
sisusb->numobufs);
#ifdef CONFIG_USB_SISUSBVGA_CON
/* Allocate our SiS_Pr */
sisusb->SiS_Pr = kmalloc(sizeof(struct SiS_Private), GFP_KERNEL);
if (!sisusb->SiS_Pr) {
retval = -ENOMEM;
goto error_4;
}
#endif
/* Do remaining init stuff */
init_waitqueue_head(&sisusb->wait_q);
usb_set_intfdata(intf, sisusb);
usb_get_dev(sisusb->sisusb_dev);
sisusb->present = 1;
if (dev->speed == USB_SPEED_HIGH || dev->speed >= USB_SPEED_SUPER) {
int initscreen = 1;
#ifdef CONFIG_USB_SISUSBVGA_CON
if (sisusb_first_vc > 0 && sisusb_last_vc > 0 &&
sisusb_first_vc <= sisusb_last_vc &&
sisusb_last_vc <= MAX_NR_CONSOLES)
initscreen = 0;
#endif
if (sisusb_init_gfxdevice(sisusb, initscreen))
dev_err(&sisusb->sisusb_dev->dev,
"Failed to early initialize device\n");
} else
dev_info(&sisusb->sisusb_dev->dev,
"Not attached to USB 2.0 hub, deferring init\n");
sisusb->ready = 1;
#ifdef SISUSBENDIANTEST
dev_dbg(&sisusb->sisusb_dev->dev, "*** RWTEST ***\n");
sisusb_testreadwrite(sisusb);
dev_dbg(&sisusb->sisusb_dev->dev, "*** RWTEST END ***\n");
#endif
#ifdef CONFIG_USB_SISUSBVGA_CON
sisusb_console_init(sisusb, sisusb_first_vc, sisusb_last_vc);
#endif
return 0;
error_4:
sisusb_free_urbs(sisusb);
error_3:
sisusb_free_buffers(sisusb);
error_2:
usb_deregister_dev(intf, &usb_sisusb_class);
error_1:
kfree(sisusb);
return retval;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'USB: sisusbvga: fix oops in error path of sisusb_probe
The pointer used to log a failure of usb_register_dev() must
be set before the error is logged.
v2: fix that minor is not available before registration
Signed-off-by: oliver Neukum <[email protected]>
Reported-by: [email protected]
Fixes: 7b5cd5fefbe02 ("USB: SisUSB2VGA: Convert printk to dev_* macros")
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>'</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: Status V2UserDocumentParser::checkValidUserDocument(const BSONObj& doc) const {
BSONElement userElement = doc[AuthorizationManager::USER_NAME_FIELD_NAME];
BSONElement userDBElement = doc[AuthorizationManager::USER_DB_FIELD_NAME];
BSONElement credentialsElement = doc[CREDENTIALS_FIELD_NAME];
BSONElement rolesElement = doc[ROLES_FIELD_NAME];
// Validate the "user" element.
if (userElement.type() != String)
return _badValue("User document needs 'user' field to be a string");
if (userElement.valueStringData().empty())
return _badValue("User document needs 'user' field to be non-empty");
// Validate the "db" element
if (userDBElement.type() != String || userDBElement.valueStringData().empty()) {
return _badValue("User document needs 'db' field to be a non-empty string");
}
StringData userDBStr = userDBElement.valueStringData();
if (!NamespaceString::validDBName(userDBStr, NamespaceString::DollarInDbNameBehavior::Allow) &&
userDBStr != "$external") {
return _badValue(mongoutils::str::stream() << "'" << userDBStr
<< "' is not a valid value for the db field.");
}
// Validate the "credentials" element
if (credentialsElement.eoo()) {
return _badValue("User document needs 'credentials' object");
}
if (credentialsElement.type() != Object) {
return _badValue("User document needs 'credentials' field to be an object");
}
BSONObj credentialsObj = credentialsElement.Obj();
if (credentialsObj.isEmpty()) {
return _badValue("User document needs 'credentials' field to be a non-empty object");
}
if (userDBStr == "$external") {
BSONElement externalElement = credentialsObj[MONGODB_EXTERNAL_CREDENTIAL_FIELD_NAME];
if (externalElement.eoo() || externalElement.type() != Bool || !externalElement.Bool()) {
return _badValue(
"User documents for users defined on '$external' must have "
"'credentials' field set to {external: true}");
}
} else {
const auto validateScram = [&credentialsObj](const auto& fieldName) {
auto scramElement = credentialsObj[fieldName];
if (scramElement.eoo()) {
return Status(ErrorCodes::NoSuchKey,
str::stream() << fieldName << " does not exist");
}
if (scramElement.type() != Object) {
return _badValue(str::stream() << fieldName
<< " credential must be an object, if present");
}
return Status::OK();
};
const auto sha1status = validateScram(SCRAMSHA1_CREDENTIAL_FIELD_NAME);
if (!sha1status.isOK() && (sha1status.code() != ErrorCodes::NoSuchKey)) {
return sha1status;
}
const auto sha256status = validateScram(SCRAMSHA256_CREDENTIAL_FIELD_NAME);
if (!sha256status.isOK() && (sha256status.code() != ErrorCodes::NoSuchKey)) {
return sha256status;
}
if (!sha1status.isOK() && !sha256status.isOK()) {
return _badValue(
"User document must provide credentials for all "
"non-external users");
}
}
// Validate the "roles" element.
Status status = _checkV2RolesArray(rolesElement);
if (!status.isOK())
return status;
// Validate the "authenticationRestrictions" element.
status = initializeAuthenticationRestrictionsFromUserDocument(doc, nullptr);
if (!status.isOK()) {
return status;
}
return Status::OK();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-613'], 'message': 'SERVER-38984 Validate unique User ID on UserCache hit'</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: Status AuthorizationManagerImpl::_initializeUserFromPrivilegeDocument(User* user,
const BSONObj& privDoc) {
V2UserDocumentParser parser;
std::string userName = parser.extractUserNameFromUserDocument(privDoc);
if (userName != user->getName().getUser()) {
return Status(ErrorCodes::BadValue,
mongoutils::str::stream() << "User name from privilege document \""
<< userName
<< "\" doesn't match name of provided User \""
<< user->getName().getUser()
<< "\"");
}
Status status = parser.initializeUserCredentialsFromUserDocument(user, privDoc);
if (!status.isOK()) {
return status;
}
status = parser.initializeUserRolesFromUserDocument(privDoc, user);
if (!status.isOK()) {
return status;
}
status = parser.initializeUserIndirectRolesFromUserDocument(privDoc, user);
if (!status.isOK()) {
return status;
}
status = parser.initializeUserPrivilegesFromUserDocument(privDoc, user);
if (!status.isOK()) {
return status;
}
status = parser.initializeAuthenticationRestrictionsFromUserDocument(privDoc, user);
if (!status.isOK()) {
return status;
}
return Status::OK();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-613'], 'message': 'SERVER-38984 Validate unique User ID on UserCache hit'</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: const std::array<unsigned char, 16> md5() const {
int len = 0;
const char* data = nullptr;
if (type() == BinData && binDataType() == BinDataType::MD5Type)
data = binData(len);
uassert(40437, "md5 must be a 16-byte binary field with MD5 (5) subtype", len == 16);
std::array<unsigned char, 16> result;
memcpy(&result, data, len);
return result;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-613'], 'message': 'SERVER-38984 Validate unique User ID on UserCache hit'</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 AuthorizationSessionImpl::_refreshUserInfoAsNeeded(OperationContext* opCtx) {
AuthorizationManager& authMan = getAuthorizationManager();
UserSet::iterator it = _authenticatedUsers.begin();
while (it != _authenticatedUsers.end()) {
User* user = *it;
if (!user->isValid()) {
// Make a good faith effort to acquire an up-to-date user object, since the one
// we've cached is marked "out-of-date."
UserName name = user->getName();
User* updatedUser;
Status status = authMan.acquireUser(opCtx, name, &updatedUser);
// Take out a lock on the client here to ensure that no one reads while
// _authenticatedUsers is being modified.
stdx::lock_guard<Client> lk(*opCtx->getClient());
switch (status.code()) {
case ErrorCodes::OK: {
// Verify the updated user object's authentication restrictions.
UserHolder userHolder(user, UserReleaser(&authMan, &_authenticatedUsers, it));
UserHolder updatedUserHolder(updatedUser, UserReleaser(&authMan));
try {
const auto& restrictionSet =
updatedUserHolder->getRestrictions(); // Owned by updatedUser
invariant(opCtx->getClient());
Status restrictionStatus = restrictionSet.validate(
RestrictionEnvironment::get(*opCtx->getClient()));
if (!restrictionStatus.isOK()) {
log() << "Removed user " << name
<< " with unmet authentication restrictions from session cache of"
<< " user information. Restriction failed because: "
<< restrictionStatus.reason();
// If we remove from the UserSet, we cannot increment the iterator.
continue;
}
} catch (...) {
log() << "Evaluating authentication restrictions for " << name
<< " resulted in an unknown exception. Removing user from the"
<< " session cache.";
continue;
}
// Success! Replace the old User object with the updated one.
fassert(17067,
_authenticatedUsers.replaceAt(it, updatedUserHolder.release()) ==
userHolder.get());
LOG(1) << "Updated session cache of user information for " << name;
break;
}
case ErrorCodes::UserNotFound: {
// User does not exist anymore; remove it from _authenticatedUsers.
fassert(17068, _authenticatedUsers.removeAt(it) == user);
authMan.releaseUser(user);
log() << "Removed deleted user " << name
<< " from session cache of user information.";
continue; // No need to advance "it" in this case.
}
case ErrorCodes::UnsupportedFormat: {
// An auth subsystem has explicitly indicated a failure.
fassert(40555, _authenticatedUsers.removeAt(it) == user);
authMan.releaseUser(user);
log() << "Removed user " << name
<< " from session cache of user information because of refresh failure:"
<< " '" << status << "'.";
continue; // No need to advance "it" in this case.
}
default:
// Unrecognized error; assume that it's transient, and continue working with the
// out-of-date privilege data.
warning() << "Could not fetch updated user privilege information for " << name
<< "; continuing to use old information. Reason is "
<< redact(status);
break;
}
}
++it;
}
_buildAuthenticatedRolesVector();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-613'], 'message': 'SERVER-38984 Validate unique User ID on UserCache hit
(cherry picked from commit e55d6e2292e5dbe2f97153251d8193d1cc89f5d7)'</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: Status AuthorizationManager::_initializeUserFromPrivilegeDocument(User* user,
const BSONObj& privDoc) {
V2UserDocumentParser parser;
std::string userName = parser.extractUserNameFromUserDocument(privDoc);
if (userName != user->getName().getUser()) {
return Status(ErrorCodes::BadValue,
mongoutils::str::stream() << "User name from privilege document \""
<< userName
<< "\" doesn't match name of provided User \""
<< user->getName().getUser()
<< "\"");
}
Status status = parser.initializeUserCredentialsFromUserDocument(user, privDoc);
if (!status.isOK()) {
return status;
}
status = parser.initializeUserRolesFromUserDocument(privDoc, user);
if (!status.isOK()) {
return status;
}
status = parser.initializeUserIndirectRolesFromUserDocument(privDoc, user);
if (!status.isOK()) {
return status;
}
status = parser.initializeUserPrivilegesFromUserDocument(privDoc, user);
if (!status.isOK()) {
return status;
}
status = parser.initializeAuthenticationRestrictionsFromUserDocument(privDoc, user);
if (!status.isOK()) {
return status;
}
return Status::OK();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-613'], 'message': 'SERVER-38984 Validate unique User ID on UserCache hit
(cherry picked from commit e55d6e2292e5dbe2f97153251d8193d1cc89f5d7)'</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 run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
auth::CreateOrUpdateUserArgs args;
Status status = auth::parseCreateOrUpdateUserCommands(cmdObj, "createUser", dbname, &args);
if (!status.isOK()) {
return appendCommandStatus(result, status);
}
if (args.userName.getDB() == "local") {
return appendCommandStatus(
result, Status(ErrorCodes::BadValue, "Cannot create users in the local database"));
}
if (!args.hasHashedPassword && args.userName.getDB() != "$external") {
return appendCommandStatus(
result,
Status(ErrorCodes::BadValue,
"Must provide a 'pwd' field for all user documents, except those"
" with '$external' as the user's source db"));
}
if ((args.hasHashedPassword) && args.userName.getDB() == "$external") {
return appendCommandStatus(
result,
Status(ErrorCodes::BadValue,
"Cannot set the password for users defined on the '$external' "
"database"));
}
if (!args.hasRoles) {
return appendCommandStatus(
result,
Status(ErrorCodes::BadValue, "\"createUser\" command requires a \"roles\" array"));
}
#ifdef MONGO_CONFIG_SSL
if (args.userName.getDB() == "$external" && getSSLManager() &&
getSSLManager()->getSSLConfiguration().isClusterMember(args.userName.getUser())) {
return appendCommandStatus(result,
Status(ErrorCodes::BadValue,
"Cannot create an x.509 user with a subjectname "
"that would be recognized as an internal "
"cluster member."));
}
#endif
BSONObjBuilder userObjBuilder;
userObjBuilder.append(
"_id", str::stream() << args.userName.getDB() << "." << args.userName.getUser());
userObjBuilder.append(AuthorizationManager::USER_NAME_FIELD_NAME, args.userName.getUser());
userObjBuilder.append(AuthorizationManager::USER_DB_FIELD_NAME, args.userName.getDB());
ServiceContext* serviceContext = opCtx->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
int authzVersion;
status = authzManager->getAuthorizationVersion(opCtx, &authzVersion);
if (!status.isOK()) {
return appendCommandStatus(result, status);
}
BSONObjBuilder credentialsBuilder(userObjBuilder.subobjStart("credentials"));
if (!args.hasHashedPassword) {
// Must be an external user
credentialsBuilder.append("external", true);
} else {
// Add SCRAM credentials for appropriate authSchemaVersions.
if (authzVersion > AuthorizationManager::schemaVersion26Final) {
BSONObj scramCred = scram::generateCredentials(
args.hashedPassword, saslGlobalParams.scramIterationCount.load());
credentialsBuilder.append("SCRAM-SHA-1", scramCred);
} else { // Otherwise default to MONGODB-CR.
credentialsBuilder.append("MONGODB-CR", args.hashedPassword);
}
}
credentialsBuilder.done();
if (args.authenticationRestrictions && !args.authenticationRestrictions->isEmpty()) {
credentialsBuilder.append("authenticationRestrictions",
*args.authenticationRestrictions);
}
if (args.hasCustomData) {
userObjBuilder.append("customData", args.customData);
}
userObjBuilder.append("roles", rolesVectorToBSONArray(args.roles));
BSONObj userObj = userObjBuilder.obj();
V2UserDocumentParser parser;
status = parser.checkValidUserDocument(userObj);
if (!status.isOK()) {
return appendCommandStatus(result, status);
}
stdx::lock_guard<stdx::mutex> lk(getAuthzDataMutex(serviceContext));
status = requireAuthSchemaVersion26Final(opCtx, authzManager);
if (!status.isOK()) {
return appendCommandStatus(result, status);
}
// Role existence has to be checked after acquiring the update lock
for (size_t i = 0; i < args.roles.size(); ++i) {
BSONObj ignored;
status = authzManager->getRoleDescription(opCtx, args.roles[i], &ignored);
if (!status.isOK()) {
return appendCommandStatus(result, status);
}
}
audit::logCreateUser(Client::getCurrent(),
args.userName,
args.hasHashedPassword,
args.hasCustomData ? &args.customData : NULL,
args.roles,
args.authenticationRestrictions);
status = insertPrivilegeDocument(opCtx, userObj);
return appendCommandStatus(result, status);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-613'], 'message': 'SERVER-38984 Validate unique User ID on UserCache hit
(cherry picked from commit e55d6e2292e5dbe2f97153251d8193d1cc89f5d7)'</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 run(OperationContext* txn,
const string& dbname,
BSONObj& cmdObj,
int options,
string& errmsg,
BSONObjBuilder& result) {
auth::CreateOrUpdateUserArgs args;
Status status = auth::parseCreateOrUpdateUserCommands(cmdObj, "createUser", dbname, &args);
if (!status.isOK()) {
return appendCommandStatus(result, status);
}
if (args.userName.getDB() == "local") {
return appendCommandStatus(
result, Status(ErrorCodes::BadValue, "Cannot create users in the local database"));
}
if (!args.hasHashedPassword && args.userName.getDB() != "$external") {
return appendCommandStatus(
result,
Status(ErrorCodes::BadValue,
"Must provide a 'pwd' field for all user documents, except those"
" with '$external' as the user's source db"));
}
if ((args.hasHashedPassword) && args.userName.getDB() == "$external") {
return appendCommandStatus(
result,
Status(ErrorCodes::BadValue,
"Cannot set the password for users defined on the '$external' "
"database"));
}
if (!args.hasRoles) {
return appendCommandStatus(
result,
Status(ErrorCodes::BadValue, "\"createUser\" command requires a \"roles\" array"));
}
#ifdef MONGO_CONFIG_SSL
if (args.userName.getDB() == "$external" && getSSLManager() &&
getSSLManager()->getSSLConfiguration().isClusterMember(args.userName.getUser())) {
return appendCommandStatus(result,
Status(ErrorCodes::BadValue,
"Cannot create an x.509 user with a subjectname "
"that would be recognized as an internal "
"cluster member."));
}
#endif
BSONObjBuilder userObjBuilder;
userObjBuilder.append(
"_id", str::stream() << args.userName.getDB() << "." << args.userName.getUser());
userObjBuilder.append(AuthorizationManager::USER_NAME_FIELD_NAME, args.userName.getUser());
userObjBuilder.append(AuthorizationManager::USER_DB_FIELD_NAME, args.userName.getDB());
ServiceContext* serviceContext = txn->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
int authzVersion;
status = authzManager->getAuthorizationVersion(txn, &authzVersion);
if (!status.isOK()) {
return appendCommandStatus(result, status);
}
BSONObjBuilder credentialsBuilder(userObjBuilder.subobjStart("credentials"));
if (!args.hasHashedPassword) {
// Must be an external user
credentialsBuilder.append("external", true);
} else {
// Add SCRAM credentials for appropriate authSchemaVersions.
if (authzVersion > AuthorizationManager::schemaVersion26Final) {
BSONObj scramCred = scram::generateCredentials(
args.hashedPassword, saslGlobalParams.scramIterationCount);
credentialsBuilder.append("SCRAM-SHA-1", scramCred);
} else { // Otherwise default to MONGODB-CR.
credentialsBuilder.append("MONGODB-CR", args.hashedPassword);
}
}
credentialsBuilder.done();
if (args.hasCustomData) {
userObjBuilder.append("customData", args.customData);
}
userObjBuilder.append("roles", rolesVectorToBSONArray(args.roles));
BSONObj userObj = userObjBuilder.obj();
V2UserDocumentParser parser;
status = parser.checkValidUserDocument(userObj);
if (!status.isOK()) {
return appendCommandStatus(result, status);
}
stdx::lock_guard<stdx::mutex> lk(getAuthzDataMutex(serviceContext));
status = requireAuthSchemaVersion26Final(txn, authzManager);
if (!status.isOK()) {
return appendCommandStatus(result, status);
}
// Role existence has to be checked after acquiring the update lock
for (size_t i = 0; i < args.roles.size(); ++i) {
BSONObj ignored;
status = authzManager->getRoleDescription(
txn, args.roles[i], PrivilegeFormat::kOmit, &ignored);
if (!status.isOK()) {
return appendCommandStatus(result, status);
}
}
audit::logCreateUser(Client::getCurrent(),
args.userName,
args.hasHashedPassword,
args.hasCustomData ? &args.customData : NULL,
args.roles);
status = insertPrivilegeDocument(txn, userObj);
return appendCommandStatus(result, status);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-613'], 'message': 'SERVER-38984 Validate unique User ID on UserCache hit
(cherry picked from commit e55d6e2292e5dbe2f97153251d8193d1cc89f5d7)'</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: Status V2UserDocumentParser::checkValidUserDocument(const BSONObj& doc) const {
BSONElement userElement = doc[AuthorizationManager::USER_NAME_FIELD_NAME];
BSONElement userDBElement = doc[AuthorizationManager::USER_DB_FIELD_NAME];
BSONElement credentialsElement = doc[CREDENTIALS_FIELD_NAME];
BSONElement rolesElement = doc[ROLES_FIELD_NAME];
// Validate the "user" element.
if (userElement.type() != String)
return _badValue("User document needs 'user' field to be a string", 0);
if (userElement.valueStringData().empty())
return _badValue("User document needs 'user' field to be non-empty", 0);
// Validate the "db" element
if (userDBElement.type() != String || userDBElement.valueStringData().empty()) {
return _badValue("User document needs 'db' field to be a non-empty string", 0);
}
StringData userDBStr = userDBElement.valueStringData();
if (!NamespaceString::validDBName(userDBStr, NamespaceString::DollarInDbNameBehavior::Allow) &&
userDBStr != "$external") {
return _badValue(mongoutils::str::stream() << "'" << userDBStr
<< "' is not a valid value for the db field.",
0);
}
// Validate the "credentials" element
if (credentialsElement.eoo()) {
return _badValue("User document needs 'credentials' object", 0);
}
if (credentialsElement.type() != Object) {
return _badValue("User document needs 'credentials' field to be an object", 0);
}
BSONObj credentialsObj = credentialsElement.Obj();
if (credentialsObj.isEmpty()) {
return _badValue("User document needs 'credentials' field to be a non-empty object", 0);
}
if (userDBStr == "$external") {
BSONElement externalElement = credentialsObj[MONGODB_EXTERNAL_CREDENTIAL_FIELD_NAME];
if (externalElement.eoo() || externalElement.type() != Bool || !externalElement.Bool()) {
return _badValue(
"User documents for users defined on '$external' must have "
"'credentials' field set to {external: true}",
0);
}
} else {
BSONElement scramElement = credentialsObj[SCRAM_CREDENTIAL_FIELD_NAME];
BSONElement mongoCRElement = credentialsObj[MONGODB_CR_CREDENTIAL_FIELD_NAME];
if (!mongoCRElement.eoo()) {
if (mongoCRElement.type() != String || mongoCRElement.valueStringData().empty()) {
return _badValue(
"MONGODB-CR credential must to be a non-empty string"
", if present",
0);
}
} else if (!scramElement.eoo()) {
if (scramElement.type() != Object) {
return _badValue("SCRAM credential must be an object, if present", 0);
}
} else {
return _badValue(
"User document must provide credentials for all "
"non-external users",
0);
}
}
// Validate the "roles" element.
Status status = _checkV2RolesArray(rolesElement);
if (!status.isOK())
return status;
return Status::OK();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-613'], 'message': 'SERVER-38984 Validate unique User ID on UserCache hit
(cherry picked from commit e55d6e2292e5dbe2f97153251d8193d1cc89f5d7)'</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 __exit atalk_proc_exit(void)
{
remove_proc_subtree("atalk", init_net.proc_net);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'appletalk: Fix use-after-free in atalk_proc_exit
KASAN report this:
BUG: KASAN: use-after-free in pde_subdir_find+0x12d/0x150 fs/proc/generic.c:71
Read of size 8 at addr ffff8881f41fe5b0 by task syz-executor.0/2806
CPU: 0 PID: 2806 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
Call Trace:
__dump_stack lib/dump_stack.c:77 [inline]
dump_stack+0xfa/0x1ce lib/dump_stack.c:113
print_address_description+0x65/0x270 mm/kasan/report.c:187
kasan_report+0x149/0x18d mm/kasan/report.c:317
pde_subdir_find+0x12d/0x150 fs/proc/generic.c:71
remove_proc_entry+0xe8/0x420 fs/proc/generic.c:667
atalk_proc_exit+0x18/0x820 [appletalk]
atalk_exit+0xf/0x5a [appletalk]
__do_sys_delete_module kernel/module.c:1018 [inline]
__se_sys_delete_module kernel/module.c:961 [inline]
__x64_sys_delete_module+0x3dc/0x5e0 kernel/module.c:961
do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007fb2de6b9c58 EFLAGS: 00000246 ORIG_RAX: 00000000000000b0
RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 0000000000000000 RDI: 00000000200001c0
RBP: 0000000000000002 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007fb2de6ba6bc
R13: 00000000004bccaa R14: 00000000006f6bc8 R15: 00000000ffffffff
Allocated by task 2806:
set_track mm/kasan/common.c:85 [inline]
__kasan_kmalloc.constprop.3+0xa0/0xd0 mm/kasan/common.c:496
slab_post_alloc_hook mm/slab.h:444 [inline]
slab_alloc_node mm/slub.c:2739 [inline]
slab_alloc mm/slub.c:2747 [inline]
kmem_cache_alloc+0xcf/0x250 mm/slub.c:2752
kmem_cache_zalloc include/linux/slab.h:730 [inline]
__proc_create+0x30f/0xa20 fs/proc/generic.c:408
proc_mkdir_data+0x47/0x190 fs/proc/generic.c:469
0xffffffffc10c01bb
0xffffffffc10c0166
do_one_initcall+0xfa/0x5ca init/main.c:887
do_init_module+0x204/0x5f6 kernel/module.c:3460
load_module+0x66b2/0x8570 kernel/module.c:3808
__do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902
do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
Freed by task 2806:
set_track mm/kasan/common.c:85 [inline]
__kasan_slab_free+0x130/0x180 mm/kasan/common.c:458
slab_free_hook mm/slub.c:1409 [inline]
slab_free_freelist_hook mm/slub.c:1436 [inline]
slab_free mm/slub.c:2986 [inline]
kmem_cache_free+0xa6/0x2a0 mm/slub.c:3002
pde_put+0x6e/0x80 fs/proc/generic.c:647
remove_proc_entry+0x1d3/0x420 fs/proc/generic.c:684
0xffffffffc10c031c
0xffffffffc10c0166
do_one_initcall+0xfa/0x5ca init/main.c:887
do_init_module+0x204/0x5f6 kernel/module.c:3460
load_module+0x66b2/0x8570 kernel/module.c:3808
__do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902
do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
The buggy address belongs to the object at ffff8881f41fe500
which belongs to the cache proc_dir_entry of size 256
The buggy address is located 176 bytes inside of
256-byte region [ffff8881f41fe500, ffff8881f41fe600)
The buggy address belongs to the page:
page:ffffea0007d07f80 count:1 mapcount:0 mapping:ffff8881f6e69a00 index:0x0
flags: 0x2fffc0000000200(slab)
raw: 02fffc0000000200 dead000000000100 dead000000000200 ffff8881f6e69a00
raw: 0000000000000000 00000000800c000c 00000001ffffffff 0000000000000000
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff8881f41fe480: fb fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
ffff8881f41fe500: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
>ffff8881f41fe580: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff8881f41fe600: fc fc fc fc fc fc fc fc fb fb fb fb fb fb fb fb
ffff8881f41fe680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
It should check the return value of atalk_proc_init fails,
otherwise atalk_exit will trgger use-after-free in pde_subdir_find
while unload the module.This patch fix error cleanup path of atalk_init
Reported-by: Hulk Robot <[email protected]>
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</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 coalesced_mmio_write(struct kvm_vcpu *vcpu,
struct kvm_io_device *this, gpa_t addr,
int len, const void *val)
{
struct kvm_coalesced_mmio_dev *dev = to_mmio(this);
struct kvm_coalesced_mmio_ring *ring = dev->kvm->coalesced_mmio_ring;
if (!coalesced_mmio_in_range(dev, addr, len))
return -EOPNOTSUPP;
spin_lock(&dev->kvm->ring_lock);
if (!coalesced_mmio_has_room(dev)) {
spin_unlock(&dev->kvm->ring_lock);
return -EOPNOTSUPP;
}
/* copy data in first free entry of the ring */
ring->coalesced_mmio[ring->last].phys_addr = addr;
ring->coalesced_mmio[ring->last].len = len;
memcpy(ring->coalesced_mmio[ring->last].data, val, len);
ring->coalesced_mmio[ring->last].pio = dev->zone.pio;
smp_wmb();
ring->last = (ring->last + 1) % KVM_COALESCED_MMIO_MAX;
spin_unlock(&dev->kvm->ring_lock);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'KVM: coalesced_mmio: add bounds checking
The first/last indexes are typically shared with a user app.
The app can change the 'last' index that the kernel uses
to store the next result. This change sanity checks the index
before using it for writing to a potentially arbitrary address.
This fixes CVE-2019-14821.
Cc: [email protected]
Fixes: 5f94c1741bdc ("KVM: Add coalesced MMIO support (common part)")
Signed-off-by: Matt Delco <[email protected]>
Signed-off-by: Jim Mattson <[email protected]>
Reported-by: [email protected]
[Use READ_ONCE. - Paolo]
Signed-off-by: Paolo Bonzini <[email protected]>'</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 rsi_init_usb_interface(struct rsi_hw *adapter,
struct usb_interface *pfunction)
{
struct rsi_91x_usbdev *rsi_dev;
int status;
rsi_dev = kzalloc(sizeof(*rsi_dev), GFP_KERNEL);
if (!rsi_dev)
return -ENOMEM;
adapter->rsi_dev = rsi_dev;
rsi_dev->usbdev = interface_to_usbdev(pfunction);
rsi_dev->priv = (void *)adapter;
if (rsi_find_bulk_in_and_out_endpoints(pfunction, adapter)) {
status = -EINVAL;
goto fail_eps;
}
adapter->device = &pfunction->dev;
usb_set_intfdata(pfunction, adapter);
rsi_dev->tx_buffer = kmalloc(2048, GFP_KERNEL);
if (!rsi_dev->tx_buffer) {
status = -ENOMEM;
goto fail_eps;
}
if (rsi_usb_init_rx(adapter)) {
rsi_dbg(ERR_ZONE, "Failed to init RX handle\n");
status = -ENOMEM;
goto fail_rx;
}
rsi_dev->tx_blk_size = 252;
adapter->block_size = rsi_dev->tx_blk_size;
/* Initializing function callbacks */
adapter->check_hw_queue_status = rsi_usb_check_queue_status;
adapter->determine_event_timeout = rsi_usb_event_timeout;
adapter->rsi_host_intf = RSI_HOST_INTF_USB;
adapter->host_intf_ops = &usb_host_intf_ops;
#ifdef CONFIG_RSI_DEBUGFS
/* In USB, one less than the MAX_DEBUGFS_ENTRIES entries is required */
adapter->num_debugfs_entries = (MAX_DEBUGFS_ENTRIES - 1);
#endif
rsi_dbg(INIT_ZONE, "%s: Enabled the interface\n", __func__);
return 0;
fail_rx:
kfree(rsi_dev->tx_buffer);
fail_eps:
kfree(rsi_dev);
return status;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-415'], 'message': 'rsi: fix a double free bug in rsi_91x_deinit()
`dev` (struct rsi_91x_usbdev *) field of adapter
(struct rsi_91x_usbdev *) is allocated and initialized in
`rsi_init_usb_interface`. If any error is detected in information
read from the device side, `rsi_init_usb_interface` will be
freed. However, in the higher level error handling code in
`rsi_probe`, if error is detected, `rsi_91x_deinit` is called
again, in which `dev` will be freed again, resulting double free.
This patch fixes the double free by removing the free operation on
`dev` in `rsi_init_usb_interface`, because `rsi_91x_deinit` is also
used in `rsi_disconnect`, in that code path, the `dev` field is not
(and thus needs to be) freed.
This bug was found in v4.19, but is also present in the latest version
of kernel. Fixes CVE-2019-15504.
Reported-by: Hui Peng <[email protected]>
Reported-by: Mathias Payer <[email protected]>
Signed-off-by: Hui Peng <[email protected]>
Reviewed-by: Guenter Roeck <[email protected]>
Signed-off-by: Kalle Valo <[email protected]>'</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 uac_mixer_unit_get_channels(struct mixer_build *state,
struct uac_mixer_unit_descriptor *desc)
{
int mu_channels;
void *c;
if (desc->bLength < sizeof(*desc))
return -EINVAL;
if (!desc->bNrInPins)
return -EINVAL;
switch (state->mixer->protocol) {
case UAC_VERSION_1:
case UAC_VERSION_2:
default:
if (desc->bLength < sizeof(*desc) + desc->bNrInPins + 1)
return 0; /* no bmControls -> skip */
mu_channels = uac_mixer_unit_bNrChannels(desc);
break;
case UAC_VERSION_3:
mu_channels = get_cluster_channels_v3(state,
uac3_mixer_unit_wClusterDescrID(desc));
break;
}
if (!mu_channels)
return 0;
c = uac_mixer_unit_bmControls(desc, state->mixer->protocol);
if (c - (void *)desc + (mu_channels - 1) / 8 >= desc->bLength)
return 0; /* no bmControls -> skip */
return mu_channels;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'ALSA: usb-audio: Fix an OOB bug in parse_audio_mixer_unit
The `uac_mixer_unit_descriptor` shown as below is read from the
device side. In `parse_audio_mixer_unit`, `baSourceID` field is
accessed from index 0 to `bNrInPins` - 1, the current implementation
assumes that descriptor is always valid (the length of descriptor
is no shorter than 5 + `bNrInPins`). If a descriptor read from
the device side is invalid, it may trigger out-of-bound memory
access.
```
struct uac_mixer_unit_descriptor {
__u8 bLength;
__u8 bDescriptorType;
__u8 bDescriptorSubtype;
__u8 bUnitID;
__u8 bNrInPins;
__u8 baSourceID[];
}
```
This patch fixes the bug by add a sanity check on the length of
the descriptor.
Reported-by: Hui Peng <[email protected]>
Reported-by: Mathias Payer <[email protected]>
Cc: <[email protected]>
Signed-off-by: Hui Peng <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>'</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 struct domain_device *sas_ex_discover_expander(
struct domain_device *parent, int phy_id)
{
struct sas_expander_device *parent_ex = rphy_to_expander_device(parent->rphy);
struct ex_phy *phy = &parent->ex_dev.ex_phy[phy_id];
struct domain_device *child = NULL;
struct sas_rphy *rphy;
struct sas_expander_device *edev;
struct asd_sas_port *port;
int res;
if (phy->routing_attr == DIRECT_ROUTING) {
pr_warn("ex %016llx:%02d:D <--> ex %016llx:0x%x is not allowed\n",
SAS_ADDR(parent->sas_addr), phy_id,
SAS_ADDR(phy->attached_sas_addr),
phy->attached_phy_id);
return NULL;
}
child = sas_alloc_device();
if (!child)
return NULL;
phy->port = sas_port_alloc(&parent->rphy->dev, phy_id);
/* FIXME: better error handling */
BUG_ON(sas_port_add(phy->port) != 0);
switch (phy->attached_dev_type) {
case SAS_EDGE_EXPANDER_DEVICE:
rphy = sas_expander_alloc(phy->port,
SAS_EDGE_EXPANDER_DEVICE);
break;
case SAS_FANOUT_EXPANDER_DEVICE:
rphy = sas_expander_alloc(phy->port,
SAS_FANOUT_EXPANDER_DEVICE);
break;
default:
rphy = NULL; /* shut gcc up */
BUG();
}
port = parent->port;
child->rphy = rphy;
get_device(&rphy->dev);
edev = rphy_to_expander_device(rphy);
child->dev_type = phy->attached_dev_type;
kref_get(&parent->kref);
child->parent = parent;
child->port = port;
child->iproto = phy->attached_iproto;
child->tproto = phy->attached_tproto;
memcpy(child->sas_addr, phy->attached_sas_addr, SAS_ADDR_SIZE);
sas_hash_addr(child->hashed_sas_addr, child->sas_addr);
sas_ex_get_linkrate(parent, child, phy);
edev->level = parent_ex->level + 1;
parent->port->disc.max_level = max(parent->port->disc.max_level,
edev->level);
sas_init_dev(child);
sas_fill_in_rphy(child, rphy);
sas_rphy_add(rphy);
spin_lock_irq(&parent->port->dev_list_lock);
list_add_tail(&child->dev_list_node, &parent->port->dev_list);
spin_unlock_irq(&parent->port->dev_list_lock);
res = sas_discover_expander(child);
if (res) {
sas_rphy_delete(rphy);
spin_lock_irq(&parent->port->dev_list_lock);
list_del(&child->dev_list_node);
spin_unlock_irq(&parent->port->dev_list_lock);
sas_put_device(child);
return NULL;
}
list_add_tail(&child->siblings, &parent->ex_dev.children);
return child;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-401'], 'message': 'scsi: libsas: delete sas port if expander discover failed
The sas_port(phy->port) allocated in sas_ex_discover_expander() will not be
deleted when the expander failed to discover. This will cause resource leak
and a further issue of kernel BUG like below:
[159785.843156] port-2:17:29: trying to add phy phy-2:17:29 fails: it's
already part of another port
[159785.852144] ------------[ cut here ]------------
[159785.856833] kernel BUG at drivers/scsi/scsi_transport_sas.c:1086!
[159785.863000] Internal error: Oops - BUG: 0 [#1] SMP
[159785.867866] CPU: 39 PID: 16993 Comm: kworker/u96:2 Tainted: G
W OE 4.19.25-vhulk1901.1.0.h111.aarch64 #1
[159785.878458] Hardware name: Huawei Technologies Co., Ltd.
Hi1620EVBCS/Hi1620EVBCS, BIOS Hi1620 CS B070 1P TA 03/21/2019
[159785.889231] Workqueue: 0000:74:02.0_disco_q sas_discover_domain
[159785.895224] pstate: 40c00009 (nZcv daif +PAN +UAO)
[159785.900094] pc : sas_port_add_phy+0x188/0x1b8
[159785.904524] lr : sas_port_add_phy+0x188/0x1b8
[159785.908952] sp : ffff0001120e3b80
[159785.912341] x29: ffff0001120e3b80 x28: 0000000000000000
[159785.917727] x27: ffff802ade8f5400 x26: ffff0000681b7560
[159785.923111] x25: ffff802adf11a800 x24: ffff0000680e8000
[159785.928496] x23: ffff802ade8f5728 x22: ffff802ade8f5708
[159785.933880] x21: ffff802adea2db40 x20: ffff802ade8f5400
[159785.939264] x19: ffff802adea2d800 x18: 0000000000000010
[159785.944649] x17: 00000000821bf734 x16: ffff00006714faa0
[159785.950033] x15: ffff0000e8ab4ecf x14: 7261702079646165
[159785.955417] x13: 726c612073277469 x12: ffff00006887b830
[159785.960802] x11: ffff00006773eaa0 x10: 7968702079687020
[159785.966186] x9 : 0000000000002453 x8 : 726f702072656874
[159785.971570] x7 : 6f6e6120666f2074 x6 : ffff802bcfb21290
[159785.976955] x5 : ffff802bcfb21290 x4 : 0000000000000000
[159785.982339] x3 : ffff802bcfb298c8 x2 : 337752b234c2ab00
[159785.987723] x1 : 337752b234c2ab00 x0 : 0000000000000000
[159785.993108] Process kworker/u96:2 (pid: 16993, stack limit =
0x0000000072dae094)
[159786.000576] Call trace:
[159786.003097] sas_port_add_phy+0x188/0x1b8
[159786.007179] sas_ex_get_linkrate.isra.5+0x134/0x140
[159786.012130] sas_ex_discover_expander+0x128/0x408
[159786.016906] sas_ex_discover_dev+0x218/0x4c8
[159786.021249] sas_ex_discover_devices+0x9c/0x1a8
[159786.025852] sas_discover_root_expander+0x134/0x160
[159786.030802] sas_discover_domain+0x1b8/0x1e8
[159786.035148] process_one_work+0x1b4/0x3f8
[159786.039230] worker_thread+0x54/0x470
[159786.042967] kthread+0x134/0x138
[159786.046269] ret_from_fork+0x10/0x18
[159786.049918] Code: 91322300 f0004402 91178042 97fe4c9b (d4210000)
[159786.056083] Modules linked in: hns3_enet_ut(OE) hclge(OE) hnae3(OE)
hisi_sas_test_hw(OE) hisi_sas_test_main(OE) serdes(OE)
[159786.067202] ---[ end trace 03622b9e2d99e196 ]---
[159786.071893] Kernel panic - not syncing: Fatal exception
[159786.077190] SMP: stopping secondary CPUs
[159786.081192] Kernel Offset: disabled
[159786.084753] CPU features: 0x2,a2a00a38
Fixes: 2908d778ab3e ("[SCSI] aic94xx: new driver")
Reported-by: Jian Luo <[email protected]>
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>'</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 event_cap (IRC_SERVER_REC *server, char *args, char *nick, char *address)
{
GSList *tmp;
GString *cmd;
char *params, *evt, *list, *star, **caps;
int i, caps_length, disable, avail_caps, multiline;
params = event_get_params(args, 4, NULL, &evt, &star, &list);
if (params == NULL)
return;
/* Multiline responses have an additional parameter and we have to do
* this stupid dance to parse them */
if (!g_ascii_strcasecmp(evt, "LS") && !strcmp(star, "*")) {
multiline = TRUE;
}
/* This branch covers the '*' parameter isn't present, adjust the
* parameter pointer to compensate for this */
else if (list[0] == '\0') {
multiline = FALSE;
list = star;
}
/* Malformed request, terminate the negotiation */
else {
irc_cap_finish_negotiation(server);
g_warn_if_reached();
return;
}
/* The table is created only when needed */
if (server->cap_supported == NULL) {
server->cap_supported = g_hash_table_new_full(g_str_hash,
g_str_equal,
g_free, g_free);
}
/* Strip the trailing whitespaces before splitting the string, some servers send responses with
* superfluous whitespaces that g_strsplit the interprets as tokens */
caps = g_strsplit(g_strchomp(list), " ", -1);
caps_length = g_strv_length(caps);
if (!g_ascii_strcasecmp(evt, "LS")) {
if (!server->cap_in_multiline) {
/* Throw away everything and start from scratch */
g_hash_table_remove_all(server->cap_supported);
}
server->cap_in_multiline = multiline;
/* Create a list of the supported caps */
for (i = 0; i < caps_length; i++) {
char *key, *val;
if (!parse_cap_name(caps[i], &key, &val)) {
g_warning("Invalid CAP %s key/value pair", evt);
continue;
}
if (g_hash_table_lookup_extended(server->cap_supported, key, NULL, NULL)) {
/* The specification doesn't say anything about
* duplicated values, let's just warn the user */
g_warning("The server sent the %s capability twice", key);
}
g_hash_table_insert(server->cap_supported, key, val);
}
/* A multiline response is always terminated by a normal one,
* wait until we receive that one to require any CAP */
if (multiline == FALSE) {
/* No CAP has been requested */
if (server->cap_queue == NULL) {
irc_cap_finish_negotiation(server);
}
else {
cmd = g_string_new("CAP REQ :");
avail_caps = 0;
/* To process the queue in order, we need to reverse the stack once */
server->cap_queue = g_slist_reverse(server->cap_queue);
/* Check whether the cap is supported by the server */
for (tmp = server->cap_queue; tmp != NULL; tmp = tmp->next) {
if (g_hash_table_lookup_extended(server->cap_supported, tmp->data, NULL, NULL)) {
if (avail_caps > 0)
g_string_append_c(cmd, ' ');
g_string_append(cmd, tmp->data);
avail_caps++;
}
}
/* Clear the queue here */
gslist_free_full(server->cap_queue, (GDestroyNotify) g_free);
server->cap_queue = NULL;
/* If the server doesn't support any cap we requested close the negotiation here */
if (avail_caps > 0) {
signal_emit("server cap req", 2, server, cmd->str + sizeof("CAP REQ :") - 1);
irc_send_cmd_now(server, cmd->str);
} else {
irc_cap_finish_negotiation(server);
}
g_string_free(cmd, TRUE);
}
}
}
else if (!g_ascii_strcasecmp(evt, "ACK")) {
int got_sasl = FALSE;
/* Emit a signal for every ack'd cap */
for (i = 0; i < caps_length; i++) {
disable = (*caps[i] == '-');
if (disable)
server->cap_active = gslist_delete_string(server->cap_active, caps[i] + 1, g_free);
else
server->cap_active = g_slist_prepend(server->cap_active, g_strdup(caps[i]));
if (!strcmp(caps[i], "sasl"))
got_sasl = TRUE;
cap_emit_signal(server, "ack", caps[i]);
}
/* Hopefully the server has ack'd all the caps requested and we're ready to terminate the
* negotiation, unless sasl was requested. In this case we must not terminate the negotiation
* until the sasl handshake is over. */
if (got_sasl == FALSE)
irc_cap_finish_negotiation(server);
}
else if (!g_ascii_strcasecmp(evt, "NAK")) {
g_warning("The server answered with a NAK to our CAP request, this should not happen");
/* A NAK'd request means that a required cap can't be enabled or disabled, don't update the
* list of active caps and notify the listeners. */
for (i = 0; i < caps_length; i++)
cap_emit_signal(server, "nak", caps[i]);
}
else if (!g_ascii_strcasecmp(evt, "NEW")) {
for (i = 0; i < caps_length; i++) {
char *key, *val;
if (!parse_cap_name(caps[i], &key, &val)) {
g_warning("Invalid CAP %s key/value pair", evt);
continue;
}
g_hash_table_insert(server->cap_supported, key, val);
cap_emit_signal(server, "new", key);
}
}
else if (!g_ascii_strcasecmp(evt, "DEL")) {
for (i = 0; i < caps_length; i++) {
char *key, *val;
if (!parse_cap_name(caps[i], &key, &val)) {
g_warning("Invalid CAP %s key/value pair", evt);
continue;
}
g_hash_table_remove(server->cap_supported, key);
cap_emit_signal(server, "delete", key);
/* The server removed this CAP, remove it from the list
* of the active ones if we had requested it */
server->cap_active = gslist_delete_string(server->cap_active, key, g_free);
/* We don't transfer the ownership of those two
* variables this time, just free them when we're done. */
g_free(key);
g_free(val);
}
}
else if (!g_ascii_strcasecmp(evt, "LIST")) {
/* do nothing, fe-cap will handle it */
}
else {
g_warning("Unhandled CAP subcommand %s", evt);
}
g_strfreev(caps);
g_free(params);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'fix use after free receiving caps
fixes GL#34'</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 __tcp_retransmit_skb(struct sock *sk, struct sk_buff *skb, int segs)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
unsigned int cur_mss;
int diff, len, err;
/* Inconclusive MTU probe */
if (icsk->icsk_mtup.probe_size)
icsk->icsk_mtup.probe_size = 0;
/* Do not sent more than we queued. 1/4 is reserved for possible
* copying overhead: fragmentation, tunneling, mangling etc.
*/
if (refcount_read(&sk->sk_wmem_alloc) >
min_t(u32, sk->sk_wmem_queued + (sk->sk_wmem_queued >> 2),
sk->sk_sndbuf))
return -EAGAIN;
if (skb_still_in_host_queue(sk, skb))
return -EBUSY;
if (before(TCP_SKB_CB(skb)->seq, tp->snd_una)) {
if (before(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
BUG();
if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq))
return -ENOMEM;
}
if (inet_csk(sk)->icsk_af_ops->rebuild_header(sk))
return -EHOSTUNREACH; /* Routing failure or similar. */
cur_mss = tcp_current_mss(sk);
/* If receiver has shrunk his window, and skb is out of
* new window, do not retransmit it. The exception is the
* case, when window is shrunk to zero. In this case
* our retransmit serves as a zero window probe.
*/
if (!before(TCP_SKB_CB(skb)->seq, tcp_wnd_end(tp)) &&
TCP_SKB_CB(skb)->seq != tp->snd_una)
return -EAGAIN;
len = cur_mss * segs;
if (skb->len > len) {
if (tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb, len,
cur_mss, GFP_ATOMIC))
return -ENOMEM; /* We'll try again later. */
} else {
if (skb_unclone(skb, GFP_ATOMIC))
return -ENOMEM;
diff = tcp_skb_pcount(skb);
tcp_set_skb_tso_segs(skb, cur_mss);
diff -= tcp_skb_pcount(skb);
if (diff)
tcp_adjust_pcount(sk, skb, diff);
if (skb->len < cur_mss)
tcp_retrans_try_collapse(sk, skb, cur_mss);
}
/* RFC3168, section 6.1.1.1. ECN fallback */
if ((TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN_ECN) == TCPHDR_SYN_ECN)
tcp_ecn_clear_syn(sk, skb);
/* Update global and local TCP statistics. */
segs = tcp_skb_pcount(skb);
TCP_ADD_STATS(sock_net(sk), TCP_MIB_RETRANSSEGS, segs);
if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)
__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSYNRETRANS);
tp->total_retrans += segs;
/* make sure skb->data is aligned on arches that require it
* and check if ack-trimming & collapsing extended the headroom
* beyond what csum_start can cover.
*/
if (unlikely((NET_IP_ALIGN && ((unsigned long)skb->data & 3)) ||
skb_headroom(skb) >= 0xFFFF)) {
struct sk_buff *nskb;
tcp_skb_tsorted_save(skb) {
nskb = __pskb_copy(skb, MAX_TCP_HEADER, GFP_ATOMIC);
err = nskb ? tcp_transmit_skb(sk, nskb, 0, GFP_ATOMIC) :
-ENOBUFS;
} tcp_skb_tsorted_restore(skb);
if (!err) {
tcp_update_skb_after_send(tp, skb);
tcp_rate_skb_sent(sk, skb);
}
} else {
err = tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC);
}
if (BPF_SOCK_OPS_TEST_FLAG(tp, BPF_SOCK_OPS_RETRANS_CB_FLAG))
tcp_call_bpf_3arg(sk, BPF_SOCK_OPS_RETRANS_CB,
TCP_SKB_CB(skb)->seq, segs, err);
if (likely(!err)) {
TCP_SKB_CB(skb)->sacked |= TCPCB_EVER_RETRANS;
trace_tcp_retransmit_skb(sk, skb);
} else if (err != -EBUSY) {
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRETRANSFAIL);
}
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'tcp: purge write queue in tcp_connect_init()
syzkaller found a reliable way to crash the host, hitting a BUG()
in __tcp_retransmit_skb()
Malicous MSG_FASTOPEN is the root cause. We need to purge write queue
in tcp_connect_init() at the point we init snd_una/write_seq.
This patch also replaces the BUG() by a less intrusive WARN_ON_ONCE()
kernel BUG at net/ipv4/tcp_output.c:2837!
invalid opcode: 0000 [#1] SMP KASAN
Dumping ftrace buffer:
(ftrace buffer empty)
Modules linked in:
CPU: 0 PID: 5276 Comm: syz-executor0 Not tainted 4.17.0-rc3+ #51
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011
RIP: 0010:__tcp_retransmit_skb+0x2992/0x2eb0 net/ipv4/tcp_output.c:2837
RSP: 0000:ffff8801dae06ff8 EFLAGS: 00010206
RAX: ffff8801b9fe61c0 RBX: 00000000ffc18a16 RCX: ffffffff864e1a49
RDX: 0000000000000100 RSI: ffffffff864e2e12 RDI: 0000000000000005
RBP: ffff8801dae073a0 R08: ffff8801b9fe61c0 R09: ffffed0039c40dd2
R10: ffffed0039c40dd2 R11: ffff8801ce206e93 R12: 00000000421eeaad
R13: ffff8801ce206d4e R14: ffff8801ce206cc0 R15: ffff8801cd4f4a80
FS: 0000000000000000(0000) GS:ffff8801dae00000(0063) knlGS:00000000096bc900
CS: 0010 DS: 002b ES: 002b CR0: 0000000080050033
CR2: 0000000020000000 CR3: 00000001c47b6000 CR4: 00000000001406f0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400
Call Trace:
<IRQ>
tcp_retransmit_skb+0x2e/0x250 net/ipv4/tcp_output.c:2923
tcp_retransmit_timer+0xc50/0x3060 net/ipv4/tcp_timer.c:488
tcp_write_timer_handler+0x339/0x960 net/ipv4/tcp_timer.c:573
tcp_write_timer+0x111/0x1d0 net/ipv4/tcp_timer.c:593
call_timer_fn+0x230/0x940 kernel/time/timer.c:1326
expire_timers kernel/time/timer.c:1363 [inline]
__run_timers+0x79e/0xc50 kernel/time/timer.c:1666
run_timer_softirq+0x4c/0x70 kernel/time/timer.c:1692
__do_softirq+0x2e0/0xaf5 kernel/softirq.c:285
invoke_softirq kernel/softirq.c:365 [inline]
irq_exit+0x1d1/0x200 kernel/softirq.c:405
exiting_irq arch/x86/include/asm/apic.h:525 [inline]
smp_apic_timer_interrupt+0x17e/0x710 arch/x86/kernel/apic/apic.c:1052
apic_timer_interrupt+0xf/0x20 arch/x86/entry/entry_64.S:863
Fixes: cf60af03ca4e ("net-tcp: Fast Open client - sendmsg(MSG_FASTOPEN)")
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Yuchung Cheng <[email protected]>
Cc: Neal Cardwell <[email protected]>
Reported-by: syzbot <[email protected]>
Acked-by: Neal Cardwell <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</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: EXTRACTOR_dvi_extract_method (struct EXTRACTOR_ExtractContext *ec)
{
unsigned int klen;
uint32_t pos;
uint32_t opos;
unsigned int len;
unsigned int pageCount;
char pages[16];
void *buf;
unsigned char *data;
uint64_t size;
uint64_t off;
ssize_t iret;
if (40 >= (iret = ec->read (ec->cls, &buf, 1024)))
return;
data = buf;
if ( (data[0] != 247) ||
(data[1] != 2) )
return; /* cannot be DVI or unsupported version */
klen = data[14];
size = ec->get_size (ec->cls);
if (size > 16 * 1024 * 1024)
return; /* too large */
if (NULL == (data = malloc ((size_t) size)))
return; /* out of memory */
memcpy (data, buf, iret);
off = iret;
while (off < size)
{
if (0 >= (iret = ec->read (ec->cls, &buf, 16 * 1024)))
{
free (data);
return;
}
memcpy (&data[off], buf, iret);
off += iret;
}
pos = size - 1;
while ( (223 == data[pos]) &&
(pos > 0) )
pos--;
if ( (2 != data[pos]) ||
(pos < 40) )
goto CLEANUP;
pos--;
pos -= 4;
/* assert pos at 'post_post tag' */
if (data[pos] != 249)
goto CLEANUP;
opos = pos;
pos = getIntAt (&data[opos + 1]);
if ( (pos + 25 > size) ||
(pos + 25 < pos) )
goto CLEANUP;
/* assert pos at 'post' command */
if (data[pos] != 248)
goto CLEANUP;
pageCount = 0;
opos = pos;
pos = getIntAt (&data[opos + 1]);
while (1)
{
if (UINT32_MAX == pos)
break;
if ( (pos + 45 > size) ||
(pos + 45 < pos) )
goto CLEANUP;
if (data[pos] != 139) /* expect 'bop' */
goto CLEANUP;
pageCount++;
opos = pos;
pos = getIntAt (&data[opos + 41]);
if (UINT32_MAX == pos)
break;
if (pos >= opos)
goto CLEANUP; /* invalid! */
}
/* ok, now we believe it's a dvi... */
snprintf (pages,
sizeof (pages),
"%u",
pageCount);
if (0 != ec->proc (ec->cls,
"dvi",
EXTRACTOR_METATYPE_PAGE_COUNT,
EXTRACTOR_METAFORMAT_UTF8,
"text/plain",
pages,
strlen (pages) + 1))
goto CLEANUP;
if (0 != ec->proc (ec->cls,
"dvi",
EXTRACTOR_METATYPE_MIMETYPE,
EXTRACTOR_METAFORMAT_UTF8,
"text/plain",
"application/x-dvi",
strlen ("application/x-dvi") + 1))
goto CLEANUP;
{
char comment[klen + 1];
comment[klen] = '\0';
memcpy (comment, &data[15], klen);
if (0 != ec->proc (ec->cls,
"dvi",
EXTRACTOR_METATYPE_COMMENT,
EXTRACTOR_METAFORMAT_C_STRING,
"text/plain",
comment,
klen + 1))
goto CLEANUP;
}
/* try to find PDF/ps special */
pos = opos;
while ( (size >= 100) &&
(pos < size - 100) )
{
switch (data[pos])
{
case 139: /* begin page 'bop', we typically have to skip that one to
find the zzz's */
pos += 45; /* skip bop */
break;
case 239: /* zzz1 */
len = data[pos + 1];
if (pos + 2 + len < size)
if (0 != parseZZZ ((const char *) data, pos + 2, len, ec->proc, ec->cls))
goto CLEANUP;
pos += len + 2;
break;
case 240: /* zzz2 */
len = getShortAt (&data[pos + 1]);
if (pos + 3 + len < size)
if (0 != parseZZZ ((const char *) data, pos + 3, len, ec->proc, ec->cls))
goto CLEANUP;
pos += len + 3;
break;
case 241: /* zzz3, who uses that? */
len = (getShortAt (&data[pos + 1])) + 65536 * data[pos + 3];
if (pos + 4 + len < size)
if (0 != parseZZZ ((const char *) data, pos + 4, len, ec->proc, ec->cls))
goto CLEANUP;
pos += len + 4;
break;
case 242: /* zzz4, hurray! */
len = getIntAt (&data[pos + 1]);
if (pos + 1 + len < size)
if (0 != parseZZZ ((const char *) data, pos + 5, len, ec->proc, ec->cls))
goto CLEANUP;
pos += len + 5;
break;
default: /* unsupported opcode, abort scan */
goto CLEANUP;
}
}
CLEANUP:
free (data);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'fix #5846'</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 CURLcode tftp_connect(struct connectdata *conn, bool *done)
{
tftp_state_data_t *state;
int blksize;
blksize = TFTP_BLKSIZE_DEFAULT;
state = conn->proto.tftpc = calloc(1, sizeof(tftp_state_data_t));
if(!state)
return CURLE_OUT_OF_MEMORY;
/* alloc pkt buffers based on specified blksize */
if(conn->data->set.tftp_blksize) {
blksize = (int)conn->data->set.tftp_blksize;
if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN)
return CURLE_TFTP_ILLEGAL;
}
if(!state->rpacket.data) {
state->rpacket.data = calloc(1, blksize + 2 + 2);
if(!state->rpacket.data)
return CURLE_OUT_OF_MEMORY;
}
if(!state->spacket.data) {
state->spacket.data = calloc(1, blksize + 2 + 2);
if(!state->spacket.data)
return CURLE_OUT_OF_MEMORY;
}
/* we don't keep TFTP connections up basically because there's none or very
* little gain for UDP */
connclose(conn, "TFTP");
state->conn = conn;
state->sockfd = state->conn->sock[FIRSTSOCKET];
state->state = TFTP_STATE_START;
state->error = TFTP_ERR_NONE;
state->blksize = blksize;
state->requested_blksize = blksize;
((struct sockaddr *)&state->local_addr)->sa_family =
(CURL_SA_FAMILY_T)(conn->ip_addr->ai_family);
tftp_set_timeouts(state);
if(!conn->bits.bound) {
/* If not already bound, bind to any interface, random UDP port. If it is
* reused or a custom local port was desired, this has already been done!
*
* We once used the size of the local_addr struct as the third argument
* for bind() to better work with IPv6 or whatever size the struct could
* have, but we learned that at least Tru64, AIX and IRIX *requires* the
* size of that argument to match the exact size of a 'sockaddr_in' struct
* when running IPv4-only.
*
* Therefore we use the size from the address we connected to, which we
* assume uses the same IP version and thus hopefully this works for both
* IPv4 and IPv6...
*/
int rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
conn->ip_addr->ai_addrlen);
if(rc) {
char buffer[STRERROR_LEN];
failf(conn->data, "bind() failed; %s",
Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
return CURLE_COULDNT_CONNECT;
}
conn->bits.bound = TRUE;
}
Curl_pgrsStartNow(conn->data);
*done = TRUE;
return CURLE_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'tftp: Alloc maximum blksize, and use default unless OACK is received
Fixes potential buffer overflow from 'recvfrom()', should the server
return an OACK without blksize.
Bug: https://curl.haxx.se/docs/CVE-2019-5482.html
CVE-2019-5482'</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 p54u_load_firmware_cb(const struct firmware *firmware,
void *context)
{
struct p54u_priv *priv = context;
struct usb_device *udev = priv->udev;
int err;
complete(&priv->fw_wait_load);
if (firmware) {
priv->fw = firmware;
err = p54u_start_ops(priv);
} else {
err = -ENOENT;
dev_err(&udev->dev, "Firmware not found.\n");
}
if (err) {
struct device *parent = priv->udev->dev.parent;
dev_err(&udev->dev, "failed to initialize device (%d)\n", err);
if (parent)
device_lock(parent);
device_release_driver(&udev->dev);
/*
* At this point p54u_disconnect has already freed
* the "priv" context. Do not use it anymore!
*/
priv = NULL;
if (parent)
device_unlock(parent);
}
usb_put_dev(udev);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'p54usb: Fix race between disconnect and firmware loading
The syzbot fuzzer found a bug in the p54 USB wireless driver. The
issue involves a race between disconnect and the firmware-loader
callback routine, and it has several aspects.
One big problem is that when the firmware can't be loaded, the
callback routine tries to unbind the driver from the USB _device_ (by
calling device_release_driver) instead of from the USB _interface_ to
which it is actually bound (by calling usb_driver_release_interface).
The race involves access to the private data structure. The driver's
disconnect handler waits for a completion that is signalled by the
firmware-loader callback routine. As soon as the completion is
signalled, you have to assume that the private data structure may have
been deallocated by the disconnect handler -- even if the firmware was
loaded without errors. However, the callback routine does access the
private data several times after that point.
Another problem is that, in order to ensure that the USB device
structure hasn't been freed when the callback routine runs, the driver
takes a reference to it. This isn't good enough any more, because now
that the callback routine calls usb_driver_release_interface, it has
to ensure that the interface structure hasn't been freed.
Finally, the driver takes an unnecessary reference to the USB device
structure in the probe function and drops the reference in the
disconnect handler. This extra reference doesn't accomplish anything,
because the USB core already guarantees that a device structure won't
be deallocated while a driver is still bound to any of its interfaces.
To fix these problems, this patch makes the following changes:
Call usb_driver_release_interface() rather than
device_release_driver().
Don't signal the completion until after the important
information has been copied out of the private data structure,
and don't refer to the private data at all thereafter.
Lock udev (the interface's parent) before unbinding the driver
instead of locking udev->parent.
During the firmware loading process, take a reference to the
USB interface instead of the USB device.
Don't take an unnecessary reference to the device during probe
(and then don't drop it during disconnect).
Signed-off-by: Alan Stern <[email protected]>
Reported-and-tested-by: [email protected]
CC: <[email protected]>
Acked-by: Christian Lamparter <[email protected]>
Signed-off-by: Kalle Valo <[email protected]>'</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 p54u_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct ieee80211_hw *dev;
struct p54u_priv *priv;
int err;
unsigned int i, recognized_pipes;
dev = p54_init_common(sizeof(*priv));
if (!dev) {
dev_err(&udev->dev, "(p54usb) ieee80211 alloc failed\n");
return -ENOMEM;
}
priv = dev->priv;
priv->hw_type = P54U_INVALID_HW;
SET_IEEE80211_DEV(dev, &intf->dev);
usb_set_intfdata(intf, dev);
priv->udev = udev;
priv->intf = intf;
skb_queue_head_init(&priv->rx_queue);
init_usb_anchor(&priv->submitted);
usb_get_dev(udev);
/* really lazy and simple way of figuring out if we're a 3887 */
/* TODO: should just stick the identification in the device table */
i = intf->altsetting->desc.bNumEndpoints;
recognized_pipes = 0;
while (i--) {
switch (intf->altsetting->endpoint[i].desc.bEndpointAddress) {
case P54U_PIPE_DATA:
case P54U_PIPE_MGMT:
case P54U_PIPE_BRG:
case P54U_PIPE_DEV:
case P54U_PIPE_DATA | USB_DIR_IN:
case P54U_PIPE_MGMT | USB_DIR_IN:
case P54U_PIPE_BRG | USB_DIR_IN:
case P54U_PIPE_DEV | USB_DIR_IN:
case P54U_PIPE_INT | USB_DIR_IN:
recognized_pipes++;
}
}
priv->common.open = p54u_open;
priv->common.stop = p54u_stop;
if (recognized_pipes < P54U_PIPE_NUMBER) {
#ifdef CONFIG_PM
/* ISL3887 needs a full reset on resume */
udev->reset_resume = 1;
#endif /* CONFIG_PM */
err = p54u_device_reset(dev);
priv->hw_type = P54U_3887;
dev->extra_tx_headroom += sizeof(struct lm87_tx_hdr);
priv->common.tx_hdr_len = sizeof(struct lm87_tx_hdr);
priv->common.tx = p54u_tx_lm87;
priv->upload_fw = p54u_upload_firmware_3887;
} else {
priv->hw_type = P54U_NET2280;
dev->extra_tx_headroom += sizeof(struct net2280_tx_hdr);
priv->common.tx_hdr_len = sizeof(struct net2280_tx_hdr);
priv->common.tx = p54u_tx_net2280;
priv->upload_fw = p54u_upload_firmware_net2280;
}
err = p54u_load_firmware(dev, intf);
if (err) {
usb_put_dev(udev);
p54_free_common(dev);
}
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'p54usb: Fix race between disconnect and firmware loading
The syzbot fuzzer found a bug in the p54 USB wireless driver. The
issue involves a race between disconnect and the firmware-loader
callback routine, and it has several aspects.
One big problem is that when the firmware can't be loaded, the
callback routine tries to unbind the driver from the USB _device_ (by
calling device_release_driver) instead of from the USB _interface_ to
which it is actually bound (by calling usb_driver_release_interface).
The race involves access to the private data structure. The driver's
disconnect handler waits for a completion that is signalled by the
firmware-loader callback routine. As soon as the completion is
signalled, you have to assume that the private data structure may have
been deallocated by the disconnect handler -- even if the firmware was
loaded without errors. However, the callback routine does access the
private data several times after that point.
Another problem is that, in order to ensure that the USB device
structure hasn't been freed when the callback routine runs, the driver
takes a reference to it. This isn't good enough any more, because now
that the callback routine calls usb_driver_release_interface, it has
to ensure that the interface structure hasn't been freed.
Finally, the driver takes an unnecessary reference to the USB device
structure in the probe function and drops the reference in the
disconnect handler. This extra reference doesn't accomplish anything,
because the USB core already guarantees that a device structure won't
be deallocated while a driver is still bound to any of its interfaces.
To fix these problems, this patch makes the following changes:
Call usb_driver_release_interface() rather than
device_release_driver().
Don't signal the completion until after the important
information has been copied out of the private data structure,
and don't refer to the private data at all thereafter.
Lock udev (the interface's parent) before unbinding the driver
instead of locking udev->parent.
During the firmware loading process, take a reference to the
USB interface instead of the USB device.
Don't take an unnecessary reference to the device during probe
(and then don't drop it during disconnect).
Signed-off-by: Alan Stern <[email protected]>
Reported-and-tested-by: [email protected]
CC: <[email protected]>
Acked-by: Christian Lamparter <[email protected]>
Signed-off-by: Kalle Valo <[email protected]>'</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 line6_init_pcm(struct usb_line6 *line6,
struct line6_pcm_properties *properties)
{
int i, err;
unsigned ep_read = line6->properties->ep_audio_r;
unsigned ep_write = line6->properties->ep_audio_w;
struct snd_pcm *pcm;
struct snd_line6_pcm *line6pcm;
if (!(line6->properties->capabilities & LINE6_CAP_PCM))
return 0; /* skip PCM initialization and report success */
err = snd_line6_new_pcm(line6, &pcm);
if (err < 0)
return err;
line6pcm = kzalloc(sizeof(*line6pcm), GFP_KERNEL);
if (!line6pcm)
return -ENOMEM;
mutex_init(&line6pcm->state_mutex);
line6pcm->pcm = pcm;
line6pcm->properties = properties;
line6pcm->volume_playback[0] = line6pcm->volume_playback[1] = 255;
line6pcm->volume_monitor = 255;
line6pcm->line6 = line6;
line6pcm->max_packet_size_in =
usb_maxpacket(line6->usbdev,
usb_rcvisocpipe(line6->usbdev, ep_read), 0);
line6pcm->max_packet_size_out =
usb_maxpacket(line6->usbdev,
usb_sndisocpipe(line6->usbdev, ep_write), 1);
spin_lock_init(&line6pcm->out.lock);
spin_lock_init(&line6pcm->in.lock);
line6pcm->impulse_period = LINE6_IMPULSE_DEFAULT_PERIOD;
line6->line6pcm = line6pcm;
pcm->private_data = line6pcm;
pcm->private_free = line6_cleanup_pcm;
err = line6_create_audio_out_urbs(line6pcm);
if (err < 0)
return err;
err = line6_create_audio_in_urbs(line6pcm);
if (err < 0)
return err;
/* mixer: */
for (i = 0; i < ARRAY_SIZE(line6_controls); i++) {
err = snd_ctl_add(line6->card,
snd_ctl_new1(&line6_controls[i], line6pcm));
if (err < 0)
return err;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'ALSA: line6: Fix write on zero-sized buffer
LINE6 drivers allocate the buffers based on the value returned from
usb_maxpacket() calls. The manipulated device may return zero for
this, and this results in the kmalloc() with zero size (and it may
succeed) while the other part of the driver code writes the packet
data with the fixed size -- which eventually overwrites.
This patch adds a simple sanity check for the invalid buffer size for
avoiding that problem.
Reported-by: [email protected]
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>'</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 toneport_setup(struct usb_line6_toneport *toneport)
{
u32 *ticks;
struct usb_line6 *line6 = &toneport->line6;
struct usb_device *usbdev = line6->usbdev;
ticks = kmalloc(sizeof(*ticks), GFP_KERNEL);
if (!ticks)
return -ENOMEM;
/* sync time on device with host: */
/* note: 32-bit timestamps overflow in year 2106 */
*ticks = (u32)ktime_get_real_seconds();
line6_write_data(line6, 0x80c6, ticks, 4);
kfree(ticks);
/* enable device: */
toneport_send_cmd(usbdev, 0x0301, 0x0000);
/* initialize source select: */
if (toneport_has_source_select(toneport))
toneport_send_cmd(usbdev,
toneport_source_info[toneport->source].code,
0x0000);
if (toneport_has_led(toneport))
toneport_update_led(toneport);
schedule_delayed_work(&toneport->pcm_work,
msecs_to_jiffies(TONEPORT_PCM_DELAY * 1000));
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'ALSA: line6: Assure canceling delayed work at disconnection
The current code performs the cancel of a delayed work at the late
stage of disconnection procedure, which may lead to the access to the
already cleared state.
This patch assures to call cancel_delayed_work_sync() at the beginning
of the disconnection procedure for avoiding that race. The delayed
work object is now assigned in the common line6 object instead of its
derivative, so that we can call cancel_delayed_work_sync().
Along with the change, the startup function is called via the new
callback instead. This will make it easier to port other LINE6
drivers to use the delayed work for startup in later patches.
Reported-by: [email protected]
Fixes: 7f84ff68be05 ("ALSA: line6: toneport: Fix broken usage of timer for delayed execution")
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>'</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 line6_toneport_disconnect(struct usb_line6 *line6)
{
struct usb_line6_toneport *toneport =
(struct usb_line6_toneport *)line6;
cancel_delayed_work_sync(&toneport->pcm_work);
if (toneport_has_led(toneport))
toneport_remove_leds(toneport);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'ALSA: line6: Assure canceling delayed work at disconnection
The current code performs the cancel of a delayed work at the late
stage of disconnection procedure, which may lead to the access to the
already cleared state.
This patch assures to call cancel_delayed_work_sync() at the beginning
of the disconnection procedure for avoiding that race. The delayed
work object is now assigned in the common line6 object instead of its
derivative, so that we can call cancel_delayed_work_sync().
Along with the change, the startup function is called via the new
callback instead. This will make it easier to port other LINE6
drivers to use the delayed work for startup in later patches.
Reported-by: [email protected]
Fixes: 7f84ff68be05 ("ALSA: line6: toneport: Fix broken usage of timer for delayed execution")
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>'</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 line6_disconnect(struct usb_interface *interface)
{
struct usb_line6 *line6 = usb_get_intfdata(interface);
struct usb_device *usbdev = interface_to_usbdev(interface);
if (!line6)
return;
if (WARN_ON(usbdev != line6->usbdev))
return;
if (line6->urb_listen != NULL)
line6_stop_listen(line6);
snd_card_disconnect(line6->card);
if (line6->line6pcm)
line6_pcm_disconnect(line6->line6pcm);
if (line6->disconnect)
line6->disconnect(line6);
dev_info(&interface->dev, "Line 6 %s now disconnected\n",
line6->properties->name);
/* make sure the device isn't destructed twice: */
usb_set_intfdata(interface, NULL);
snd_card_free_when_closed(line6->card);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'ALSA: line6: Assure canceling delayed work at disconnection
The current code performs the cancel of a delayed work at the late
stage of disconnection procedure, which may lead to the access to the
already cleared state.
This patch assures to call cancel_delayed_work_sync() at the beginning
of the disconnection procedure for avoiding that race. The delayed
work object is now assigned in the common line6 object instead of its
derivative, so that we can call cancel_delayed_work_sync().
Along with the change, the startup function is called via the new
callback instead. This will make it easier to port other LINE6
drivers to use the delayed work for startup in later patches.
Reported-by: [email protected]
Fixes: 7f84ff68be05 ("ALSA: line6: toneport: Fix broken usage of timer for delayed execution")
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>'</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: SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
unsigned int *nbytes, struct kvec *iov, int n_vec)
{
struct smb_rqst rqst;
int rc = 0;
struct smb2_write_req *req = NULL;
struct smb2_write_rsp *rsp = NULL;
int resp_buftype;
struct kvec rsp_iov;
int flags = 0;
unsigned int total_len;
*nbytes = 0;
if (n_vec < 1)
return rc;
rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, (void **) &req,
&total_len);
if (rc)
return rc;
if (io_parms->tcon->ses->server == NULL)
return -ECONNABORTED;
if (smb3_encryption_required(io_parms->tcon))
flags |= CIFS_TRANSFORM_REQ;
req->sync_hdr.ProcessId = cpu_to_le32(io_parms->pid);
req->PersistentFileId = io_parms->persistent_fid;
req->VolatileFileId = io_parms->volatile_fid;
req->WriteChannelInfoOffset = 0;
req->WriteChannelInfoLength = 0;
req->Channel = 0;
req->Length = cpu_to_le32(io_parms->length);
req->Offset = cpu_to_le64(io_parms->offset);
req->DataOffset = cpu_to_le16(
offsetof(struct smb2_write_req, Buffer));
req->RemainingBytes = 0;
trace_smb3_write_enter(xid, io_parms->persistent_fid,
io_parms->tcon->tid, io_parms->tcon->ses->Suid,
io_parms->offset, io_parms->length);
iov[0].iov_base = (char *)req;
/* 1 for Buffer */
iov[0].iov_len = total_len - 1;
memset(&rqst, 0, sizeof(struct smb_rqst));
rqst.rq_iov = iov;
rqst.rq_nvec = n_vec + 1;
rc = cifs_send_recv(xid, io_parms->tcon->ses, &rqst,
&resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
if (rc) {
trace_smb3_write_err(xid, req->PersistentFileId,
io_parms->tcon->tid,
io_parms->tcon->ses->Suid,
io_parms->offset, io_parms->length, rc);
cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
cifs_dbg(VFS, "Send error in write = %d\n", rc);
} else {
*nbytes = le32_to_cpu(rsp->DataLength);
trace_smb3_write_done(xid, req->PersistentFileId,
io_parms->tcon->tid,
io_parms->tcon->ses->Suid,
io_parms->offset, *nbytes);
}
free_rsp_buf(resp_buftype, rsp);
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-200'], 'message': 'cifs: Fix use-after-free in SMB2_write
There is a KASAN use-after-free:
BUG: KASAN: use-after-free in SMB2_write+0x1342/0x1580
Read of size 8 at addr ffff8880b6a8e450 by task ln/4196
Should not release the 'req' because it will use in the trace.
Fixes: eccb4422cf97 ("smb3: Add ftrace tracepoints for improved SMB3 debugging")
Signed-off-by: ZhangXiaoxu <[email protected]>
Signed-off-by: Steve French <[email protected]>
CC: Stable <[email protected]> 4.18+
Reviewed-by: Pavel Shilovsky <[email protected]>'</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 vhost_get_vq_desc(struct vhost_virtqueue *vq,
struct iovec iov[], unsigned int iov_size,
unsigned int *out_num, unsigned int *in_num,
struct vhost_log *log, unsigned int *log_num)
{
struct vring_desc desc;
unsigned int i, head, found = 0;
u16 last_avail_idx;
__virtio16 avail_idx;
__virtio16 ring_head;
int ret, access;
/* Check it isn't doing very strange things with descriptor numbers. */
last_avail_idx = vq->last_avail_idx;
if (vq->avail_idx == vq->last_avail_idx) {
if (unlikely(vhost_get_avail_idx(vq, &avail_idx))) {
vq_err(vq, "Failed to access avail idx at %p\n",
&vq->avail->idx);
return -EFAULT;
}
vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
vq_err(vq, "Guest moved used index from %u to %u",
last_avail_idx, vq->avail_idx);
return -EFAULT;
}
/* If there's nothing new since last we looked, return
* invalid.
*/
if (vq->avail_idx == last_avail_idx)
return vq->num;
/* Only get avail ring entries after they have been
* exposed by guest.
*/
smp_rmb();
}
/* Grab the next descriptor number they're advertising, and increment
* the index we've seen. */
if (unlikely(vhost_get_avail_head(vq, &ring_head, last_avail_idx))) {
vq_err(vq, "Failed to read head: idx %d address %p\n",
last_avail_idx,
&vq->avail->ring[last_avail_idx % vq->num]);
return -EFAULT;
}
head = vhost16_to_cpu(vq, ring_head);
/* If their number is silly, that's an error. */
if (unlikely(head >= vq->num)) {
vq_err(vq, "Guest says index %u > %u is available",
head, vq->num);
return -EINVAL;
}
/* When we start there are none of either input nor output. */
*out_num = *in_num = 0;
if (unlikely(log))
*log_num = 0;
i = head;
do {
unsigned iov_count = *in_num + *out_num;
if (unlikely(i >= vq->num)) {
vq_err(vq, "Desc index is %u > %u, head = %u",
i, vq->num, head);
return -EINVAL;
}
if (unlikely(++found > vq->num)) {
vq_err(vq, "Loop detected: last one at %u "
"vq size %u head %u\n",
i, vq->num, head);
return -EINVAL;
}
ret = vhost_get_desc(vq, &desc, i);
if (unlikely(ret)) {
vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
i, vq->desc + i);
return -EFAULT;
}
if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
ret = get_indirect(vq, iov, iov_size,
out_num, in_num,
log, log_num, &desc);
if (unlikely(ret < 0)) {
if (ret != -EAGAIN)
vq_err(vq, "Failure detected "
"in indirect descriptor at idx %d\n", i);
return ret;
}
continue;
}
if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
access = VHOST_ACCESS_WO;
else
access = VHOST_ACCESS_RO;
ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
vhost32_to_cpu(vq, desc.len), iov + iov_count,
iov_size - iov_count, access);
if (unlikely(ret < 0)) {
if (ret != -EAGAIN)
vq_err(vq, "Translation failure %d descriptor idx %d\n",
ret, i);
return ret;
}
if (access == VHOST_ACCESS_WO) {
/* If this is an input descriptor,
* increment that count. */
*in_num += ret;
if (unlikely(log)) {
log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
log[*log_num].len = vhost32_to_cpu(vq, desc.len);
++*log_num;
}
} else {
/* If it's an output descriptor, they're all supposed
* to come before any input descriptors. */
if (unlikely(*in_num)) {
vq_err(vq, "Descriptor has out after in: "
"idx %d\n", i);
return -EINVAL;
}
*out_num += ret;
}
} while ((i = next_desc(vq, &desc)) != -1);
/* On success, increment avail index. */
vq->last_avail_idx++;
/* Assume notifications from guest are disabled at this point,
* if they aren't we would need to update avail_event index. */
BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
return head;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-120'], 'message': 'vhost: make sure log_num < in_num
The code assumes log_num < in_num everywhere, and that is true as long as
in_num is incremented by descriptor iov count, and log_num by 1. However
this breaks if there's a zero sized descriptor.
As a result, if a malicious guest creates a vring desc with desc.len = 0,
it may cause the host kernel to crash by overflowing the log array. This
bug can be triggered during the VM migration.
There's no need to log when desc.len = 0, so just don't increment log_num
in this case.
Fixes: 3a4d5c94e959 ("vhost_net: a kernel-level virtio server")
Cc: [email protected]
Reviewed-by: Lidong Chen <[email protected]>
Signed-off-by: ruippan <[email protected]>
Signed-off-by: yongduan <[email protected]>
Acked-by: Michael S. Tsirkin <[email protected]>
Reviewed-by: Tyler Hicks <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>'</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 ath6kl_wmi_pstream_timeout_event_rx(struct wmi *wmi, u8 *datap,
int len)
{
struct wmi_pstream_timeout_event *ev;
if (len < sizeof(struct wmi_pstream_timeout_event))
return -EINVAL;
ev = (struct wmi_pstream_timeout_event *) datap;
/*
* When the pstream (fat pipe == AC) timesout, it means there were
* no thinStreams within this pstream & it got implicitly created
* due to data flow on this AC. We start the inactivity timer only
* for implicitly created pstream. Just reset the host state.
*/
spin_lock_bh(&wmi->lock);
wmi->stream_exist_for_ac[ev->traffic_class] = 0;
wmi->fat_pipe_exist &= ~(1 << ev->traffic_class);
spin_unlock_bh(&wmi->lock);
/* Indicate inactivity to driver layer for this fatpipe (pstream) */
ath6kl_indicate_tx_activity(wmi->parent_dev, ev->traffic_class, false);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'ath6kl: add some bounds checking
The "ev->traffic_class" and "reply->ac" variables come from the network
and they're used as an offset into the wmi->stream_exist_for_ac[] array.
Those variables are u8 so they can be 0-255 but the stream_exist_for_ac[]
array only has WMM_NUM_AC (4) elements. We need to add a couple bounds
checks to prevent array overflows.
I also modified one existing check from "if (traffic_class > 3) {" to
"if (traffic_class >= WMM_NUM_AC) {" just to make them all consistent.
Fixes: bdcd81707973 (" Add ath6kl cleaned up driver")
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Kalle Valo <[email protected]>'</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 register_queue_kobjects(struct net_device *dev)
{
int error = 0, txq = 0, rxq = 0, real_rx = 0, real_tx = 0;
#ifdef CONFIG_SYSFS
dev->queues_kset = kset_create_and_add("queues",
NULL, &dev->dev.kobj);
if (!dev->queues_kset)
return -ENOMEM;
real_rx = dev->real_num_rx_queues;
#endif
real_tx = dev->real_num_tx_queues;
error = net_rx_queue_update_kobjects(dev, 0, real_rx);
if (error)
goto error;
rxq = real_rx;
error = netdev_queue_update_kobjects(dev, 0, real_tx);
if (error)
goto error;
txq = real_tx;
return 0;
error:
netdev_queue_update_kobjects(dev, txq, 0);
net_rx_queue_update_kobjects(dev, rxq, 0);
return error; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-401'], 'message': 'net-sysfs: Fix mem leak in netdev_register_kobject
syzkaller report this:
BUG: memory leak
unreferenced object 0xffff88837a71a500 (size 256):
comm "syz-executor.2", pid 9770, jiffies 4297825125 (age 17.843s)
hex dump (first 32 bytes):
00 00 00 00 ad 4e ad de ff ff ff ff 00 00 00 00 .....N..........
ff ff ff ff ff ff ff ff 20 c0 ef 86 ff ff ff ff ........ .......
backtrace:
[<00000000db12624b>] netdev_register_kobject+0x124/0x2e0 net/core/net-sysfs.c:1751
[<00000000dc49a994>] register_netdevice+0xcc1/0x1270 net/core/dev.c:8516
[<00000000e5f3fea0>] tun_set_iff drivers/net/tun.c:2649 [inline]
[<00000000e5f3fea0>] __tun_chr_ioctl+0x2218/0x3d20 drivers/net/tun.c:2883
[<000000001b8ac127>] vfs_ioctl fs/ioctl.c:46 [inline]
[<000000001b8ac127>] do_vfs_ioctl+0x1a5/0x10e0 fs/ioctl.c:690
[<0000000079b269f8>] ksys_ioctl+0x89/0xa0 fs/ioctl.c:705
[<00000000de649beb>] __do_sys_ioctl fs/ioctl.c:712 [inline]
[<00000000de649beb>] __se_sys_ioctl fs/ioctl.c:710 [inline]
[<00000000de649beb>] __x64_sys_ioctl+0x74/0xb0 fs/ioctl.c:710
[<000000007ebded1e>] do_syscall_64+0xc8/0x580 arch/x86/entry/common.c:290
[<00000000db315d36>] entry_SYSCALL_64_after_hwframe+0x49/0xbe
[<00000000115be9bb>] 0xffffffffffffffff
It should call kset_unregister to free 'dev->queues_kset'
in error path of register_queue_kobjects, otherwise will cause a mem leak.
Reported-by: Hulk Robot <[email protected]>
Fixes: 1d24eb4815d1 ("xps: Transmit Packet Steering")
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</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: bgp_log_error(struct bgp_proto *p, u8 class, char *msg, unsigned code, unsigned subcode, byte *data, unsigned len)
{
byte argbuf[256], *t = argbuf;
unsigned i;
/* Don't report Cease messages generated by myself */
if (code == 6 && class == BE_BGP_TX)
return;
/* Reset shutdown message */
if ((code == 6) && ((subcode == 2) || (subcode == 4)))
proto_set_message(&p->p, NULL, 0);
if (len)
{
/* Bad peer AS - we would like to print the AS */
if ((code == 2) && (subcode == 2) && ((len == 2) || (len == 4)))
{
t += bsprintf(t, ": %u", (len == 2) ? get_u16(data) : get_u32(data));
goto done;
}
/* RFC 8203 - shutdown communication */
if (((code == 6) && ((subcode == 2) || (subcode == 4))))
if (bgp_handle_message(p, data, len, &t))
goto done;
*t++ = ':';
*t++ = ' ';
if (len > 16)
len = 16;
for (i=0; i<len; i++)
t += bsprintf(t, "%02x", data[i]);
}
done:
*t = 0;
const byte *dsc = bgp_error_dsc(code, subcode);
log(L_REMOTE "%s: %s: %s%s", p->p.name, msg, dsc, argbuf);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'BGP: Fix bugs in handling of shutdown messages
There is an improper check for valid message size, which may lead to
stack overflow and buffer leaks to log when a large message is received.
Thanks to Daniel McCarney for bugreport and analysis.'</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 HaarEvaluator::Feature :: read( const FileNode& node )
{
FileNode rnode = node[CC_RECTS];
FileNodeIterator it = rnode.begin(), it_end = rnode.end();
int ri;
for( ri = 0; ri < RECT_NUM; ri++ )
{
rect[ri].r = Rect();
rect[ri].weight = 0.f;
}
for(ri = 0; it != it_end; ++it, ri++)
{
FileNodeIterator it2 = (*it).begin();
it2 >> rect[ri].r.x >> rect[ri].r.y >>
rect[ri].r.width >> rect[ri].r.height >> rect[ri].weight;
}
tilted = (int)node[CC_TILTED] != 0;
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'objdetect: validate feature rectangle on reading'</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 CascadeClassifierImpl::Data::read(const FileNode &root)
{
static const float THRESHOLD_EPS = 1e-5f;
// load stage params
String stageTypeStr = (String)root[CC_STAGE_TYPE];
if( stageTypeStr == CC_BOOST )
stageType = BOOST;
else
return false;
String featureTypeStr = (String)root[CC_FEATURE_TYPE];
if( featureTypeStr == CC_HAAR )
featureType = FeatureEvaluator::HAAR;
else if( featureTypeStr == CC_LBP )
featureType = FeatureEvaluator::LBP;
else if( featureTypeStr == CC_HOG )
{
featureType = FeatureEvaluator::HOG;
CV_Error(Error::StsNotImplemented, "HOG cascade is not supported in 3.0");
}
else
return false;
origWinSize.width = (int)root[CC_WIDTH];
origWinSize.height = (int)root[CC_HEIGHT];
CV_Assert( origWinSize.height > 0 && origWinSize.width > 0 );
// load feature params
FileNode fn = root[CC_FEATURE_PARAMS];
if( fn.empty() )
return false;
ncategories = fn[CC_MAX_CAT_COUNT];
int subsetSize = (ncategories + 31)/32,
nodeStep = 3 + ( ncategories>0 ? subsetSize : 1 );
// load stages
fn = root[CC_STAGES];
if( fn.empty() )
return false;
stages.reserve(fn.size());
classifiers.clear();
nodes.clear();
stumps.clear();
FileNodeIterator it = fn.begin(), it_end = fn.end();
minNodesPerTree = INT_MAX;
maxNodesPerTree = 0;
for( int si = 0; it != it_end; si++, ++it )
{
FileNode fns = *it;
Stage stage;
stage.threshold = (float)fns[CC_STAGE_THRESHOLD] - THRESHOLD_EPS;
fns = fns[CC_WEAK_CLASSIFIERS];
if(fns.empty())
return false;
stage.ntrees = (int)fns.size();
stage.first = (int)classifiers.size();
stages.push_back(stage);
classifiers.reserve(stages[si].first + stages[si].ntrees);
FileNodeIterator it1 = fns.begin(), it1_end = fns.end();
for( ; it1 != it1_end; ++it1 ) // weak trees
{
FileNode fnw = *it1;
FileNode internalNodes = fnw[CC_INTERNAL_NODES];
FileNode leafValues = fnw[CC_LEAF_VALUES];
if( internalNodes.empty() || leafValues.empty() )
return false;
DTree tree;
tree.nodeCount = (int)internalNodes.size()/nodeStep;
minNodesPerTree = std::min(minNodesPerTree, tree.nodeCount);
maxNodesPerTree = std::max(maxNodesPerTree, tree.nodeCount);
classifiers.push_back(tree);
nodes.reserve(nodes.size() + tree.nodeCount);
leaves.reserve(leaves.size() + leafValues.size());
if( subsetSize > 0 )
subsets.reserve(subsets.size() + tree.nodeCount*subsetSize);
FileNodeIterator internalNodesIter = internalNodes.begin(), internalNodesEnd = internalNodes.end();
for( ; internalNodesIter != internalNodesEnd; ) // nodes
{
DTreeNode node;
node.left = (int)*internalNodesIter; ++internalNodesIter;
node.right = (int)*internalNodesIter; ++internalNodesIter;
node.featureIdx = (int)*internalNodesIter; ++internalNodesIter;
if( subsetSize > 0 )
{
for( int j = 0; j < subsetSize; j++, ++internalNodesIter )
subsets.push_back((int)*internalNodesIter);
node.threshold = 0.f;
}
else
{
node.threshold = (float)*internalNodesIter; ++internalNodesIter;
}
nodes.push_back(node);
}
internalNodesIter = leafValues.begin(), internalNodesEnd = leafValues.end();
for( ; internalNodesIter != internalNodesEnd; ++internalNodesIter ) // leaves
leaves.push_back((float)*internalNodesIter);
}
}
if( maxNodesPerTree == 1 )
{
int nodeOfs = 0, leafOfs = 0;
size_t nstages = stages.size();
for( size_t stageIdx = 0; stageIdx < nstages; stageIdx++ )
{
const Stage& stage = stages[stageIdx];
int ntrees = stage.ntrees;
for( int i = 0; i < ntrees; i++, nodeOfs++, leafOfs+= 2 )
{
const DTreeNode& node = nodes[nodeOfs];
stumps.push_back(Stump(node.featureIdx, node.threshold,
leaves[leafOfs], leaves[leafOfs+1]));
}
}
}
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'objdetect: validate feature rectangle on reading'</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 LBPEvaluator::Feature :: read(const FileNode& node )
{
FileNode rnode = node[CC_RECT];
FileNodeIterator it = rnode.begin();
it >> rect.x >> rect.y >> rect.width >> rect.height;
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'objdetect: validate feature rectangle on reading'</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: prologProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
const char *next = s;
int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-611', 'CWE-776', 'CWE-415', 'CWE-125'], 'message': 'xmlparse.c: Deny internal entities closing the doctype'</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: externalParEntProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
const char *next = s;
int tok;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
if (tok <= 0) {
if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_NONE: /* start == end */
default:
break;
}
}
/* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.
However, when parsing an external subset, doProlog will not accept a BOM
as valid, and report a syntax error, so we have to skip the BOM
*/
else if (tok == XML_TOK_BOM) {
s = next;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
}
parser->m_processor = prologProcessor;
return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-611', 'CWE-776', 'CWE-415', 'CWE-125'], 'message': 'xmlparse.c: Deny internal entities closing the doctype'</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: HeaderMapImpl::HeaderEntryImpl& HeaderMapImpl::maybeCreateInline(HeaderEntryImpl** entry,
const LowerCaseString& key,
HeaderString&& value) {
if (*entry) {
value.clear();
return **entry;
}
std::list<HeaderEntryImpl>::iterator i = headers_.insert(key, std::move(value));
i->entry_ = i;
*entry = &(*i);
return **entry;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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 HeaderMapImpl::appendToHeader(HeaderString& header, absl::string_view data) {
if (data.empty()) {
return;
}
if (!header.empty()) {
header.append(",", 1);
}
header.append(data.data(), data.size());
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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 HttpGrpcAccessLog::emitLog(const Http::HeaderMap& request_headers,
const Http::HeaderMap& response_headers,
const Http::HeaderMap& response_trailers,
const StreamInfo::StreamInfo& stream_info) {
// Common log properties.
// TODO(mattklein123): Populate sample_rate field.
envoy::data::accesslog::v2::HTTPAccessLogEntry log_entry;
GrpcCommon::Utility::extractCommonAccessLogProperties(*log_entry.mutable_common_properties(),
stream_info);
if (stream_info.protocol()) {
switch (stream_info.protocol().value()) {
case Http::Protocol::Http10:
log_entry.set_protocol_version(envoy::data::accesslog::v2::HTTPAccessLogEntry::HTTP10);
break;
case Http::Protocol::Http11:
log_entry.set_protocol_version(envoy::data::accesslog::v2::HTTPAccessLogEntry::HTTP11);
break;
case Http::Protocol::Http2:
log_entry.set_protocol_version(envoy::data::accesslog::v2::HTTPAccessLogEntry::HTTP2);
break;
}
}
// HTTP request properties.
// TODO(mattklein123): Populate port field.
auto* request_properties = log_entry.mutable_request();
if (request_headers.Scheme() != nullptr) {
request_properties->set_scheme(std::string(request_headers.Scheme()->value().getStringView()));
}
if (request_headers.Host() != nullptr) {
request_properties->set_authority(std::string(request_headers.Host()->value().getStringView()));
}
if (request_headers.Path() != nullptr) {
request_properties->set_path(std::string(request_headers.Path()->value().getStringView()));
}
if (request_headers.UserAgent() != nullptr) {
request_properties->set_user_agent(
std::string(request_headers.UserAgent()->value().getStringView()));
}
if (request_headers.Referer() != nullptr) {
request_properties->set_referer(
std::string(request_headers.Referer()->value().getStringView()));
}
if (request_headers.ForwardedFor() != nullptr) {
request_properties->set_forwarded_for(
std::string(request_headers.ForwardedFor()->value().getStringView()));
}
if (request_headers.RequestId() != nullptr) {
request_properties->set_request_id(
std::string(request_headers.RequestId()->value().getStringView()));
}
if (request_headers.EnvoyOriginalPath() != nullptr) {
request_properties->set_original_path(
std::string(request_headers.EnvoyOriginalPath()->value().getStringView()));
}
request_properties->set_request_headers_bytes(request_headers.byteSize());
request_properties->set_request_body_bytes(stream_info.bytesReceived());
if (request_headers.Method() != nullptr) {
envoy::api::v2::core::RequestMethod method =
envoy::api::v2::core::RequestMethod::METHOD_UNSPECIFIED;
envoy::api::v2::core::RequestMethod_Parse(
std::string(request_headers.Method()->value().getStringView()), &method);
request_properties->set_request_method(method);
}
if (!request_headers_to_log_.empty()) {
auto* logged_headers = request_properties->mutable_request_headers();
for (const auto& header : request_headers_to_log_) {
const Http::HeaderEntry* entry = request_headers.get(header);
if (entry != nullptr) {
logged_headers->insert({header.get(), std::string(entry->value().getStringView())});
}
}
}
// HTTP response properties.
auto* response_properties = log_entry.mutable_response();
if (stream_info.responseCode()) {
response_properties->mutable_response_code()->set_value(stream_info.responseCode().value());
}
if (stream_info.responseCodeDetails()) {
response_properties->set_response_code_details(stream_info.responseCodeDetails().value());
}
response_properties->set_response_headers_bytes(response_headers.byteSize());
response_properties->set_response_body_bytes(stream_info.bytesSent());
if (!response_headers_to_log_.empty()) {
auto* logged_headers = response_properties->mutable_response_headers();
for (const auto& header : response_headers_to_log_) {
const Http::HeaderEntry* entry = response_headers.get(header);
if (entry != nullptr) {
logged_headers->insert({header.get(), std::string(entry->value().getStringView())});
}
}
}
if (!response_trailers_to_log_.empty()) {
auto* logged_headers = response_properties->mutable_response_trailers();
for (const auto& header : response_trailers_to_log_) {
const Http::HeaderEntry* entry = response_trailers.get(header);
if (entry != nullptr) {
logged_headers->insert({header.get(), std::string(entry->value().getStringView())});
}
}
}
tls_slot_->getTyped<ThreadLocalLogger>().logger_->log(std::move(log_entry));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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 HeaderMapImpl::addCopy(const LowerCaseString& key, const std::string& value) {
auto* entry = getExistingInline(key.get());
if (entry != nullptr) {
appendToHeader(entry->value(), value);
return;
}
HeaderString new_key;
new_key.setCopy(key.get().c_str(), key.get().size());
HeaderString new_value;
new_value.setCopy(value.c_str(), value.size());
insertByKey(std::move(new_key), std::move(new_value));
ASSERT(new_key.empty()); // NOLINT(bugprone-use-after-move)
ASSERT(new_value.empty()); // NOLINT(bugprone-use-after-move)
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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: IntegrationStreamDecoderPtr HttpIntegrationTest::sendRequestAndWaitForResponse(
const Http::TestHeaderMapImpl& request_headers, uint32_t request_body_size,
const Http::TestHeaderMapImpl& response_headers, uint32_t response_size, int upstream_index) {
ASSERT(codec_client_ != nullptr);
// Send the request to Envoy.
IntegrationStreamDecoderPtr response;
if (request_body_size) {
response = codec_client_->makeRequestWithBody(request_headers, request_body_size);
} else {
response = codec_client_->makeHeaderOnlyRequest(request_headers);
}
waitForNextUpstreamRequest(upstream_index);
// Send response headers, and end_stream if there is no response body.
upstream_request_->encodeHeaders(response_headers, response_size == 0);
// Send any response data, with end_stream true.
if (response_size) {
upstream_request_->encodeData(response_size, true);
}
// Wait for the response to be read by the codec client.
response->waitForEndStream();
return response;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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 ConnectionImpl::onFrameReceived(const nghttp2_frame* frame) {
ENVOY_CONN_LOG(trace, "recv frame type={}", connection_, static_cast<uint64_t>(frame->hd.type));
// onFrameReceived() is called with a complete HEADERS frame assembled from all the HEADERS
// and CONTINUATION frames, but we track them separately: HEADERS frames in onBeginHeaders()
// and CONTINUATION frames in onBeforeFrameReceived().
ASSERT(frame->hd.type != NGHTTP2_CONTINUATION);
if (frame->hd.type == NGHTTP2_DATA) {
if (!trackInboundFrames(&frame->hd, frame->data.padlen)) {
return NGHTTP2_ERR_FLOODED;
}
}
// Only raise GOAWAY once, since we don't currently expose stream information. Shutdown
// notifications are the same as a normal GOAWAY.
if (frame->hd.type == NGHTTP2_GOAWAY && !raised_goaway_) {
ASSERT(frame->hd.stream_id == 0);
raised_goaway_ = true;
callbacks().onGoAway();
return 0;
}
StreamImpl* stream = getStream(frame->hd.stream_id);
if (!stream) {
return 0;
}
switch (frame->hd.type) {
case NGHTTP2_HEADERS: {
stream->remote_end_stream_ = frame->hd.flags & NGHTTP2_FLAG_END_STREAM;
if (!stream->cookies_.empty()) {
HeaderString key(Headers::get().Cookie);
stream->headers_->addViaMove(std::move(key), std::move(stream->cookies_));
}
switch (frame->headers.cat) {
case NGHTTP2_HCAT_RESPONSE: {
if (CodeUtility::is1xx(Http::Utility::getResponseStatus(*stream->headers_))) {
stream->waiting_for_non_informational_headers_ = true;
}
if (stream->headers_->Status()->value() == "100") {
ASSERT(!stream->remote_end_stream_);
stream->decoder_->decode100ContinueHeaders(std::move(stream->headers_));
} else {
stream->decodeHeaders();
}
break;
}
case NGHTTP2_HCAT_REQUEST: {
stream->decodeHeaders();
break;
}
case NGHTTP2_HCAT_HEADERS: {
// It's possible that we are waiting to send a deferred reset, so only raise headers/trailers
// if local is not complete.
if (!stream->deferred_reset_) {
if (!stream->waiting_for_non_informational_headers_) {
if (!stream->remote_end_stream_) {
// This indicates we have received more headers frames than Envoy
// supports. Even if this is valid HTTP (something like 103 early hints) fail here
// rather than trying to push unexpected headers through the Envoy pipeline as that
// will likely result in Envoy crashing.
// It would be cleaner to reset the stream rather than reset the/ entire connection but
// it's also slightly more dangerous so currently we err on the side of safety.
stats_.too_many_header_frames_.inc();
throw CodecProtocolException("Unexpected 'trailers' with no end stream.");
} else {
stream->decoder_->decodeTrailers(std::move(stream->headers_));
}
} else {
ASSERT(!nghttp2_session_check_server_session(session_));
stream->waiting_for_non_informational_headers_ = false;
// Even if we have :status 100 in the client case in a response, when
// we received a 1xx to start out with, nghttp2 message checking
// guarantees proper flow here.
stream->decodeHeaders();
}
}
break;
}
default:
// We do not currently support push.
NOT_IMPLEMENTED_GCOVR_EXCL_LINE;
}
stream->headers_.reset();
break;
}
case NGHTTP2_DATA: {
stream->remote_end_stream_ = frame->hd.flags & NGHTTP2_FLAG_END_STREAM;
// It's possible that we are waiting to send a deferred reset, so only raise data if local
// is not complete.
if (!stream->deferred_reset_) {
stream->decoder_->decodeData(stream->pending_recv_data_, stream->remote_end_stream_);
}
stream->pending_recv_data_.drain(stream->pending_recv_data_.length());
break;
}
case NGHTTP2_RST_STREAM: {
ENVOY_CONN_LOG(trace, "remote reset: {}", connection_, frame->rst_stream.error_code);
stats_.rx_reset_.inc();
break;
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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: HeaderMapImpl::HeaderEntryImpl& HeaderMapImpl::maybeCreateInline(HeaderEntryImpl** entry,
const LowerCaseString& key) {
if (*entry) {
return **entry;
}
std::list<HeaderEntryImpl>::iterator i = headers_.insert(key);
i->entry_ = i;
*entry = &(*i);
return **entry;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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 ConnectionImpl::onHeaderValue(const char* data, size_t length) {
if (header_parsing_state_ == HeaderParsingState::Done) {
// Ignore trailers.
return;
}
const absl::string_view header_value = absl::string_view(data, length);
if (strict_header_validation_) {
if (!Http::HeaderUtility::headerIsValid(header_value)) {
ENVOY_CONN_LOG(debug, "invalid header value: {}", connection_, header_value);
error_code_ = Http::Code::BadRequest;
sendProtocolError();
throw CodecProtocolException("http/1.1 protocol error: header value contains invalid chars");
}
} else if (header_value.find('\0') != absl::string_view::npos) {
// http-parser should filter for this
// (https://tools.ietf.org/html/rfc7230#section-3.2.6), but it doesn't today. HeaderStrings
// have an invariant that they must not contain embedded zero characters
// (NUL, ASCII 0x0).
throw CodecProtocolException("http/1.1 protocol error: header value contains NUL");
}
header_parsing_state_ = HeaderParsingState::Value;
current_header_value_.append(data, length);
const uint32_t total =
current_header_field_.size() + current_header_value_.size() + current_header_map_->byteSize();
if (total > (max_request_headers_kb_ * 1024)) {
error_code_ = Http::Code::RequestHeaderFieldsTooLarge;
sendProtocolError();
throw CodecProtocolException("headers size exceeds limit");
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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 HeaderMapImpl::removeInline(HeaderEntryImpl** ptr_to_entry) {
if (!*ptr_to_entry) {
return;
}
HeaderEntryImpl* entry = *ptr_to_entry;
*ptr_to_entry = nullptr;
headers_.erase(entry->entry_);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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(HeaderMapImplTest, SetReferenceKey) {
HeaderMapImpl headers;
LowerCaseString foo("hello");
headers.setReferenceKey(foo, "world");
EXPECT_NE("world", headers.get(foo)->value().getStringView().data());
EXPECT_EQ("world", headers.get(foo)->value().getStringView());
headers.setReferenceKey(foo, "monde");
EXPECT_NE("monde", headers.get(foo)->value().getStringView().data());
EXPECT_EQ("monde", headers.get(foo)->value().getStringView());
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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 HeaderMapImpl::removePrefix(const LowerCaseString& prefix) {
headers_.remove_if([&](const HeaderEntryImpl& entry) {
bool to_remove = absl::StartsWith(entry.key().getStringView(), prefix.get());
if (to_remove) {
// If this header should be removed, make sure any references in the
// static lookup table are cleared as well.
EntryCb cb = ConstSingleton<StaticLookupTable>::get().find(entry.key().getStringView());
if (cb) {
StaticLookupResponse ref_lookup_response = cb(*this);
if (ref_lookup_response.entry_) {
*ref_lookup_response.entry_ = nullptr;
}
}
}
return to_remove;
});
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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(HeaderMapImplTest, Remove) {
HeaderMapImpl headers;
// Add random header and then remove by name.
LowerCaseString static_key("hello");
std::string ref_value("value");
headers.addReference(static_key, ref_value);
EXPECT_EQ("value", headers.get(static_key)->value().getStringView());
EXPECT_EQ(HeaderString::Type::Reference, headers.get(static_key)->value().type());
EXPECT_EQ(1UL, headers.size());
EXPECT_FALSE(headers.empty());
headers.remove(static_key);
EXPECT_EQ(nullptr, headers.get(static_key));
EXPECT_EQ(0UL, headers.size());
EXPECT_TRUE(headers.empty());
// Add and remove by inline.
headers.insertContentLength().value(5);
EXPECT_EQ("5", headers.ContentLength()->value().getStringView());
EXPECT_EQ(1UL, headers.size());
EXPECT_FALSE(headers.empty());
headers.removeContentLength();
EXPECT_EQ(nullptr, headers.ContentLength());
EXPECT_EQ(0UL, headers.size());
EXPECT_TRUE(headers.empty());
// Add inline and remove by name.
headers.insertContentLength().value(5);
EXPECT_EQ("5", headers.ContentLength()->value().getStringView());
EXPECT_EQ(1UL, headers.size());
EXPECT_FALSE(headers.empty());
headers.remove(Headers::get().ContentLength);
EXPECT_EQ(nullptr, headers.ContentLength());
EXPECT_EQ(0UL, headers.size());
EXPECT_TRUE(headers.empty());
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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: Filter::UpstreamRequest::~UpstreamRequest() {
if (span_ != nullptr) {
Tracing::HttpTracerUtility::finalizeUpstreamSpan(*span_, upstream_headers_.get(),
upstream_trailers_.get(), stream_info_,
Tracing::EgressConfig::get());
}
if (per_try_timeout_ != nullptr) {
// Allows for testing.
per_try_timeout_->disableTimer();
}
clearRequestEncoder();
stream_info_.setUpstreamTiming(upstream_timing_);
stream_info_.onRequestComplete();
for (const auto& upstream_log : parent_.config_.upstream_logs_) {
upstream_log->log(parent_.downstream_headers_, upstream_headers_.get(),
upstream_trailers_.get(), stream_info_);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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_F(HttpConnectionManagerImplTest, OverlyLongHeadersRejected) {
setup(false, "");
std::string response_code;
std::string response_body;
EXPECT_CALL(*codec_, dispatch(_)).WillOnce(Invoke([&](Buffer::Instance&) -> void {
StreamDecoder* decoder = &conn_manager_->newStream(response_encoder_);
HeaderMapPtr headers{
new TestHeaderMapImpl{{":authority", "host"}, {":path", "/"}, {":method", "GET"}}};
headers->addCopy(LowerCaseString("Foo"), std::string(60 * 1024, 'a'));
EXPECT_CALL(response_encoder_, encodeHeaders(_, true))
.WillOnce(Invoke([&response_code](const HeaderMap& headers, bool) -> void {
response_code = std::string(headers.Status()->value().getStringView());
}));
decoder->decodeHeaders(std::move(headers), true);
conn_manager_->newStream(response_encoder_);
}));
Buffer::OwnedImpl fake_input("1234");
conn_manager_->onData(fake_input, false); // kick off request
EXPECT_EQ("431", response_code);
EXPECT_EQ("", response_body);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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_P(Http2CodecImplTest, TestLargeRequestHeadersAtLimitAccepted) {
uint32_t codec_limit_kb = 64;
max_request_headers_kb_ = codec_limit_kb;
initialize();
TestHeaderMapImpl request_headers;
HttpTestUtility::addDefaultHeaders(request_headers);
std::string key = "big";
uint32_t head_room = 77;
uint32_t long_string_length =
codec_limit_kb * 1024 - request_headers.byteSize() - key.length() - head_room;
std::string long_string = std::string(long_string_length, 'q');
request_headers.addCopy(key, long_string);
// The amount of data sent to the codec is not equivalent to the size of the
// request headers that Envoy computes, as the codec limits based on the
// entire http2 frame. The exact head room needed (76) was found through iteration.
ASSERT_EQ(request_headers.byteSize() + head_room, codec_limit_kb * 1024);
EXPECT_CALL(request_decoder_, decodeHeaders_(_, _));
request_encoder_->encodeHeaders(request_headers, true);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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: const HeaderEntry* HeaderMapImpl::get(const LowerCaseString& key) const {
for (const HeaderEntryImpl& header : headers_) {
if (header.key() == key.get().c_str()) {
return &header;
}
}
return nullptr;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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(HeaderMapImplTest, AddCopy) {
HeaderMapImpl headers;
// Start with a string value.
std::unique_ptr<LowerCaseString> lcKeyPtr(new LowerCaseString("hello"));
headers.addCopy(*lcKeyPtr, "world");
const HeaderString& value = headers.get(*lcKeyPtr)->value();
EXPECT_EQ("world", value.getStringView());
EXPECT_EQ(5UL, value.size());
lcKeyPtr.reset();
const HeaderString& value2 = headers.get(LowerCaseString("hello"))->value();
EXPECT_EQ("world", value2.getStringView());
EXPECT_EQ(5UL, value2.size());
EXPECT_EQ(value.getStringView(), value2.getStringView());
EXPECT_EQ(1UL, headers.size());
// Repeat with an int value.
//
// addReferenceKey and addCopy can both add multiple instances of a
// given header, so we need to delete the old "hello" header.
headers.remove(LowerCaseString("hello"));
// Build "hello" with string concatenation to make it unlikely that the
// compiler is just reusing the same string constant for everything.
lcKeyPtr = std::make_unique<LowerCaseString>(std::string("he") + "llo");
EXPECT_STREQ("hello", lcKeyPtr->get().c_str());
headers.addCopy(*lcKeyPtr, 42);
const HeaderString& value3 = headers.get(*lcKeyPtr)->value();
EXPECT_EQ("42", value3.getStringView());
EXPECT_EQ(2UL, value3.size());
lcKeyPtr.reset();
const HeaderString& value4 = headers.get(LowerCaseString("hello"))->value();
EXPECT_EQ("42", value4.getStringView());
EXPECT_EQ(2UL, value4.size());
EXPECT_EQ(1UL, headers.size());
// Here, again, we'll build yet another key string.
LowerCaseString lcKey3(std::string("he") + "ll" + "o");
EXPECT_STREQ("hello", lcKey3.get().c_str());
EXPECT_EQ("42", headers.get(lcKey3)->value().getStringView());
EXPECT_EQ(2UL, headers.get(lcKey3)->value().size());
LowerCaseString cache_control("cache-control");
headers.addCopy(cache_control, "max-age=1345");
EXPECT_EQ("max-age=1345", headers.get(cache_control)->value().getStringView());
EXPECT_EQ("max-age=1345", headers.CacheControl()->value().getStringView());
headers.addCopy(cache_control, "public");
EXPECT_EQ("max-age=1345,public", headers.get(cache_control)->value().getStringView());
headers.addCopy(cache_control, "");
EXPECT_EQ("max-age=1345,public", headers.get(cache_control)->value().getStringView());
headers.addCopy(cache_control, 123);
EXPECT_EQ("max-age=1345,public,123", headers.get(cache_control)->value().getStringView());
headers.addCopy(cache_control, std::numeric_limits<uint64_t>::max());
EXPECT_EQ("max-age=1345,public,123,18446744073709551615",
headers.get(cache_control)->value().getStringView());
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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_F(HttpConnectionManagerImplTest, OverlyLongHeadersAcceptedIfConfigured) {
max_request_headers_kb_ = 62;
setup(false, "");
EXPECT_CALL(*codec_, dispatch(_)).WillOnce(Invoke([&](Buffer::Instance&) -> void {
StreamDecoder* decoder = &conn_manager_->newStream(response_encoder_);
HeaderMapPtr headers{
new TestHeaderMapImpl{{":authority", "host"}, {":path", "/"}, {":method", "GET"}}};
headers->addCopy(LowerCaseString("Foo"), std::string(60 * 1024, 'a'));
EXPECT_CALL(response_encoder_, encodeHeaders(_, _)).Times(0);
decoder->decodeHeaders(std::move(headers), true);
conn_manager_->newStream(response_encoder_);
}));
Buffer::OwnedImpl fake_input("1234");
conn_manager_->onData(fake_input, false); // kick off request
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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 HeaderMapImpl::addViaMove(HeaderString&& key, HeaderString&& value) {
// If this is an inline header, we can't addViaMove, because we'll overwrite
// the existing value.
auto* entry = getExistingInline(key.getStringView());
if (entry != nullptr) {
appendToHeader(entry->value(), value.getStringView());
key.clear();
value.clear();
} else {
insertByKey(std::move(key), std::move(value));
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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(HeaderMapImplTest, DoubleCookieAdd) {
HeaderMapImpl headers;
const std::string foo("foo");
const std::string bar("bar");
const LowerCaseString& set_cookie = Http::Headers::get().SetCookie;
headers.addReference(set_cookie, foo);
headers.addReference(set_cookie, bar);
EXPECT_EQ(2UL, headers.size());
std::vector<absl::string_view> out;
Http::HeaderUtility::getAllOfHeader(headers, "set-cookie", out);
ASSERT_EQ(out.size(), 2);
ASSERT_EQ(out[0], "foo");
ASSERT_EQ(out[1], "bar");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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(HeaderMapImplTest, LargeCharInHeader) {
HeaderMapImpl headers;
LowerCaseString static_key("\x90hello");
std::string ref_value("value");
headers.addReference(static_key, ref_value);
EXPECT_EQ("value", headers.get(static_key)->value().getStringView());
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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: ConnectionManagerImpl::ActiveStream::~ActiveStream() {
stream_info_.onRequestComplete();
// A downstream disconnect can be identified for HTTP requests when the upstream returns with a 0
// response code and when no other response flags are set.
if (!stream_info_.hasAnyResponseFlag() && !stream_info_.responseCode()) {
stream_info_.setResponseFlag(StreamInfo::ResponseFlag::DownstreamConnectionTermination);
}
connection_manager_.stats_.named_.downstream_rq_active_.dec();
for (const AccessLog::InstanceSharedPtr& access_log : connection_manager_.config_.accessLogs()) {
access_log->log(request_headers_.get(), response_headers_.get(), response_trailers_.get(),
stream_info_);
}
for (const auto& log_handler : access_log_handlers_) {
log_handler->log(request_headers_.get(), response_headers_.get(), response_trailers_.get(),
stream_info_);
}
if (stream_info_.healthCheck()) {
connection_manager_.config_.tracingStats().health_check_.inc();
}
if (active_span_) {
Tracing::HttpTracerUtility::finalizeDownstreamSpan(
*active_span_, request_headers_.get(), response_headers_.get(), response_trailers_.get(),
stream_info_, *this);
}
if (state_.successful_upgrade_) {
connection_manager_.stats_.named_.downstream_cx_upgrades_active_.dec();
}
ASSERT(state_.filter_call_state_ == 0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.
Introduces a cached byte size updated internally in HeaderMap. The value
is stored as an optional, and is cleared whenever a non-const pointer or
reference to a HeaderEntry is accessed. The cached value can be set with
refreshByteSize() which performs an iteration over the HeaderMap to sum
the size of each key and value in the HeaderMap.
Signed-off-by: Asra Ali <[email protected]>'</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: Stream *Parser::makeStream(Object &&dict, Guchar *fileKey,
CryptAlgorithm encAlgorithm, int keyLength,
int objNum, int objGen, int recursion,
GBool strict) {
BaseStream *baseStr;
Stream *str;
Goffset length;
Goffset pos, endPos;
// get stream start position
lexer->skipToNextLine();
if (!(str = lexer->getStream())) {
return nullptr;
}
pos = str->getPos();
// get length
Object obj = dict.dictLookup("Length", recursion);
if (obj.isInt()) {
length = obj.getInt();
} else if (obj.isInt64()) {
length = obj.getInt64();
} else {
error(errSyntaxError, getPos(), "Bad 'Length' attribute in stream");
if (strict) return nullptr;
length = 0;
}
// check for length in damaged file
if (xref && xref->getStreamEnd(pos, &endPos)) {
length = endPos - pos;
}
// in badly damaged PDF files, we can run off the end of the input
// stream immediately after the "stream" token
if (!lexer->getStream()) {
return nullptr;
}
baseStr = lexer->getStream()->getBaseStream();
// skip over stream data
if (Lexer::LOOK_VALUE_NOT_CACHED != lexer->lookCharLastValueCached) {
// take into account the fact that we've cached one value
pos = pos - 1;
lexer->lookCharLastValueCached = Lexer::LOOK_VALUE_NOT_CACHED;
}
lexer->setPos(pos + length);
// refill token buffers and check for 'endstream'
shift(); // kill '>>'
shift("endstream", objNum); // kill 'stream'
if (buf1.isCmd("endstream")) {
shift();
} else {
error(errSyntaxError, getPos(), "Missing 'endstream' or incorrect stream length");
if (strict) return nullptr;
if (xref && lexer->getStream()) {
// shift until we find the proper endstream or we change to another object or reach eof
length = lexer->getPos() - pos;
if (buf1.isCmd("endstream")) {
dict.dictSet("Length", Object(length));
}
} else {
// When building the xref we can't use it so use this
// kludge for broken PDF files: just add 5k to the length, and
// hope its enough
length += 5000;
}
}
// make base stream
str = baseStr->makeSubStream(pos, gTrue, length, std::move(dict));
// handle decryption
if (fileKey) {
str = new DecryptStream(str, fileKey, encAlgorithm, keyLength,
objNum, objGen);
}
// get filters
str = str->addFilters(str->getDict(), recursion);
return str;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'Parser::makeStream: Fix potential integer 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: void rds6_inc_info_copy(struct rds_incoming *inc,
struct rds_info_iterator *iter,
struct in6_addr *saddr, struct in6_addr *daddr,
int flip)
{
struct rds6_info_message minfo6;
minfo6.seq = be64_to_cpu(inc->i_hdr.h_sequence);
minfo6.len = be32_to_cpu(inc->i_hdr.h_len);
if (flip) {
minfo6.laddr = *daddr;
minfo6.faddr = *saddr;
minfo6.lport = inc->i_hdr.h_dport;
minfo6.fport = inc->i_hdr.h_sport;
} else {
minfo6.laddr = *saddr;
minfo6.faddr = *daddr;
minfo6.lport = inc->i_hdr.h_sport;
minfo6.fport = inc->i_hdr.h_dport;
}
rds_info_copy(iter, &minfo6, sizeof(minfo6));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-909'], 'message': 'net/rds: Fix info leak in rds6_inc_info_copy()
The rds6_inc_info_copy() function has a couple struct members which
are leaking stack information. The ->tos field should hold actual
information and the ->flags field needs to be zeroed out.
Fixes: 3eb450367d08 ("rds: add type of service(tos) infrastructure")
Fixes: b7ff8b1036f0 ("rds: Extend RDS API for IPv6 support")
Reported-by: 黄ID蝴蝶 <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Ka-Cheong Poon <[email protected]>
Acked-by: Santosh Shilimkar <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</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: http1_dissect_hdrs(struct http *hp, char *p, struct http_conn *htc,
unsigned maxhdr)
{
char *q, *r, *s;
int i;
assert(p > htc->rxbuf_b);
assert(p <= htc->rxbuf_e);
hp->nhd = HTTP_HDR_FIRST;
r = NULL; /* For FlexeLint */
for (; p < htc->rxbuf_e; p = r) {
/* Find end of next header */
q = r = p;
if (vct_iscrlf(p, htc->rxbuf_e))
break;
while (r < htc->rxbuf_e) {
if (!vct_isctl(*r) || vct_issp(*r)) {
r++;
continue;
}
if (!vct_iscrlf(r, htc->rxbuf_e)) {
VSLb(hp->vsl, SLT_BogoHeader,
"Header has ctrl char 0x%02x", *r);
return (400);
}
q = r;
assert(r < htc->rxbuf_e);
r = vct_skipcrlf(r, htc->rxbuf_e);
if (r >= htc->rxbuf_e)
break;
if (vct_iscrlf(r, htc->rxbuf_e))
break;
/* If line does not continue: got it. */
if (!vct_issp(*r))
break;
/* Clear line continuation LWS to spaces */
while (q < r)
*q++ = ' ';
while (q < htc->rxbuf_e && vct_issp(*q))
*q++ = ' ';
}
/* Empty header = end of headers */
if (p == q)
break;
if (q - p > maxhdr) {
VSLb(hp->vsl, SLT_BogoHeader, "Header too long: %.*s",
(int)(q - p > 20 ? 20 : q - p), p);
return (400);
}
if (vct_islws(*p)) {
VSLb(hp->vsl, SLT_BogoHeader,
"1st header has white space: %.*s",
(int)(q - p > 20 ? 20 : q - p), p);
return (400);
}
if (*p == ':') {
VSLb(hp->vsl, SLT_BogoHeader,
"Missing header name: %.*s",
(int)(q - p > 20 ? 20 : q - p), p);
return (400);
}
while (q > p && vct_issp(q[-1]))
q--;
*q = '\0';
for (s = p; *s != ':' && s < q; s++) {
if (!vct_istchar(*s)) {
VSLb(hp->vsl, SLT_BogoHeader,
"Illegal char 0x%02x in header name", *s);
return (400);
}
}
if (*s != ':') {
VSLb(hp->vsl, SLT_BogoHeader, "Header without ':' %.*s",
(int)(q - p > 20 ? 20 : q - p), p);
return (400);
}
if (hp->nhd < hp->shd) {
hp->hdf[hp->nhd] = 0;
hp->hd[hp->nhd].b = p;
hp->hd[hp->nhd].e = q;
hp->nhd++;
} else {
VSLb(hp->vsl, SLT_BogoHeader, "Too many headers: %.*s",
(int)(q - p > 20 ? 20 : q - p), p);
return (400);
}
}
i = vct_iscrlf(p, htc->rxbuf_e);
assert(i > 0); /* HTTP1_Complete guarantees this */
p += i;
HTC_RxPipeline(htc, p);
htc->rxbuf_e = p;
return (0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-617'], 'message': 'Avoid some code duplication
Apply some adjustments to recent patches based off of review by Nils
Goroll at UPLEX (@nigoroll)'</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: _handle_single_connection (int sockin, int sockout)
{
const char *plugin_name;
int ret = -1, r;
struct connection *conn;
int nworkers = threads ? threads : DEFAULT_PARALLEL_REQUESTS;
pthread_t *workers = NULL;
if (backend->thread_model (backend) < NBDKIT_THREAD_MODEL_PARALLEL ||
nworkers == 1)
nworkers = 0;
conn = new_connection (sockin, sockout, nworkers);
if (!conn)
goto done;
lock_request (conn);
r = backend_open (backend, conn, read_only);
unlock_request (conn);
if (r == -1)
goto done;
/* NB: because of an asynchronous exit backend can be set to NULL at
* just about any time.
*/
if (backend)
plugin_name = backend->plugin_name (backend);
else
plugin_name = "(unknown)";
threadlocal_set_name (plugin_name);
/* Prepare (for filters), called just after open. */
lock_request (conn);
if (backend)
r = backend_prepare (backend, conn);
else
r = 0;
unlock_request (conn);
if (r == -1)
goto done;
/* Handshake. */
if (protocol_handshake (conn) == -1)
goto done;
if (!nworkers) {
/* No need for a separate thread. */
debug ("handshake complete, processing requests serially");
while (!quit && connection_get_status (conn) > 0)
protocol_recv_request_send_reply (conn);
}
else {
/* Create thread pool to process requests. */
debug ("handshake complete, processing requests with %d threads",
nworkers);
workers = calloc (nworkers, sizeof *workers);
if (!workers) {
perror ("malloc");
goto done;
}
for (nworkers = 0; nworkers < conn->nworkers; nworkers++) {
struct worker_data *worker = malloc (sizeof *worker);
int err;
if (!worker) {
perror ("malloc");
connection_set_status (conn, -1);
goto wait;
}
if (asprintf (&worker->name, "%s.%d", plugin_name, nworkers) < 0) {
perror ("asprintf");
connection_set_status (conn, -1);
free (worker);
goto wait;
}
worker->conn = conn;
err = pthread_create (&workers[nworkers], NULL, connection_worker,
worker);
if (err) {
errno = err;
perror ("pthread_create");
connection_set_status (conn, -1);
free (worker);
goto wait;
}
}
wait:
while (nworkers)
pthread_join (workers[--nworkers], NULL);
free (workers);
}
/* Finalize (for filters), called just before close. */
lock_request (conn);
if (backend)
r = backend->finalize (backend, conn);
else
r = 0;
unlock_request (conn);
if (r == -1)
goto done;
ret = connection_get_status (conn);
done:
free_connection (conn);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-406'], 'message': 'server: Wait until handshake complete before calling .open callback
Currently we call the plugin .open callback as soon as we receive a
TCP connection:
$ nbdkit -fv --tls=require --tls-certificates=tests/pki null \
--run "telnet localhost 10809"
[...]
Trying ::1...
Connected to localhost.
Escape character is '^]'.
nbdkit: debug: accepted connection
nbdkit: debug: null: open readonly=0 ◀ NOTE
nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3
NBDMAGICIHAVEOPT
In plugins such as curl, guestfs, ssh, vddk and others we do a
considerable amount of work in the .open callback (such as making a
remote connection or launching an appliance). Therefore we are
providing an easy Denial of Service / Amplification Attack for
unauthorized clients to cause a lot of work to be done for only the
cost of a simple TCP 3 way handshake.
This commit moves the call to the .open callback after the NBD
handshake has mostly completed. In particular TLS authentication must
be complete before we will call into the plugin.
It is unlikely that there are plugins which really depend on the
current behaviour of .open (which I found surprising even though I
guess I must have written it). If there are then we could add a new
.connect callback or similar to allow plugins to get control at the
earlier point in the connection.
After this change you can see that the .open callback is not called
from just a simple TCP connection:
$ ./nbdkit -fv --tls=require --tls-certificates=tests/pki null \
--run "telnet localhost 10809"
[...]
Trying ::1...
Connected to localhost.
Escape character is '^]'.
nbdkit: debug: accepted connection
nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3
NBDMAGICIHAVEOPT
xx
nbdkit: null[1]: debug: newstyle negotiation: client flags: 0xd0a7878
nbdkit: null[1]: error: client requested unknown flags 0xd0a7878
Connection closed by foreign host.
nbdkit: debug: null: unload plugin
Signed-off-by: Richard W.M. Jones <[email protected]>'</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: protocol_compute_eflags (struct connection *conn, uint16_t *flags)
{
uint16_t eflags = NBD_FLAG_HAS_FLAGS;
int fl;
/* Check all flags even if they won't be advertised, to prime the
* cache and make later request validation easier.
*/
fl = backend_can_write (backend, conn);
if (fl == -1)
return -1;
if (!fl)
eflags |= NBD_FLAG_READ_ONLY;
fl = backend_can_zero (backend, conn);
if (fl == -1)
return -1;
if (fl)
eflags |= NBD_FLAG_SEND_WRITE_ZEROES;
fl = backend_can_fast_zero (backend, conn);
if (fl == -1)
return -1;
if (fl)
eflags |= NBD_FLAG_SEND_FAST_ZERO;
fl = backend_can_trim (backend, conn);
if (fl == -1)
return -1;
if (fl)
eflags |= NBD_FLAG_SEND_TRIM;
fl = backend_can_fua (backend, conn);
if (fl == -1)
return -1;
if (fl)
eflags |= NBD_FLAG_SEND_FUA;
fl = backend_can_flush (backend, conn);
if (fl == -1)
return -1;
if (fl)
eflags |= NBD_FLAG_SEND_FLUSH;
fl = backend_is_rotational (backend, conn);
if (fl == -1)
return -1;
if (fl)
eflags |= NBD_FLAG_ROTATIONAL;
/* multi-conn is useless if parallel connections are not allowed. */
fl = backend_can_multi_conn (backend, conn);
if (fl == -1)
return -1;
if (fl && (backend->thread_model (backend) >
NBDKIT_THREAD_MODEL_SERIALIZE_CONNECTIONS))
eflags |= NBD_FLAG_CAN_MULTI_CONN;
fl = backend_can_cache (backend, conn);
if (fl == -1)
return -1;
if (fl)
eflags |= NBD_FLAG_SEND_CACHE;
/* The result of this is not directly advertised as part of the
* handshake, but priming the cache here makes BLOCK_STATUS handling
* not have to worry about errors, and makes test-layers easier to
* write.
*/
fl = backend_can_extents (backend, conn);
if (fl == -1)
return -1;
if (conn->structured_replies)
eflags |= NBD_FLAG_SEND_DF;
*flags = eflags;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-406'], 'message': 'server: Wait until handshake complete before calling .open callback
Currently we call the plugin .open callback as soon as we receive a
TCP connection:
$ nbdkit -fv --tls=require --tls-certificates=tests/pki null \
--run "telnet localhost 10809"
[...]
Trying ::1...
Connected to localhost.
Escape character is '^]'.
nbdkit: debug: accepted connection
nbdkit: debug: null: open readonly=0 ◀ NOTE
nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3
NBDMAGICIHAVEOPT
In plugins such as curl, guestfs, ssh, vddk and others we do a
considerable amount of work in the .open callback (such as making a
remote connection or launching an appliance). Therefore we are
providing an easy Denial of Service / Amplification Attack for
unauthorized clients to cause a lot of work to be done for only the
cost of a simple TCP 3 way handshake.
This commit moves the call to the .open callback after the NBD
handshake has mostly completed. In particular TLS authentication must
be complete before we will call into the plugin.
It is unlikely that there are plugins which really depend on the
current behaviour of .open (which I found surprising even though I
guess I must have written it). If there are then we could add a new
.connect callback or similar to allow plugins to get control at the
earlier point in the connection.
After this change you can see that the .open callback is not called
from just a simple TCP connection:
$ ./nbdkit -fv --tls=require --tls-certificates=tests/pki null \
--run "telnet localhost 10809"
[...]
Trying ::1...
Connected to localhost.
Escape character is '^]'.
nbdkit: debug: accepted connection
nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3
NBDMAGICIHAVEOPT
xx
nbdkit: null[1]: debug: newstyle negotiation: client flags: 0xd0a7878
nbdkit: null[1]: error: client requested unknown flags 0xd0a7878
Connection closed by foreign host.
nbdkit: debug: null: unload plugin
Signed-off-by: Richard W.M. Jones <[email protected]>'</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: protocol_handshake_oldstyle (struct connection *conn)
{
struct old_handshake handshake;
int64_t r;
uint64_t exportsize;
uint16_t gflags, eflags;
/* In --tls=require / FORCEDTLS mode, old style handshakes are
* rejected because they cannot support TLS.
*/
if (tls == 2) {
nbdkit_error ("non-TLS client tried to connect in --tls=require mode");
return -1;
}
r = backend_get_size (backend, conn);
if (r == -1)
return -1;
if (r < 0) {
nbdkit_error (".get_size function returned invalid value "
"(%" PRIi64 ")", r);
return -1;
}
exportsize = (uint64_t) r;
gflags = 0;
if (protocol_compute_eflags (conn, &eflags) < 0)
return -1;
debug ("oldstyle negotiation: flags: global 0x%x export 0x%x",
gflags, eflags);
memset (&handshake, 0, sizeof handshake);
memcpy (handshake.nbdmagic, "NBDMAGIC", 8);
handshake.version = htobe64 (OLD_VERSION);
handshake.exportsize = htobe64 (exportsize);
handshake.gflags = htobe16 (gflags);
handshake.eflags = htobe16 (eflags);
if (conn->send (conn, &handshake, sizeof handshake, 0) == -1) {
nbdkit_error ("write: %m");
return -1;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-406'], 'message': 'server: Wait until handshake complete before calling .open callback
Currently we call the plugin .open callback as soon as we receive a
TCP connection:
$ nbdkit -fv --tls=require --tls-certificates=tests/pki null \
--run "telnet localhost 10809"
[...]
Trying ::1...
Connected to localhost.
Escape character is '^]'.
nbdkit: debug: accepted connection
nbdkit: debug: null: open readonly=0 ◀ NOTE
nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3
NBDMAGICIHAVEOPT
In plugins such as curl, guestfs, ssh, vddk and others we do a
considerable amount of work in the .open callback (such as making a
remote connection or launching an appliance). Therefore we are
providing an easy Denial of Service / Amplification Attack for
unauthorized clients to cause a lot of work to be done for only the
cost of a simple TCP 3 way handshake.
This commit moves the call to the .open callback after the NBD
handshake has mostly completed. In particular TLS authentication must
be complete before we will call into the plugin.
It is unlikely that there are plugins which really depend on the
current behaviour of .open (which I found surprising even though I
guess I must have written it). If there are then we could add a new
.connect callback or similar to allow plugins to get control at the
earlier point in the connection.
After this change you can see that the .open callback is not called
from just a simple TCP connection:
$ ./nbdkit -fv --tls=require --tls-certificates=tests/pki null \
--run "telnet localhost 10809"
[...]
Trying ::1...
Connected to localhost.
Escape character is '^]'.
nbdkit: debug: accepted connection
nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3
NBDMAGICIHAVEOPT
xx
nbdkit: null[1]: debug: newstyle negotiation: client flags: 0xd0a7878
nbdkit: null[1]: error: client requested unknown flags 0xd0a7878
Connection closed by foreign host.
nbdkit: debug: null: unload plugin
Signed-off-by: Richard W.M. Jones <[email protected]>'</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: free_connection (struct connection *conn)
{
if (!conn)
return;
threadlocal_set_conn (NULL);
conn->close (conn);
if (listen_stdin) {
int fd;
/* Restore something to stdin/out so the rest of our code can
* continue to assume that all new fds will be above stderr.
* Swap directions to get EBADF on improper use of stdin/out.
*/
fd = open ("/dev/null", O_WRONLY | O_CLOEXEC);
assert (fd == 0);
fd = open ("/dev/null", O_RDONLY | O_CLOEXEC);
assert (fd == 1);
}
/* Don't call the plugin again if quit has been set because the main
* thread will be in the process of unloading it. The plugin.unload
* callback should always be called.
*/
if (!quit && connection_get_handle (conn, 0)) {
lock_request (conn);
backend->close (backend, conn);
unlock_request (conn);
}
if (conn->status_pipe[0] >= 0) {
close (conn->status_pipe[0]);
close (conn->status_pipe[1]);
}
pthread_mutex_destroy (&conn->request_lock);
pthread_mutex_destroy (&conn->read_lock);
pthread_mutex_destroy (&conn->write_lock);
pthread_mutex_destroy (&conn->status_lock);
free (conn->handles);
free (conn->exportname);
free (conn);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-406'], 'message': 'server: Fix regression for NBD_OPT_INFO before NBD_OPT_GO
Most known NBD clients do not bother with NBD_OPT_INFO (except for
clients like 'qemu-nbd --list' that don't ever intend to connect), but
go straight to NBD_OPT_GO. However, it's not too hard to hack up qemu
to add in an extra client step (whether info on the same name, or more
interestingly, info on a different name), as a patch against qemu
commit 6f214b30445:
| diff --git i/nbd/client.c w/nbd/client.c
| index f6733962b49b..425292ac5ea9 100644
| --- i/nbd/client.c
| +++ w/nbd/client.c
| @@ -1038,6 +1038,14 @@ int nbd_receive_negotiate(AioContext *aio_context, QIOChannel *ioc,
| * TLS). If it is not available, fall back to
| * NBD_OPT_LIST for nicer error messages about a missing
| * export, then use NBD_OPT_EXPORT_NAME. */
| + if (getenv ("HACK"))
| + info->name[0]++;
| + result = nbd_opt_info_or_go(ioc, NBD_OPT_INFO, info, errp);
| + if (getenv ("HACK"))
| + info->name[0]--;
| + if (result < 0) {
| + return -EINVAL;
| + }
| result = nbd_opt_info_or_go(ioc, NBD_OPT_GO, info, errp);
| if (result < 0) {
| return -EINVAL;
This works just fine in 1.14.0, where we call .open only once (so the
INFO and GO repeat calls into the same plugin handle), but in 1.14.1
it regressed into causing an assertion failure: we are now calling
.open a second time on a connection that is already opened:
$ nbdkit -rfv null &
$ hacked-qemu-io -f raw -r nbd://localhost -c quit
...
nbdkit: null[1]: debug: null: open readonly=1
nbdkit: backend.c:179: backend_open: Assertion `h->handle == NULL' failed.
Worse, on the mainline development, we have recently made it possible
for plugins to actively report different information for different
export names; for example, a plugin may choose to report different
answers for .can_write on export A than for export B; but if we share
cached handles, then an NBD_OPT_INFO on one export prevents correct
answers for NBD_OPT_GO on the second export name. (The HACK envvar in
my qemu modifications can be used to demonstrate cross-name requests,
which are even less likely in a real client).
The solution is to call .close after NBD_OPT_INFO, coupled with enough
glue logic to reset cached connection handles back to the state
expected by .open. This in turn means factoring out another backend_*
function, but also gives us an opportunity to change
backend_set_handle to no longer accept NULL.
The assertion failure is, to some extent, a possible denial of service
attack (one client can force nbdkit to exit by merely sending OPT_INFO
before OPT_GO, preventing the next client from connecting), although
this is mitigated by using TLS to weed out untrusted clients. Still,
the fact that we introduced a potential DoS attack while trying to fix
a traffic amplification security bug is not very nice.
Sadly, as there are no known clients that easily trigger this mode of
operation (OPT_INFO before OPT_GO), there is no easy way to cover this
via a testsuite addition. I may end up hacking something into libnbd.
Fixes: c05686f957
Signed-off-by: Eric Blake <[email protected]>'</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: plugin_close (struct backend *b, struct connection *conn)
{
struct backend_plugin *p = container_of (b, struct backend_plugin, backend);
assert (connection_get_handle (conn, 0));
debug ("close");
if (p->plugin.close)
p->plugin.close (connection_get_handle (conn, 0));
backend_set_handle (b, conn, NULL);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-406'], 'message': 'server: Fix regression for NBD_OPT_INFO before NBD_OPT_GO
Most known NBD clients do not bother with NBD_OPT_INFO (except for
clients like 'qemu-nbd --list' that don't ever intend to connect), but
go straight to NBD_OPT_GO. However, it's not too hard to hack up qemu
to add in an extra client step (whether info on the same name, or more
interestingly, info on a different name), as a patch against qemu
commit 6f214b30445:
| diff --git i/nbd/client.c w/nbd/client.c
| index f6733962b49b..425292ac5ea9 100644
| --- i/nbd/client.c
| +++ w/nbd/client.c
| @@ -1038,6 +1038,14 @@ int nbd_receive_negotiate(AioContext *aio_context, QIOChannel *ioc,
| * TLS). If it is not available, fall back to
| * NBD_OPT_LIST for nicer error messages about a missing
| * export, then use NBD_OPT_EXPORT_NAME. */
| + if (getenv ("HACK"))
| + info->name[0]++;
| + result = nbd_opt_info_or_go(ioc, NBD_OPT_INFO, info, errp);
| + if (getenv ("HACK"))
| + info->name[0]--;
| + if (result < 0) {
| + return -EINVAL;
| + }
| result = nbd_opt_info_or_go(ioc, NBD_OPT_GO, info, errp);
| if (result < 0) {
| return -EINVAL;
This works just fine in 1.14.0, where we call .open only once (so the
INFO and GO repeat calls into the same plugin handle), but in 1.14.1
it regressed into causing an assertion failure: we are now calling
.open a second time on a connection that is already opened:
$ nbdkit -rfv null &
$ hacked-qemu-io -f raw -r nbd://localhost -c quit
...
nbdkit: null[1]: debug: null: open readonly=1
nbdkit: backend.c:179: backend_open: Assertion `h->handle == NULL' failed.
Worse, on the mainline development, we have recently made it possible
for plugins to actively report different information for different
export names; for example, a plugin may choose to report different
answers for .can_write on export A than for export B; but if we share
cached handles, then an NBD_OPT_INFO on one export prevents correct
answers for NBD_OPT_GO on the second export name. (The HACK envvar in
my qemu modifications can be used to demonstrate cross-name requests,
which are even less likely in a real client).
The solution is to call .close after NBD_OPT_INFO, coupled with enough
glue logic to reset cached connection handles back to the state
expected by .open. This in turn means factoring out another backend_*
function, but also gives us an opportunity to change
backend_set_handle to no longer accept NULL.
The assertion failure is, to some extent, a possible denial of service
attack (one client can force nbdkit to exit by merely sending OPT_INFO
before OPT_GO, preventing the next client from connecting), although
this is mitigated by using TLS to weed out untrusted clients. Still,
the fact that we introduced a potential DoS attack while trying to fix
a traffic amplification security bug is not very nice.
Sadly, as there are no known clients that easily trigger this mode of
operation (OPT_INFO before OPT_GO), there is no easy way to cover this
via a testsuite addition. I may end up hacking something into libnbd.
Fixes: c05686f957
Signed-off-by: Eric Blake <[email protected]>'</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: protocol_compute_eflags (struct connection *conn, uint16_t *flags)
{
uint16_t eflags = NBD_FLAG_HAS_FLAGS;
int fl;
fl = backend->can_write (backend, conn);
if (fl == -1)
return -1;
if (readonly || !fl) {
eflags |= NBD_FLAG_READ_ONLY;
conn->readonly = true;
}
if (!conn->readonly) {
fl = backend->can_zero (backend, conn);
if (fl == -1)
return -1;
if (fl) {
eflags |= NBD_FLAG_SEND_WRITE_ZEROES;
conn->can_zero = true;
}
fl = backend->can_trim (backend, conn);
if (fl == -1)
return -1;
if (fl) {
eflags |= NBD_FLAG_SEND_TRIM;
conn->can_trim = true;
}
fl = backend->can_fua (backend, conn);
if (fl == -1)
return -1;
if (fl) {
eflags |= NBD_FLAG_SEND_FUA;
conn->can_fua = true;
}
}
fl = backend->can_flush (backend, conn);
if (fl == -1)
return -1;
if (fl) {
eflags |= NBD_FLAG_SEND_FLUSH;
conn->can_flush = true;
}
fl = backend->is_rotational (backend, conn);
if (fl == -1)
return -1;
if (fl) {
eflags |= NBD_FLAG_ROTATIONAL;
conn->is_rotational = true;
}
/* multi-conn is useless if parallel connections are not allowed */
if (backend->thread_model (backend) >
NBDKIT_THREAD_MODEL_SERIALIZE_CONNECTIONS) {
fl = backend->can_multi_conn (backend, conn);
if (fl == -1)
return -1;
if (fl) {
eflags |= NBD_FLAG_CAN_MULTI_CONN;
conn->can_multi_conn = true;
}
}
fl = backend->can_cache (backend, conn);
if (fl == -1)
return -1;
if (fl) {
eflags |= NBD_FLAG_SEND_CACHE;
conn->can_cache = true;
conn->emulate_cache = fl == NBDKIT_CACHE_EMULATE;
}
/* The result of this is not returned to callers here (or at any
* time during the handshake). However it makes sense to do it once
* per connection and store the result in the handle anyway. This
* protocol_compute_eflags function is a bit misnamed XXX.
*/
fl = backend->can_extents (backend, conn);
if (fl == -1)
return -1;
if (fl)
conn->can_extents = true;
if (conn->structured_replies)
eflags |= NBD_FLAG_SEND_DF;
*flags = eflags;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-406'], 'message': 'server: Wait until handshake complete before calling .open callback
Currently we call the plugin .open callback as soon as we receive a
TCP connection:
$ nbdkit -fv --tls=require --tls-certificates=tests/pki null \
--run "telnet localhost 10809"
[...]
Trying ::1...
Connected to localhost.
Escape character is '^]'.
nbdkit: debug: accepted connection
nbdkit: debug: null: open readonly=0 ◀ NOTE
nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3
NBDMAGICIHAVEOPT
In plugins such as curl, guestfs, ssh, vddk and others we do a
considerable amount of work in the .open callback (such as making a
remote connection or launching an appliance). Therefore we are
providing an easy Denial of Service / Amplification Attack for
unauthorized clients to cause a lot of work to be done for only the
cost of a simple TCP 3 way handshake.
This commit moves the call to the .open callback after the NBD
handshake has mostly completed. In particular TLS authentication must
be complete before we will call into the plugin.
It is unlikely that there are plugins which really depend on the
current behaviour of .open (which I found surprising even though I
guess I must have written it). If there are then we could add a new
.connect callback or similar to allow plugins to get control at the
earlier point in the connection.
After this change you can see that the .open callback is not called
from just a simple TCP connection:
$ ./nbdkit -fv --tls=require --tls-certificates=tests/pki null \
--run "telnet localhost 10809"
[...]
Trying ::1...
Connected to localhost.
Escape character is '^]'.
nbdkit: debug: accepted connection
nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3
NBDMAGICIHAVEOPT
xx
nbdkit: null[1]: debug: newstyle negotiation: client flags: 0xd0a7878
nbdkit: null[1]: error: client requested unknown flags 0xd0a7878
Connection closed by foreign host.
nbdkit: debug: null: unload plugin
Signed-off-by: Richard W.M. Jones <[email protected]>
(cherry picked from commit c05686f9577fa91b6a3a4d8c065954ca6fc3fd62)'</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: finish_newstyle_options (struct connection *conn)
{
int64_t r;
r = backend->get_size (backend, conn);
if (r == -1)
return -1;
if (r < 0) {
nbdkit_error (".get_size function returned invalid value "
"(%" PRIi64 ")", r);
return -1;
}
conn->exportsize = (uint64_t) r;
if (protocol_compute_eflags (conn, &conn->eflags) < 0)
return -1;
debug ("newstyle negotiation: flags: export 0x%x", conn->eflags);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-406'], 'message': 'server: Wait until handshake complete before calling .open callback
Currently we call the plugin .open callback as soon as we receive a
TCP connection:
$ nbdkit -fv --tls=require --tls-certificates=tests/pki null \
--run "telnet localhost 10809"
[...]
Trying ::1...
Connected to localhost.
Escape character is '^]'.
nbdkit: debug: accepted connection
nbdkit: debug: null: open readonly=0 ◀ NOTE
nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3
NBDMAGICIHAVEOPT
In plugins such as curl, guestfs, ssh, vddk and others we do a
considerable amount of work in the .open callback (such as making a
remote connection or launching an appliance). Therefore we are
providing an easy Denial of Service / Amplification Attack for
unauthorized clients to cause a lot of work to be done for only the
cost of a simple TCP 3 way handshake.
This commit moves the call to the .open callback after the NBD
handshake has mostly completed. In particular TLS authentication must
be complete before we will call into the plugin.
It is unlikely that there are plugins which really depend on the
current behaviour of .open (which I found surprising even though I
guess I must have written it). If there are then we could add a new
.connect callback or similar to allow plugins to get control at the
earlier point in the connection.
After this change you can see that the .open callback is not called
from just a simple TCP connection:
$ ./nbdkit -fv --tls=require --tls-certificates=tests/pki null \
--run "telnet localhost 10809"
[...]
Trying ::1...
Connected to localhost.
Escape character is '^]'.
nbdkit: debug: accepted connection
nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3
NBDMAGICIHAVEOPT
xx
nbdkit: null[1]: debug: newstyle negotiation: client flags: 0xd0a7878
nbdkit: null[1]: error: client requested unknown flags 0xd0a7878
Connection closed by foreign host.
nbdkit: debug: null: unload plugin
Signed-off-by: Richard W.M. Jones <[email protected]>
(cherry picked from commit c05686f9577fa91b6a3a4d8c065954ca6fc3fd62)'</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: negotiate_handshake_newstyle_options (struct connection *conn)
{
struct new_option new_option;
size_t nr_options;
uint64_t version;
uint32_t option;
uint32_t optlen;
char data[MAX_OPTION_LENGTH+1];
struct new_handshake_finish handshake_finish;
const char *optname;
for (nr_options = 0; nr_options < MAX_NR_OPTIONS; ++nr_options) {
if (conn_recv_full (conn, &new_option, sizeof new_option,
"reading option: conn->recv: %m") == -1)
return -1;
version = be64toh (new_option.version);
if (version != NEW_VERSION) {
nbdkit_error ("unknown option version %" PRIx64
", expecting %" PRIx64,
version, NEW_VERSION);
return -1;
}
/* There is a maximum option length we will accept, regardless
* of the option type.
*/
optlen = be32toh (new_option.optlen);
if (optlen > MAX_OPTION_LENGTH) {
nbdkit_error ("client option data too long (%" PRIu32 ")", optlen);
return -1;
}
option = be32toh (new_option.option);
optname = name_of_nbd_opt (option);
/* In --tls=require / FORCEDTLS mode the only options allowed
* before TLS negotiation are NBD_OPT_ABORT and NBD_OPT_STARTTLS.
*/
if (tls == 2 && !conn->using_tls &&
!(option == NBD_OPT_ABORT || option == NBD_OPT_STARTTLS)) {
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_TLS_REQD))
return -1;
continue;
}
switch (option) {
case NBD_OPT_EXPORT_NAME:
if (conn_recv_full (conn, data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
/* Apart from printing it, ignore the export name. */
data[optlen] = '\0';
debug ("newstyle negotiation: %s: "
"client requested export '%s' (ignored)",
name_of_nbd_opt (option), data);
/* We have to finish the handshake by sending handshake_finish. */
if (finish_newstyle_options (conn) == -1)
return -1;
memset (&handshake_finish, 0, sizeof handshake_finish);
handshake_finish.exportsize = htobe64 (conn->exportsize);
handshake_finish.eflags = htobe16 (conn->eflags);
if (conn->send (conn,
&handshake_finish,
(conn->cflags & NBD_FLAG_NO_ZEROES)
? offsetof (struct new_handshake_finish, zeroes)
: sizeof handshake_finish, 0) == -1) {
nbdkit_error ("write: %s: %m", optname);
return -1;
}
break;
case NBD_OPT_ABORT:
if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)
return -1;
debug ("client sent %s to abort the connection",
name_of_nbd_opt (option));
return -1;
case NBD_OPT_LIST:
if (optlen != 0) {
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (conn, data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
/* Send back the exportname. */
debug ("newstyle negotiation: %s: advertising export '%s'",
name_of_nbd_opt (option), exportname);
if (send_newstyle_option_reply_exportname (conn, option, NBD_REP_SERVER,
exportname) == -1)
return -1;
if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)
return -1;
break;
case NBD_OPT_STARTTLS:
if (optlen != 0) {
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (conn, data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
if (tls == 0) { /* --tls=off (NOTLS mode). */
#ifdef HAVE_GNUTLS
#define NO_TLS_REPLY NBD_REP_ERR_POLICY
#else
#define NO_TLS_REPLY NBD_REP_ERR_UNSUP
#endif
if (send_newstyle_option_reply (conn, option, NO_TLS_REPLY) == -1)
return -1;
}
else /* --tls=on or --tls=require */ {
/* We can't upgrade to TLS twice on the same connection. */
if (conn->using_tls) {
if (send_newstyle_option_reply (conn, option,
NBD_REP_ERR_INVALID) == -1)
return -1;
continue;
}
/* We have to send the (unencrypted) reply before starting
* the handshake.
*/
if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)
return -1;
/* Upgrade the connection to TLS. Also performs access control. */
if (crypto_negotiate_tls (conn, conn->sockin, conn->sockout) == -1)
return -1;
conn->using_tls = true;
debug ("using TLS on this connection");
}
break;
case NBD_OPT_INFO:
case NBD_OPT_GO:
if (conn_recv_full (conn, data, optlen,
"read: %s: %m", optname) == -1)
return -1;
if (optlen < 6) { /* 32 bit export length + 16 bit nr info */
debug ("newstyle negotiation: %s option length < 6", optname);
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
{
uint32_t exportnamelen;
uint16_t nrinfos;
uint16_t info;
size_t i;
CLEANUP_FREE char *requested_exportname = NULL;
/* Validate the name length and number of INFO requests. */
memcpy (&exportnamelen, &data[0], 4);
exportnamelen = be32toh (exportnamelen);
if (exportnamelen > optlen-6 /* NB optlen >= 6, see above */) {
debug ("newstyle negotiation: %s: export name too long", optname);
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
memcpy (&nrinfos, &data[exportnamelen+4], 2);
nrinfos = be16toh (nrinfos);
if (optlen != 4 + exportnamelen + 2 + 2*nrinfos) {
debug ("newstyle negotiation: %s: "
"number of information requests incorrect", optname);
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* As with NBD_OPT_EXPORT_NAME we print the export name and then
* ignore it.
*/
requested_exportname = malloc (exportnamelen+1);
if (requested_exportname == NULL) {
nbdkit_error ("malloc: %m");
return -1;
}
memcpy (requested_exportname, &data[4], exportnamelen);
requested_exportname[exportnamelen] = '\0';
debug ("newstyle negotiation: %s: "
"client requested export '%s' (ignored)",
optname, requested_exportname);
/* The spec is confusing, but it is required that we send back
* NBD_INFO_EXPORT, even if the client did not request it!
* qemu client in particular does not request this, but will
* fail if we don't send it.
*/
if (finish_newstyle_options (conn) == -1)
return -1;
if (send_newstyle_option_reply_info_export (conn, option,
NBD_REP_INFO,
NBD_INFO_EXPORT) == -1)
return -1;
/* For now we ignore all other info requests (but we must
* ignore NBD_INFO_EXPORT if it was requested, because we
* replied already above). Therefore this loop doesn't do
* much at the moment.
*/
for (i = 0; i < nrinfos; ++i) {
memcpy (&info, &data[4 + exportnamelen + 2 + i*2], 2);
info = be16toh (info);
switch (info) {
case NBD_INFO_EXPORT: /* ignore - reply sent above */ break;
default:
debug ("newstyle negotiation: %s: "
"ignoring NBD_INFO_* request %u (%s)",
optname, (unsigned) info, name_of_nbd_info (info));
break;
}
}
}
/* Unlike NBD_OPT_EXPORT_NAME, NBD_OPT_GO sends back an ACK
* or ERROR packet.
*/
if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)
return -1;
break;
case NBD_OPT_STRUCTURED_REPLY:
if (optlen != 0) {
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (conn, data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
debug ("newstyle negotiation: %s: client requested structured replies",
name_of_nbd_opt (option));
if (no_sr) {
/* Must fail with ERR_UNSUP for qemu 4.2 to remain happy;
* but failing with ERR_POLICY would have been nicer.
*/
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_UNSUP) == -1)
return -1;
debug ("newstyle negotiation: %s: structured replies are disabled",
name_of_nbd_opt (option));
break;
}
if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)
return -1;
conn->structured_replies = true;
break;
case NBD_OPT_LIST_META_CONTEXT:
case NBD_OPT_SET_META_CONTEXT:
{
uint32_t opt_index;
uint32_t exportnamelen;
uint32_t nr_queries;
uint32_t querylen;
const char *what;
if (conn_recv_full (conn, data, optlen, "read: %s: %m", optname) == -1)
return -1;
/* Note that we support base:allocation whether or not the plugin
* supports can_extents.
*/
if (!conn->structured_replies) {
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* Minimum length of the option payload is:
* 32 bit export name length followed by empty export name
* + 32 bit number of queries followed by no queries
* = 8 bytes.
*/
what = "optlen < 8";
if (optlen < 8) {
opt_meta_invalid_option_len:
debug ("newstyle negotiation: %s: invalid option length: %s",
optname, what);
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* Discard the export name. */
memcpy (&exportnamelen, &data[0], 4);
exportnamelen = be32toh (exportnamelen);
opt_index = 4 + exportnamelen;
/* Read the number of queries. */
what = "reading number of queries";
if (opt_index+4 > optlen)
goto opt_meta_invalid_option_len;
memcpy (&nr_queries, &data[opt_index], 4);
nr_queries = be32toh (nr_queries);
opt_index += 4;
/* for LIST: nr_queries == 0 means return all meta contexts
* for SET: nr_queries == 0 means reset all contexts
*/
debug ("newstyle negotiation: %s: %s count: %d", optname,
option == NBD_OPT_LIST_META_CONTEXT ? "query" : "set",
nr_queries);
if (nr_queries == 0) {
if (option == NBD_OPT_SET_META_CONTEXT)
conn->meta_context_base_allocation = false;
else /* LIST */ {
if (send_newstyle_option_reply_meta_context
(conn, option, NBD_REP_META_CONTEXT,
0, "base:allocation") == -1)
return -1;
}
if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)
return -1;
}
else {
/* Read and answer each query. */
while (nr_queries > 0) {
what = "reading query string length";
if (opt_index+4 > optlen)
goto opt_meta_invalid_option_len;
memcpy (&querylen, &data[opt_index], 4);
querylen = be32toh (querylen);
opt_index += 4;
what = "reading query string";
if (opt_index + querylen > optlen)
goto opt_meta_invalid_option_len;
debug ("newstyle negotiation: %s: %s %.*s",
optname,
option == NBD_OPT_LIST_META_CONTEXT ? "query" : "set",
(int) querylen, &data[opt_index]);
/* For LIST, "base:" returns all supported contexts in the
* base namespace. We only support "base:allocation".
*/
if (option == NBD_OPT_LIST_META_CONTEXT &&
querylen == 5 &&
strncmp (&data[opt_index], "base:", 5) == 0) {
if (send_newstyle_option_reply_meta_context
(conn, option, NBD_REP_META_CONTEXT,
0, "base:allocation") == -1)
return -1;
}
/* "base:allocation" requested by name. */
else if (querylen == 15 &&
strncmp (&data[opt_index], "base:allocation", 15) == 0) {
if (send_newstyle_option_reply_meta_context
(conn, option, NBD_REP_META_CONTEXT,
option == NBD_OPT_SET_META_CONTEXT
? base_allocation_id : 0,
"base:allocation") == -1)
return -1;
if (option == NBD_OPT_SET_META_CONTEXT)
conn->meta_context_base_allocation = true;
}
/* Every other query must be ignored. */
opt_index += querylen;
nr_queries--;
}
if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)
return -1;
}
debug ("newstyle negotiation: %s: reply complete", optname);
}
break;
default:
/* Unknown option. */
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_UNSUP) == -1)
return -1;
if (conn_recv_full (conn, data, optlen,
"reading unknown option data: conn->recv: %m") == -1)
return -1;
}
/* Note, since it's not very clear from the protocol doc, that the
* client must send NBD_OPT_EXPORT_NAME or NBD_OPT_GO last, and
* that ends option negotiation.
*/
if (option == NBD_OPT_EXPORT_NAME || option == NBD_OPT_GO)
break;
}
if (nr_options >= MAX_NR_OPTIONS) {
nbdkit_error ("client exceeded maximum number of options (%d)",
MAX_NR_OPTIONS);
return -1;
}
/* In --tls=require / FORCEDTLS mode, we must have upgraded to TLS
* by the time we finish option negotiation. If not, give up.
*/
if (tls == 2 && !conn->using_tls) {
nbdkit_error ("non-TLS client tried to connect in --tls=require mode");
return -1;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-406'], 'message': 'server: Fix regression for NBD_OPT_INFO before NBD_OPT_GO
Most known NBD clients do not bother with NBD_OPT_INFO (except for
clients like 'qemu-nbd --list' that don't ever intend to connect), but
go straight to NBD_OPT_GO. However, it's not too hard to hack up qemu
to add in an extra client step (whether info on the same name, or more
interestingly, info on a different name), as a patch against qemu
commit 6f214b30445:
| diff --git i/nbd/client.c w/nbd/client.c
| index f6733962b49b..425292ac5ea9 100644
| --- i/nbd/client.c
| +++ w/nbd/client.c
| @@ -1038,6 +1038,14 @@ int nbd_receive_negotiate(AioContext *aio_context, QIOChannel *ioc,
| * TLS). If it is not available, fall back to
| * NBD_OPT_LIST for nicer error messages about a missing
| * export, then use NBD_OPT_EXPORT_NAME. */
| + if (getenv ("HACK"))
| + info->name[0]++;
| + result = nbd_opt_info_or_go(ioc, NBD_OPT_INFO, info, errp);
| + if (getenv ("HACK"))
| + info->name[0]--;
| + if (result < 0) {
| + return -EINVAL;
| + }
| result = nbd_opt_info_or_go(ioc, NBD_OPT_GO, info, errp);
| if (result < 0) {
| return -EINVAL;
This works just fine in 1.14.0, where we call .open only once (so the
INFO and GO repeat calls into the same plugin handle), but in 1.14.1
it regressed into causing an assertion failure: we are now calling
.open a second time on a connection that is already opened:
$ nbdkit -rfv null &
$ hacked-qemu-io -f raw -r nbd://localhost -c quit
...
nbdkit: null[1]: debug: null: open readonly=1
nbdkit: backend.c:179: backend_open: Assertion `h->handle == NULL' failed.
Worse, on the mainline development, we have recently made it possible
for plugins to actively report different information for different
export names; for example, a plugin may choose to report different
answers for .can_write on export A than for export B; but if we share
cached handles, then an NBD_OPT_INFO on one export prevents correct
answers for NBD_OPT_GO on the second export name. (The HACK envvar in
my qemu modifications can be used to demonstrate cross-name requests,
which are even less likely in a real client).
The solution is to call .close after NBD_OPT_INFO, coupled with enough
glue logic to reset cached connection handles back to the state
expected by .open. This in turn means factoring out another backend_*
function, but also gives us an opportunity to change
backend_set_handle to no longer accept NULL.
The assertion failure is, to some extent, a possible denial of service
attack (one client can force nbdkit to exit by merely sending OPT_INFO
before OPT_GO, preventing the next client from connecting), although
this is mitigated by using TLS to weed out untrusted clients. Still,
the fact that we introduced a potential DoS attack while trying to fix
a traffic amplification security bug is not very nice.
Sadly, as there are no known clients that easily trigger this mode of
operation (OPT_INFO before OPT_GO), there is no easy way to cover this
via a testsuite addition. I may end up hacking something into libnbd.
Fixes: c05686f957
Signed-off-by: Eric Blake <[email protected]>
(cherry picked from commit a6b88b195a959b17524d1c8353fd425d4891dc5f)
Conflicts:
server/backend.c
server/connections.c
server/filters.c
server/internal.h
server/plugins.c
No backend.c in the stable branch, and less things to reset, so instead
ode that logic into filter_close.
Signed-off-by: Eric Blake <[email protected]>'</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: protocol_compute_eflags (struct connection *conn, uint16_t *flags)
{
uint16_t eflags = NBD_FLAG_HAS_FLAGS;
int fl;
fl = backend->can_write (backend, conn);
if (fl == -1)
return -1;
if (readonly || !fl) {
eflags |= NBD_FLAG_READ_ONLY;
conn->readonly = true;
}
if (!conn->readonly) {
fl = backend->can_zero (backend, conn);
if (fl == -1)
return -1;
if (fl) {
eflags |= NBD_FLAG_SEND_WRITE_ZEROES;
conn->can_zero = true;
}
fl = backend->can_trim (backend, conn);
if (fl == -1)
return -1;
if (fl) {
eflags |= NBD_FLAG_SEND_TRIM;
conn->can_trim = true;
}
fl = backend->can_fua (backend, conn);
if (fl == -1)
return -1;
if (fl) {
eflags |= NBD_FLAG_SEND_FUA;
conn->can_fua = true;
}
}
fl = backend->can_flush (backend, conn);
if (fl == -1)
return -1;
if (fl) {
eflags |= NBD_FLAG_SEND_FLUSH;
conn->can_flush = true;
}
fl = backend->is_rotational (backend, conn);
if (fl == -1)
return -1;
if (fl) {
eflags |= NBD_FLAG_ROTATIONAL;
conn->is_rotational = true;
}
/* multi-conn is useless if parallel connections are not allowed */
if (backend->thread_model (backend) >
NBDKIT_THREAD_MODEL_SERIALIZE_CONNECTIONS) {
fl = backend->can_multi_conn (backend, conn);
if (fl == -1)
return -1;
if (fl) {
eflags |= NBD_FLAG_CAN_MULTI_CONN;
conn->can_multi_conn = true;
}
}
/* The result of this is not returned to callers here (or at any
* time during the handshake). However it makes sense to do it once
* per connection and store the result in the handle anyway. This
* protocol_compute_eflags function is a bit misnamed XXX.
*/
fl = backend->can_extents (backend, conn);
if (fl == -1)
return -1;
if (fl)
conn->can_extents = true;
if (conn->structured_replies)
eflags |= NBD_FLAG_SEND_DF;
*flags = eflags;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-406'], 'message': 'server: Wait until handshake complete before calling .open callback
Currently we call the plugin .open callback as soon as we receive a
TCP connection:
$ nbdkit -fv --tls=require --tls-certificates=tests/pki null \
--run "telnet localhost 10809"
[...]
Trying ::1...
Connected to localhost.
Escape character is '^]'.
nbdkit: debug: accepted connection
nbdkit: debug: null: open readonly=0 ◀ NOTE
nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3
NBDMAGICIHAVEOPT
In plugins such as curl, guestfs, ssh, vddk and others we do a
considerable amount of work in the .open callback (such as making a
remote connection or launching an appliance). Therefore we are
providing an easy Denial of Service / Amplification Attack for
unauthorized clients to cause a lot of work to be done for only the
cost of a simple TCP 3 way handshake.
This commit moves the call to the .open callback after the NBD
handshake has mostly completed. In particular TLS authentication must
be complete before we will call into the plugin.
It is unlikely that there are plugins which really depend on the
current behaviour of .open (which I found surprising even though I
guess I must have written it). If there are then we could add a new
.connect callback or similar to allow plugins to get control at the
earlier point in the connection.
After this change you can see that the .open callback is not called
from just a simple TCP connection:
$ ./nbdkit -fv --tls=require --tls-certificates=tests/pki null \
--run "telnet localhost 10809"
[...]
Trying ::1...
Connected to localhost.
Escape character is '^]'.
nbdkit: debug: accepted connection
nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3
NBDMAGICIHAVEOPT
xx
nbdkit: null[1]: debug: newstyle negotiation: client flags: 0xd0a7878
nbdkit: null[1]: error: client requested unknown flags 0xd0a7878
Connection closed by foreign host.
nbdkit: debug: null: unload plugin
Signed-off-by: Richard W.M. Jones <[email protected]>
(cherry picked from commit c05686f9577fa91b6a3a4d8c065954ca6fc3fd62)
(cherry picked from commit e06cde00659ff97182173d0e33fff784041bcb4a)'</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: negotiate_handshake_newstyle_options (struct connection *conn)
{
struct new_option new_option;
size_t nr_options;
uint64_t version;
uint32_t option;
uint32_t optlen;
char data[MAX_OPTION_LENGTH+1];
struct new_handshake_finish handshake_finish;
const char *optname;
for (nr_options = 0; nr_options < MAX_NR_OPTIONS; ++nr_options) {
if (conn_recv_full (conn, &new_option, sizeof new_option,
"reading option: conn->recv: %m") == -1)
return -1;
version = be64toh (new_option.version);
if (version != NEW_VERSION) {
nbdkit_error ("unknown option version %" PRIx64
", expecting %" PRIx64,
version, NEW_VERSION);
return -1;
}
/* There is a maximum option length we will accept, regardless
* of the option type.
*/
optlen = be32toh (new_option.optlen);
if (optlen > MAX_OPTION_LENGTH) {
nbdkit_error ("client option data too long (%" PRIu32 ")", optlen);
return -1;
}
option = be32toh (new_option.option);
optname = name_of_nbd_opt (option);
/* In --tls=require / FORCEDTLS mode the only options allowed
* before TLS negotiation are NBD_OPT_ABORT and NBD_OPT_STARTTLS.
*/
if (tls == 2 && !conn->using_tls &&
!(option == NBD_OPT_ABORT || option == NBD_OPT_STARTTLS)) {
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_TLS_REQD))
return -1;
continue;
}
switch (option) {
case NBD_OPT_EXPORT_NAME:
if (conn_recv_full (conn, data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
/* Apart from printing it, ignore the export name. */
data[optlen] = '\0';
debug ("newstyle negotiation: %s: "
"client requested export '%s' (ignored)",
name_of_nbd_opt (option), data);
/* We have to finish the handshake by sending handshake_finish. */
if (finish_newstyle_options (conn) == -1)
return -1;
memset (&handshake_finish, 0, sizeof handshake_finish);
handshake_finish.exportsize = htobe64 (conn->exportsize);
handshake_finish.eflags = htobe16 (conn->eflags);
if (conn->send (conn,
&handshake_finish,
(conn->cflags & NBD_FLAG_NO_ZEROES)
? offsetof (struct new_handshake_finish, zeroes)
: sizeof handshake_finish) == -1) {
nbdkit_error ("write: %s: %m", optname);
return -1;
}
break;
case NBD_OPT_ABORT:
if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)
return -1;
debug ("client sent %s to abort the connection",
name_of_nbd_opt (option));
return -1;
case NBD_OPT_LIST:
if (optlen != 0) {
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (conn, data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
/* Send back the exportname. */
debug ("newstyle negotiation: %s: advertising export '%s'",
name_of_nbd_opt (option), exportname);
if (send_newstyle_option_reply_exportname (conn, option, NBD_REP_SERVER,
exportname) == -1)
return -1;
if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)
return -1;
break;
case NBD_OPT_STARTTLS:
if (optlen != 0) {
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (conn, data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
if (tls == 0) { /* --tls=off (NOTLS mode). */
#ifdef HAVE_GNUTLS
#define NO_TLS_REPLY NBD_REP_ERR_POLICY
#else
#define NO_TLS_REPLY NBD_REP_ERR_UNSUP
#endif
if (send_newstyle_option_reply (conn, option, NO_TLS_REPLY) == -1)
return -1;
}
else /* --tls=on or --tls=require */ {
/* We can't upgrade to TLS twice on the same connection. */
if (conn->using_tls) {
if (send_newstyle_option_reply (conn, option,
NBD_REP_ERR_INVALID) == -1)
return -1;
continue;
}
/* We have to send the (unencrypted) reply before starting
* the handshake.
*/
if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)
return -1;
/* Upgrade the connection to TLS. Also performs access control. */
if (crypto_negotiate_tls (conn, conn->sockin, conn->sockout) == -1)
return -1;
conn->using_tls = true;
debug ("using TLS on this connection");
}
break;
case NBD_OPT_INFO:
case NBD_OPT_GO:
if (conn_recv_full (conn, data, optlen,
"read: %s: %m", optname) == -1)
return -1;
if (optlen < 6) { /* 32 bit export length + 16 bit nr info */
debug ("newstyle negotiation: %s option length < 6", optname);
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
{
uint32_t exportnamelen;
uint16_t nrinfos;
uint16_t info;
size_t i;
CLEANUP_FREE char *requested_exportname = NULL;
/* Validate the name length and number of INFO requests. */
memcpy (&exportnamelen, &data[0], 4);
exportnamelen = be32toh (exportnamelen);
if (exportnamelen > optlen-6 /* NB optlen >= 6, see above */) {
debug ("newstyle negotiation: %s: export name too long", optname);
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
memcpy (&nrinfos, &data[exportnamelen+4], 2);
nrinfos = be16toh (nrinfos);
if (optlen != 4 + exportnamelen + 2 + 2*nrinfos) {
debug ("newstyle negotiation: %s: "
"number of information requests incorrect", optname);
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* As with NBD_OPT_EXPORT_NAME we print the export name and then
* ignore it.
*/
requested_exportname = malloc (exportnamelen+1);
if (requested_exportname == NULL) {
nbdkit_error ("malloc: %m");
return -1;
}
memcpy (requested_exportname, &data[4], exportnamelen);
requested_exportname[exportnamelen] = '\0';
debug ("newstyle negotiation: %s: "
"client requested export '%s' (ignored)",
optname, requested_exportname);
/* The spec is confusing, but it is required that we send back
* NBD_INFO_EXPORT, even if the client did not request it!
* qemu client in particular does not request this, but will
* fail if we don't send it.
*/
if (finish_newstyle_options (conn) == -1)
return -1;
if (send_newstyle_option_reply_info_export (conn, option,
NBD_REP_INFO,
NBD_INFO_EXPORT) == -1)
return -1;
/* For now we ignore all other info requests (but we must
* ignore NBD_INFO_EXPORT if it was requested, because we
* replied already above). Therefore this loop doesn't do
* much at the moment.
*/
for (i = 0; i < nrinfos; ++i) {
memcpy (&info, &data[4 + exportnamelen + 2 + i*2], 2);
info = be16toh (info);
switch (info) {
case NBD_INFO_EXPORT: /* ignore - reply sent above */ break;
default:
debug ("newstyle negotiation: %s: "
"ignoring NBD_INFO_* request %u (%s)",
optname, (unsigned) info, name_of_nbd_info (info));
break;
}
}
}
/* Unlike NBD_OPT_EXPORT_NAME, NBD_OPT_GO sends back an ACK
* or ERROR packet.
*/
if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)
return -1;
break;
case NBD_OPT_STRUCTURED_REPLY:
if (optlen != 0) {
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (conn, data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
debug ("newstyle negotiation: %s: client requested structured replies",
name_of_nbd_opt (option));
if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)
return -1;
conn->structured_replies = true;
break;
case NBD_OPT_LIST_META_CONTEXT:
case NBD_OPT_SET_META_CONTEXT:
{
uint32_t opt_index;
uint32_t exportnamelen;
uint32_t nr_queries;
uint32_t querylen;
const char *what;
if (conn_recv_full (conn, data, optlen, "read: %s: %m", optname) == -1)
return -1;
if (!conn->structured_replies) {
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* Minimum length of the option payload is:
* 32 bit export name length followed by empty export name
* + 32 bit number of queries followed by no queries
* = 8 bytes.
*/
what = "optlen < 8";
if (optlen < 8) {
opt_meta_invalid_option_len:
debug ("newstyle negotiation: %s: invalid option length: %s",
optname, what);
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* Discard the export name. */
memcpy (&exportnamelen, &data[0], 4);
exportnamelen = be32toh (exportnamelen);
opt_index = 4 + exportnamelen;
/* Read the number of queries. */
what = "reading number of queries";
if (opt_index+4 > optlen)
goto opt_meta_invalid_option_len;
memcpy (&nr_queries, &data[opt_index], 4);
nr_queries = be32toh (nr_queries);
opt_index += 4;
/* for LIST: nr_queries == 0 means return all meta contexts
* for SET: nr_queries == 0 means reset all contexts
*/
debug ("newstyle negotiation: %s: %s count: %d", optname,
option == NBD_OPT_LIST_META_CONTEXT ? "query" : "set",
nr_queries);
if (nr_queries == 0) {
if (option == NBD_OPT_SET_META_CONTEXT)
conn->meta_context_base_allocation = false;
else /* LIST */ {
if (send_newstyle_option_reply_meta_context
(conn, option, NBD_REP_META_CONTEXT,
0, "base:allocation") == -1)
return -1;
}
if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)
return -1;
}
else {
/* Read and answer each query. */
while (nr_queries > 0) {
what = "reading query string length";
if (opt_index+4 > optlen)
goto opt_meta_invalid_option_len;
memcpy (&querylen, &data[opt_index], 4);
querylen = be32toh (querylen);
opt_index += 4;
what = "reading query string";
if (opt_index + querylen > optlen)
goto opt_meta_invalid_option_len;
debug ("newstyle negotiation: %s: %s %.*s",
optname,
option == NBD_OPT_LIST_META_CONTEXT ? "query" : "set",
(int) querylen, &data[opt_index]);
/* For LIST, "base:" returns all supported contexts in the
* base namespace. We only support "base:allocation".
*/
if (option == NBD_OPT_LIST_META_CONTEXT &&
querylen == 5 &&
strncmp (&data[opt_index], "base:", 5) == 0) {
if (send_newstyle_option_reply_meta_context
(conn, option, NBD_REP_META_CONTEXT,
0, "base:allocation") == -1)
return -1;
}
/* "base:allocation" requested by name. */
else if (querylen == 15 &&
strncmp (&data[opt_index], "base:allocation", 15) == 0) {
if (send_newstyle_option_reply_meta_context
(conn, option, NBD_REP_META_CONTEXT,
option == NBD_OPT_SET_META_CONTEXT
? base_allocation_id : 0,
"base:allocation") == -1)
return -1;
if (option == NBD_OPT_SET_META_CONTEXT)
conn->meta_context_base_allocation = true;
}
/* Every other query must be ignored. */
opt_index += querylen;
nr_queries--;
}
if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1)
return -1;
}
debug ("newstyle negotiation: %s: reply complete", optname);
}
break;
default:
/* Unknown option. */
if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_UNSUP) == -1)
return -1;
if (conn_recv_full (conn, data, optlen,
"reading unknown option data: conn->recv: %m") == -1)
return -1;
}
/* Note, since it's not very clear from the protocol doc, that the
* client must send NBD_OPT_EXPORT_NAME or NBD_OPT_GO last, and
* that ends option negotiation.
*/
if (option == NBD_OPT_EXPORT_NAME || option == NBD_OPT_GO)
break;
}
if (nr_options >= MAX_NR_OPTIONS) {
nbdkit_error ("client exceeded maximum number of options (%d)",
MAX_NR_OPTIONS);
return -1;
}
/* In --tls=require / FORCEDTLS mode, we must have upgraded to TLS
* by the time we finish option negotiation. If not, give up.
*/
if (tls == 2 && !conn->using_tls) {
nbdkit_error ("non-TLS client tried to connect in --tls=require mode");
return -1;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-406'], 'message': 'server: Fix regression for NBD_OPT_INFO before NBD_OPT_GO
Most known NBD clients do not bother with NBD_OPT_INFO (except for
clients like 'qemu-nbd --list' that don't ever intend to connect), but
go straight to NBD_OPT_GO. However, it's not too hard to hack up qemu
to add in an extra client step (whether info on the same name, or more
interestingly, info on a different name), as a patch against qemu
commit 6f214b30445:
| diff --git i/nbd/client.c w/nbd/client.c
| index f6733962b49b..425292ac5ea9 100644
| --- i/nbd/client.c
| +++ w/nbd/client.c
| @@ -1038,6 +1038,14 @@ int nbd_receive_negotiate(AioContext *aio_context, QIOChannel *ioc,
| * TLS). If it is not available, fall back to
| * NBD_OPT_LIST for nicer error messages about a missing
| * export, then use NBD_OPT_EXPORT_NAME. */
| + if (getenv ("HACK"))
| + info->name[0]++;
| + result = nbd_opt_info_or_go(ioc, NBD_OPT_INFO, info, errp);
| + if (getenv ("HACK"))
| + info->name[0]--;
| + if (result < 0) {
| + return -EINVAL;
| + }
| result = nbd_opt_info_or_go(ioc, NBD_OPT_GO, info, errp);
| if (result < 0) {
| return -EINVAL;
This works just fine in 1.14.0, where we call .open only once (so the
INFO and GO repeat calls into the same plugin handle), but in 1.14.1
it regressed into causing an assertion failure: we are now calling
.open a second time on a connection that is already opened:
$ nbdkit -rfv null &
$ hacked-qemu-io -f raw -r nbd://localhost -c quit
...
nbdkit: null[1]: debug: null: open readonly=1
nbdkit: backend.c:179: backend_open: Assertion `h->handle == NULL' failed.
Worse, on the mainline development, we have recently made it possible
for plugins to actively report different information for different
export names; for example, a plugin may choose to report different
answers for .can_write on export A than for export B; but if we share
cached handles, then an NBD_OPT_INFO on one export prevents correct
answers for NBD_OPT_GO on the second export name. (The HACK envvar in
my qemu modifications can be used to demonstrate cross-name requests,
which are even less likely in a real client).
The solution is to call .close after NBD_OPT_INFO, coupled with enough
glue logic to reset cached connection handles back to the state
expected by .open. This in turn means factoring out another backend_*
function, but also gives us an opportunity to change
backend_set_handle to no longer accept NULL.
The assertion failure is, to some extent, a possible denial of service
attack (one client can force nbdkit to exit by merely sending OPT_INFO
before OPT_GO, preventing the next client from connecting), although
this is mitigated by using TLS to weed out untrusted clients. Still,
the fact that we introduced a potential DoS attack while trying to fix
a traffic amplification security bug is not very nice.
Sadly, as there are no known clients that easily trigger this mode of
operation (OPT_INFO before OPT_GO), there is no easy way to cover this
via a testsuite addition. I may end up hacking something into libnbd.
Fixes: c05686f957
Signed-off-by: Eric Blake <[email protected]>
(cherry picked from commit a6b88b195a959b17524d1c8353fd425d4891dc5f)
Conflicts:
server/backend.c
server/connections.c
server/filters.c
server/internal.h
server/plugins.c
No backend.c in the stable branch, and less things to reset, so instead
ode that logic into filter_close.
Signed-off-by: Eric Blake <[email protected]>'</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: v9fs_stat2inode_dotl(struct p9_stat_dotl *stat, struct inode *inode)
{
umode_t mode;
struct v9fs_inode *v9inode = V9FS_I(inode);
if ((stat->st_result_mask & P9_STATS_BASIC) == P9_STATS_BASIC) {
inode->i_atime.tv_sec = stat->st_atime_sec;
inode->i_atime.tv_nsec = stat->st_atime_nsec;
inode->i_mtime.tv_sec = stat->st_mtime_sec;
inode->i_mtime.tv_nsec = stat->st_mtime_nsec;
inode->i_ctime.tv_sec = stat->st_ctime_sec;
inode->i_ctime.tv_nsec = stat->st_ctime_nsec;
inode->i_uid = stat->st_uid;
inode->i_gid = stat->st_gid;
set_nlink(inode, stat->st_nlink);
mode = stat->st_mode & S_IALLUGO;
mode |= inode->i_mode & ~S_IALLUGO;
inode->i_mode = mode;
i_size_write(inode, stat->st_size);
inode->i_blocks = stat->st_blocks;
} else {
if (stat->st_result_mask & P9_STATS_ATIME) {
inode->i_atime.tv_sec = stat->st_atime_sec;
inode->i_atime.tv_nsec = stat->st_atime_nsec;
}
if (stat->st_result_mask & P9_STATS_MTIME) {
inode->i_mtime.tv_sec = stat->st_mtime_sec;
inode->i_mtime.tv_nsec = stat->st_mtime_nsec;
}
if (stat->st_result_mask & P9_STATS_CTIME) {
inode->i_ctime.tv_sec = stat->st_ctime_sec;
inode->i_ctime.tv_nsec = stat->st_ctime_nsec;
}
if (stat->st_result_mask & P9_STATS_UID)
inode->i_uid = stat->st_uid;
if (stat->st_result_mask & P9_STATS_GID)
inode->i_gid = stat->st_gid;
if (stat->st_result_mask & P9_STATS_NLINK)
set_nlink(inode, stat->st_nlink);
if (stat->st_result_mask & P9_STATS_MODE) {
inode->i_mode = stat->st_mode;
if ((S_ISBLK(inode->i_mode)) ||
(S_ISCHR(inode->i_mode)))
init_special_inode(inode, inode->i_mode,
inode->i_rdev);
}
if (stat->st_result_mask & P9_STATS_RDEV)
inode->i_rdev = new_decode_dev(stat->st_rdev);
if (stat->st_result_mask & P9_STATS_SIZE)
i_size_write(inode, stat->st_size);
if (stat->st_result_mask & P9_STATS_BLOCKS)
inode->i_blocks = stat->st_blocks;
}
if (stat->st_result_mask & P9_STATS_GEN)
inode->i_generation = stat->st_gen;
/* Currently we don't support P9_STATS_BTIME and P9_STATS_DATA_VERSION
* because the inode structure does not have fields for them.
*/
v9inode->cache_validity &= ~V9FS_INO_INVALID_ATTR;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': '9p: use inode->i_lock to protect i_size_write() under 32-bit
Use inode->i_lock to protect i_size_write(), else i_size_read() in
generic_fillattr() may loop infinitely in read_seqcount_begin() when
multiple processes invoke v9fs_vfs_getattr() or v9fs_vfs_getattr_dotl()
simultaneously under 32-bit SMP environment, and a soft lockup will be
triggered as show below:
watchdog: BUG: soft lockup - CPU#5 stuck for 22s! [stat:2217]
Modules linked in:
CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4
Hardware name: Generic DT based system
PC is at generic_fillattr+0x104/0x108
LR is at 0xec497f00
pc : [<802b8898>] lr : [<ec497f00>] psr: 200c0013
sp : ec497e20 ip : ed608030 fp : ec497e3c
r10: 00000000 r9 : ec497f00 r8 : ed608030
r7 : ec497ebc r6 : ec497f00 r5 : ee5c1550 r4 : ee005780
r3 : 0000052d r2 : 00000000 r1 : ec497f00 r0 : ed608030
Flags: nzCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none
Control: 10c5387d Table: ac48006a DAC: 00000051
CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4
Hardware name: Generic DT based system
Backtrace:
[<8010d974>] (dump_backtrace) from [<8010dc88>] (show_stack+0x20/0x24)
[<8010dc68>] (show_stack) from [<80a1d194>] (dump_stack+0xb0/0xdc)
[<80a1d0e4>] (dump_stack) from [<80109f34>] (show_regs+0x1c/0x20)
[<80109f18>] (show_regs) from [<801d0a80>] (watchdog_timer_fn+0x280/0x2f8)
[<801d0800>] (watchdog_timer_fn) from [<80198658>] (__hrtimer_run_queues+0x18c/0x380)
[<801984cc>] (__hrtimer_run_queues) from [<80198e60>] (hrtimer_run_queues+0xb8/0xf0)
[<80198da8>] (hrtimer_run_queues) from [<801973e8>] (run_local_timers+0x28/0x64)
[<801973c0>] (run_local_timers) from [<80197460>] (update_process_times+0x3c/0x6c)
[<80197424>] (update_process_times) from [<801ab2b8>] (tick_nohz_handler+0xe0/0x1bc)
[<801ab1d8>] (tick_nohz_handler) from [<80843050>] (arch_timer_handler_virt+0x38/0x48)
[<80843018>] (arch_timer_handler_virt) from [<80180a64>] (handle_percpu_devid_irq+0x8c/0x240)
[<801809d8>] (handle_percpu_devid_irq) from [<8017ac20>] (generic_handle_irq+0x34/0x44)
[<8017abec>] (generic_handle_irq) from [<8017b344>] (__handle_domain_irq+0x6c/0xc4)
[<8017b2d8>] (__handle_domain_irq) from [<801022e0>] (gic_handle_irq+0x4c/0x88)
[<80102294>] (gic_handle_irq) from [<80101a30>] (__irq_svc+0x70/0x98)
[<802b8794>] (generic_fillattr) from [<8056b284>] (v9fs_vfs_getattr_dotl+0x74/0xa4)
[<8056b210>] (v9fs_vfs_getattr_dotl) from [<802b8904>] (vfs_getattr_nosec+0x68/0x7c)
[<802b889c>] (vfs_getattr_nosec) from [<802b895c>] (vfs_getattr+0x44/0x48)
[<802b8918>] (vfs_getattr) from [<802b8a74>] (vfs_statx+0x9c/0xec)
[<802b89d8>] (vfs_statx) from [<802b9428>] (sys_lstat64+0x48/0x78)
[<802b93e0>] (sys_lstat64) from [<80101000>] (ret_fast_syscall+0x0/0x28)
[[email protected]: updated comment to not refer to a function
in another subsystem]
Link: http://lkml.kernel.org/r/[email protected]
Cc: [email protected]
Fixes: 7549ae3e81cc ("9p: Use the i_size_[read, write]() macros instead of using inode->i_size directly.")
Reported-by: Xing Gaopeng <[email protected]>
Signed-off-by: Hou Tao <[email protected]>
Signed-off-by: Dominique Martinet <[email protected]>'</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 struct dentry *v9fs_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data)
{
struct super_block *sb = NULL;
struct inode *inode = NULL;
struct dentry *root = NULL;
struct v9fs_session_info *v9ses = NULL;
umode_t mode = S_IRWXUGO | S_ISVTX;
struct p9_fid *fid;
int retval = 0;
p9_debug(P9_DEBUG_VFS, "\n");
v9ses = kzalloc(sizeof(struct v9fs_session_info), GFP_KERNEL);
if (!v9ses)
return ERR_PTR(-ENOMEM);
fid = v9fs_session_init(v9ses, dev_name, data);
if (IS_ERR(fid)) {
retval = PTR_ERR(fid);
goto free_session;
}
sb = sget(fs_type, NULL, v9fs_set_super, flags, v9ses);
if (IS_ERR(sb)) {
retval = PTR_ERR(sb);
goto clunk_fid;
}
retval = v9fs_fill_super(sb, v9ses, flags, data);
if (retval)
goto release_sb;
if (v9ses->cache == CACHE_LOOSE || v9ses->cache == CACHE_FSCACHE)
sb->s_d_op = &v9fs_cached_dentry_operations;
else
sb->s_d_op = &v9fs_dentry_operations;
inode = v9fs_get_inode(sb, S_IFDIR | mode, 0);
if (IS_ERR(inode)) {
retval = PTR_ERR(inode);
goto release_sb;
}
root = d_make_root(inode);
if (!root) {
retval = -ENOMEM;
goto release_sb;
}
sb->s_root = root;
if (v9fs_proto_dotl(v9ses)) {
struct p9_stat_dotl *st = NULL;
st = p9_client_getattr_dotl(fid, P9_STATS_BASIC);
if (IS_ERR(st)) {
retval = PTR_ERR(st);
goto release_sb;
}
d_inode(root)->i_ino = v9fs_qid2ino(&st->qid);
v9fs_stat2inode_dotl(st, d_inode(root));
kfree(st);
} else {
struct p9_wstat *st = NULL;
st = p9_client_stat(fid);
if (IS_ERR(st)) {
retval = PTR_ERR(st);
goto release_sb;
}
d_inode(root)->i_ino = v9fs_qid2ino(&st->qid);
v9fs_stat2inode(st, d_inode(root), sb);
p9stat_free(st);
kfree(st);
}
retval = v9fs_get_acl(inode, fid);
if (retval)
goto release_sb;
v9fs_fid_add(root, fid);
p9_debug(P9_DEBUG_VFS, " simple set mount, return 0\n");
return dget(sb->s_root);
clunk_fid:
p9_client_clunk(fid);
v9fs_session_close(v9ses);
free_session:
kfree(v9ses);
return ERR_PTR(retval);
release_sb:
/*
* we will do the session_close and root dentry release
* in the below call. But we need to clunk fid, because we haven't
* attached the fid to dentry so it won't get clunked
* automatically.
*/
p9_client_clunk(fid);
deactivate_locked_super(sb);
return ERR_PTR(retval);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': '9p: use inode->i_lock to protect i_size_write() under 32-bit
Use inode->i_lock to protect i_size_write(), else i_size_read() in
generic_fillattr() may loop infinitely in read_seqcount_begin() when
multiple processes invoke v9fs_vfs_getattr() or v9fs_vfs_getattr_dotl()
simultaneously under 32-bit SMP environment, and a soft lockup will be
triggered as show below:
watchdog: BUG: soft lockup - CPU#5 stuck for 22s! [stat:2217]
Modules linked in:
CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4
Hardware name: Generic DT based system
PC is at generic_fillattr+0x104/0x108
LR is at 0xec497f00
pc : [<802b8898>] lr : [<ec497f00>] psr: 200c0013
sp : ec497e20 ip : ed608030 fp : ec497e3c
r10: 00000000 r9 : ec497f00 r8 : ed608030
r7 : ec497ebc r6 : ec497f00 r5 : ee5c1550 r4 : ee005780
r3 : 0000052d r2 : 00000000 r1 : ec497f00 r0 : ed608030
Flags: nzCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none
Control: 10c5387d Table: ac48006a DAC: 00000051
CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4
Hardware name: Generic DT based system
Backtrace:
[<8010d974>] (dump_backtrace) from [<8010dc88>] (show_stack+0x20/0x24)
[<8010dc68>] (show_stack) from [<80a1d194>] (dump_stack+0xb0/0xdc)
[<80a1d0e4>] (dump_stack) from [<80109f34>] (show_regs+0x1c/0x20)
[<80109f18>] (show_regs) from [<801d0a80>] (watchdog_timer_fn+0x280/0x2f8)
[<801d0800>] (watchdog_timer_fn) from [<80198658>] (__hrtimer_run_queues+0x18c/0x380)
[<801984cc>] (__hrtimer_run_queues) from [<80198e60>] (hrtimer_run_queues+0xb8/0xf0)
[<80198da8>] (hrtimer_run_queues) from [<801973e8>] (run_local_timers+0x28/0x64)
[<801973c0>] (run_local_timers) from [<80197460>] (update_process_times+0x3c/0x6c)
[<80197424>] (update_process_times) from [<801ab2b8>] (tick_nohz_handler+0xe0/0x1bc)
[<801ab1d8>] (tick_nohz_handler) from [<80843050>] (arch_timer_handler_virt+0x38/0x48)
[<80843018>] (arch_timer_handler_virt) from [<80180a64>] (handle_percpu_devid_irq+0x8c/0x240)
[<801809d8>] (handle_percpu_devid_irq) from [<8017ac20>] (generic_handle_irq+0x34/0x44)
[<8017abec>] (generic_handle_irq) from [<8017b344>] (__handle_domain_irq+0x6c/0xc4)
[<8017b2d8>] (__handle_domain_irq) from [<801022e0>] (gic_handle_irq+0x4c/0x88)
[<80102294>] (gic_handle_irq) from [<80101a30>] (__irq_svc+0x70/0x98)
[<802b8794>] (generic_fillattr) from [<8056b284>] (v9fs_vfs_getattr_dotl+0x74/0xa4)
[<8056b210>] (v9fs_vfs_getattr_dotl) from [<802b8904>] (vfs_getattr_nosec+0x68/0x7c)
[<802b889c>] (vfs_getattr_nosec) from [<802b895c>] (vfs_getattr+0x44/0x48)
[<802b8918>] (vfs_getattr) from [<802b8a74>] (vfs_statx+0x9c/0xec)
[<802b89d8>] (vfs_statx) from [<802b9428>] (sys_lstat64+0x48/0x78)
[<802b93e0>] (sys_lstat64) from [<80101000>] (ret_fast_syscall+0x0/0x28)
[[email protected]: updated comment to not refer to a function
in another subsystem]
Link: http://lkml.kernel.org/r/[email protected]
Cc: [email protected]
Fixes: 7549ae3e81cc ("9p: Use the i_size_[read, write]() macros instead of using inode->i_size directly.")
Reported-by: Xing Gaopeng <[email protected]>
Signed-off-by: Hou Tao <[email protected]>
Signed-off-by: Dominique Martinet <[email protected]>'</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: v9fs_stat2inode(struct p9_wstat *stat, struct inode *inode,
struct super_block *sb)
{
umode_t mode;
char ext[32];
char tag_name[14];
unsigned int i_nlink;
struct v9fs_session_info *v9ses = sb->s_fs_info;
struct v9fs_inode *v9inode = V9FS_I(inode);
set_nlink(inode, 1);
inode->i_atime.tv_sec = stat->atime;
inode->i_mtime.tv_sec = stat->mtime;
inode->i_ctime.tv_sec = stat->mtime;
inode->i_uid = v9ses->dfltuid;
inode->i_gid = v9ses->dfltgid;
if (v9fs_proto_dotu(v9ses)) {
inode->i_uid = stat->n_uid;
inode->i_gid = stat->n_gid;
}
if ((S_ISREG(inode->i_mode)) || (S_ISDIR(inode->i_mode))) {
if (v9fs_proto_dotu(v9ses) && (stat->extension[0] != '\0')) {
/*
* Hadlink support got added later to
* to the .u extension. So there can be
* server out there that doesn't support
* this even with .u extension. So check
* for non NULL stat->extension
*/
strlcpy(ext, stat->extension, sizeof(ext));
/* HARDLINKCOUNT %u */
sscanf(ext, "%13s %u", tag_name, &i_nlink);
if (!strncmp(tag_name, "HARDLINKCOUNT", 13))
set_nlink(inode, i_nlink);
}
}
mode = p9mode2perm(v9ses, stat);
mode |= inode->i_mode & ~S_IALLUGO;
inode->i_mode = mode;
i_size_write(inode, stat->length);
/* not real number of blocks, but 512 byte ones ... */
inode->i_blocks = (i_size_read(inode) + 512 - 1) >> 9;
v9inode->cache_validity &= ~V9FS_INO_INVALID_ATTR;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': '9p: use inode->i_lock to protect i_size_write() under 32-bit
Use inode->i_lock to protect i_size_write(), else i_size_read() in
generic_fillattr() may loop infinitely in read_seqcount_begin() when
multiple processes invoke v9fs_vfs_getattr() or v9fs_vfs_getattr_dotl()
simultaneously under 32-bit SMP environment, and a soft lockup will be
triggered as show below:
watchdog: BUG: soft lockup - CPU#5 stuck for 22s! [stat:2217]
Modules linked in:
CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4
Hardware name: Generic DT based system
PC is at generic_fillattr+0x104/0x108
LR is at 0xec497f00
pc : [<802b8898>] lr : [<ec497f00>] psr: 200c0013
sp : ec497e20 ip : ed608030 fp : ec497e3c
r10: 00000000 r9 : ec497f00 r8 : ed608030
r7 : ec497ebc r6 : ec497f00 r5 : ee5c1550 r4 : ee005780
r3 : 0000052d r2 : 00000000 r1 : ec497f00 r0 : ed608030
Flags: nzCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none
Control: 10c5387d Table: ac48006a DAC: 00000051
CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4
Hardware name: Generic DT based system
Backtrace:
[<8010d974>] (dump_backtrace) from [<8010dc88>] (show_stack+0x20/0x24)
[<8010dc68>] (show_stack) from [<80a1d194>] (dump_stack+0xb0/0xdc)
[<80a1d0e4>] (dump_stack) from [<80109f34>] (show_regs+0x1c/0x20)
[<80109f18>] (show_regs) from [<801d0a80>] (watchdog_timer_fn+0x280/0x2f8)
[<801d0800>] (watchdog_timer_fn) from [<80198658>] (__hrtimer_run_queues+0x18c/0x380)
[<801984cc>] (__hrtimer_run_queues) from [<80198e60>] (hrtimer_run_queues+0xb8/0xf0)
[<80198da8>] (hrtimer_run_queues) from [<801973e8>] (run_local_timers+0x28/0x64)
[<801973c0>] (run_local_timers) from [<80197460>] (update_process_times+0x3c/0x6c)
[<80197424>] (update_process_times) from [<801ab2b8>] (tick_nohz_handler+0xe0/0x1bc)
[<801ab1d8>] (tick_nohz_handler) from [<80843050>] (arch_timer_handler_virt+0x38/0x48)
[<80843018>] (arch_timer_handler_virt) from [<80180a64>] (handle_percpu_devid_irq+0x8c/0x240)
[<801809d8>] (handle_percpu_devid_irq) from [<8017ac20>] (generic_handle_irq+0x34/0x44)
[<8017abec>] (generic_handle_irq) from [<8017b344>] (__handle_domain_irq+0x6c/0xc4)
[<8017b2d8>] (__handle_domain_irq) from [<801022e0>] (gic_handle_irq+0x4c/0x88)
[<80102294>] (gic_handle_irq) from [<80101a30>] (__irq_svc+0x70/0x98)
[<802b8794>] (generic_fillattr) from [<8056b284>] (v9fs_vfs_getattr_dotl+0x74/0xa4)
[<8056b210>] (v9fs_vfs_getattr_dotl) from [<802b8904>] (vfs_getattr_nosec+0x68/0x7c)
[<802b889c>] (vfs_getattr_nosec) from [<802b895c>] (vfs_getattr+0x44/0x48)
[<802b8918>] (vfs_getattr) from [<802b8a74>] (vfs_statx+0x9c/0xec)
[<802b89d8>] (vfs_statx) from [<802b9428>] (sys_lstat64+0x48/0x78)
[<802b93e0>] (sys_lstat64) from [<80101000>] (ret_fast_syscall+0x0/0x28)
[[email protected]: updated comment to not refer to a function
in another subsystem]
Link: http://lkml.kernel.org/r/[email protected]
Cc: [email protected]
Fixes: 7549ae3e81cc ("9p: Use the i_size_[read, write]() macros instead of using inode->i_size directly.")
Reported-by: Xing Gaopeng <[email protected]>
Signed-off-by: Hou Tao <[email protected]>
Signed-off-by: Dominique Martinet <[email protected]>'</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: v9fs_vfs_getattr_dotl(const struct path *path, struct kstat *stat,
u32 request_mask, unsigned int flags)
{
struct dentry *dentry = path->dentry;
struct v9fs_session_info *v9ses;
struct p9_fid *fid;
struct p9_stat_dotl *st;
p9_debug(P9_DEBUG_VFS, "dentry: %p\n", dentry);
v9ses = v9fs_dentry2v9ses(dentry);
if (v9ses->cache == CACHE_LOOSE || v9ses->cache == CACHE_FSCACHE) {
generic_fillattr(d_inode(dentry), stat);
return 0;
}
fid = v9fs_fid_lookup(dentry);
if (IS_ERR(fid))
return PTR_ERR(fid);
/* Ask for all the fields in stat structure. Server will return
* whatever it supports
*/
st = p9_client_getattr_dotl(fid, P9_STATS_ALL);
if (IS_ERR(st))
return PTR_ERR(st);
v9fs_stat2inode_dotl(st, d_inode(dentry));
generic_fillattr(d_inode(dentry), stat);
/* Change block size to what the server returned */
stat->blksize = st->st_blksize;
kfree(st);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': '9p: use inode->i_lock to protect i_size_write() under 32-bit
Use inode->i_lock to protect i_size_write(), else i_size_read() in
generic_fillattr() may loop infinitely in read_seqcount_begin() when
multiple processes invoke v9fs_vfs_getattr() or v9fs_vfs_getattr_dotl()
simultaneously under 32-bit SMP environment, and a soft lockup will be
triggered as show below:
watchdog: BUG: soft lockup - CPU#5 stuck for 22s! [stat:2217]
Modules linked in:
CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4
Hardware name: Generic DT based system
PC is at generic_fillattr+0x104/0x108
LR is at 0xec497f00
pc : [<802b8898>] lr : [<ec497f00>] psr: 200c0013
sp : ec497e20 ip : ed608030 fp : ec497e3c
r10: 00000000 r9 : ec497f00 r8 : ed608030
r7 : ec497ebc r6 : ec497f00 r5 : ee5c1550 r4 : ee005780
r3 : 0000052d r2 : 00000000 r1 : ec497f00 r0 : ed608030
Flags: nzCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none
Control: 10c5387d Table: ac48006a DAC: 00000051
CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4
Hardware name: Generic DT based system
Backtrace:
[<8010d974>] (dump_backtrace) from [<8010dc88>] (show_stack+0x20/0x24)
[<8010dc68>] (show_stack) from [<80a1d194>] (dump_stack+0xb0/0xdc)
[<80a1d0e4>] (dump_stack) from [<80109f34>] (show_regs+0x1c/0x20)
[<80109f18>] (show_regs) from [<801d0a80>] (watchdog_timer_fn+0x280/0x2f8)
[<801d0800>] (watchdog_timer_fn) from [<80198658>] (__hrtimer_run_queues+0x18c/0x380)
[<801984cc>] (__hrtimer_run_queues) from [<80198e60>] (hrtimer_run_queues+0xb8/0xf0)
[<80198da8>] (hrtimer_run_queues) from [<801973e8>] (run_local_timers+0x28/0x64)
[<801973c0>] (run_local_timers) from [<80197460>] (update_process_times+0x3c/0x6c)
[<80197424>] (update_process_times) from [<801ab2b8>] (tick_nohz_handler+0xe0/0x1bc)
[<801ab1d8>] (tick_nohz_handler) from [<80843050>] (arch_timer_handler_virt+0x38/0x48)
[<80843018>] (arch_timer_handler_virt) from [<80180a64>] (handle_percpu_devid_irq+0x8c/0x240)
[<801809d8>] (handle_percpu_devid_irq) from [<8017ac20>] (generic_handle_irq+0x34/0x44)
[<8017abec>] (generic_handle_irq) from [<8017b344>] (__handle_domain_irq+0x6c/0xc4)
[<8017b2d8>] (__handle_domain_irq) from [<801022e0>] (gic_handle_irq+0x4c/0x88)
[<80102294>] (gic_handle_irq) from [<80101a30>] (__irq_svc+0x70/0x98)
[<802b8794>] (generic_fillattr) from [<8056b284>] (v9fs_vfs_getattr_dotl+0x74/0xa4)
[<8056b210>] (v9fs_vfs_getattr_dotl) from [<802b8904>] (vfs_getattr_nosec+0x68/0x7c)
[<802b889c>] (vfs_getattr_nosec) from [<802b895c>] (vfs_getattr+0x44/0x48)
[<802b8918>] (vfs_getattr) from [<802b8a74>] (vfs_statx+0x9c/0xec)
[<802b89d8>] (vfs_statx) from [<802b9428>] (sys_lstat64+0x48/0x78)
[<802b93e0>] (sys_lstat64) from [<80101000>] (ret_fast_syscall+0x0/0x28)
[[email protected]: updated comment to not refer to a function
in another subsystem]
Link: http://lkml.kernel.org/r/[email protected]
Cc: [email protected]
Fixes: 7549ae3e81cc ("9p: Use the i_size_[read, write]() macros instead of using inode->i_size directly.")
Reported-by: Xing Gaopeng <[email protected]>
Signed-off-by: Hou Tao <[email protected]>
Signed-off-by: Dominique Martinet <[email protected]>'</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: v9fs_vfs_getattr(const struct path *path, struct kstat *stat,
u32 request_mask, unsigned int flags)
{
struct dentry *dentry = path->dentry;
struct v9fs_session_info *v9ses;
struct p9_fid *fid;
struct p9_wstat *st;
p9_debug(P9_DEBUG_VFS, "dentry: %p\n", dentry);
v9ses = v9fs_dentry2v9ses(dentry);
if (v9ses->cache == CACHE_LOOSE || v9ses->cache == CACHE_FSCACHE) {
generic_fillattr(d_inode(dentry), stat);
return 0;
}
fid = v9fs_fid_lookup(dentry);
if (IS_ERR(fid))
return PTR_ERR(fid);
st = p9_client_stat(fid);
if (IS_ERR(st))
return PTR_ERR(st);
v9fs_stat2inode(st, d_inode(dentry), dentry->d_sb);
generic_fillattr(d_inode(dentry), stat);
p9stat_free(st);
kfree(st);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': '9p: use inode->i_lock to protect i_size_write() under 32-bit
Use inode->i_lock to protect i_size_write(), else i_size_read() in
generic_fillattr() may loop infinitely in read_seqcount_begin() when
multiple processes invoke v9fs_vfs_getattr() or v9fs_vfs_getattr_dotl()
simultaneously under 32-bit SMP environment, and a soft lockup will be
triggered as show below:
watchdog: BUG: soft lockup - CPU#5 stuck for 22s! [stat:2217]
Modules linked in:
CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4
Hardware name: Generic DT based system
PC is at generic_fillattr+0x104/0x108
LR is at 0xec497f00
pc : [<802b8898>] lr : [<ec497f00>] psr: 200c0013
sp : ec497e20 ip : ed608030 fp : ec497e3c
r10: 00000000 r9 : ec497f00 r8 : ed608030
r7 : ec497ebc r6 : ec497f00 r5 : ee5c1550 r4 : ee005780
r3 : 0000052d r2 : 00000000 r1 : ec497f00 r0 : ed608030
Flags: nzCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none
Control: 10c5387d Table: ac48006a DAC: 00000051
CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4
Hardware name: Generic DT based system
Backtrace:
[<8010d974>] (dump_backtrace) from [<8010dc88>] (show_stack+0x20/0x24)
[<8010dc68>] (show_stack) from [<80a1d194>] (dump_stack+0xb0/0xdc)
[<80a1d0e4>] (dump_stack) from [<80109f34>] (show_regs+0x1c/0x20)
[<80109f18>] (show_regs) from [<801d0a80>] (watchdog_timer_fn+0x280/0x2f8)
[<801d0800>] (watchdog_timer_fn) from [<80198658>] (__hrtimer_run_queues+0x18c/0x380)
[<801984cc>] (__hrtimer_run_queues) from [<80198e60>] (hrtimer_run_queues+0xb8/0xf0)
[<80198da8>] (hrtimer_run_queues) from [<801973e8>] (run_local_timers+0x28/0x64)
[<801973c0>] (run_local_timers) from [<80197460>] (update_process_times+0x3c/0x6c)
[<80197424>] (update_process_times) from [<801ab2b8>] (tick_nohz_handler+0xe0/0x1bc)
[<801ab1d8>] (tick_nohz_handler) from [<80843050>] (arch_timer_handler_virt+0x38/0x48)
[<80843018>] (arch_timer_handler_virt) from [<80180a64>] (handle_percpu_devid_irq+0x8c/0x240)
[<801809d8>] (handle_percpu_devid_irq) from [<8017ac20>] (generic_handle_irq+0x34/0x44)
[<8017abec>] (generic_handle_irq) from [<8017b344>] (__handle_domain_irq+0x6c/0xc4)
[<8017b2d8>] (__handle_domain_irq) from [<801022e0>] (gic_handle_irq+0x4c/0x88)
[<80102294>] (gic_handle_irq) from [<80101a30>] (__irq_svc+0x70/0x98)
[<802b8794>] (generic_fillattr) from [<8056b284>] (v9fs_vfs_getattr_dotl+0x74/0xa4)
[<8056b210>] (v9fs_vfs_getattr_dotl) from [<802b8904>] (vfs_getattr_nosec+0x68/0x7c)
[<802b889c>] (vfs_getattr_nosec) from [<802b895c>] (vfs_getattr+0x44/0x48)
[<802b8918>] (vfs_getattr) from [<802b8a74>] (vfs_statx+0x9c/0xec)
[<802b89d8>] (vfs_statx) from [<802b9428>] (sys_lstat64+0x48/0x78)
[<802b93e0>] (sys_lstat64) from [<80101000>] (ret_fast_syscall+0x0/0x28)
[[email protected]: updated comment to not refer to a function
in another subsystem]
Link: http://lkml.kernel.org/r/[email protected]
Cc: [email protected]
Fixes: 7549ae3e81cc ("9p: Use the i_size_[read, write]() macros instead of using inode->i_size directly.")
Reported-by: Xing Gaopeng <[email protected]>
Signed-off-by: Hou Tao <[email protected]>
Signed-off-by: Dominique Martinet <[email protected]>'</s>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.