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 PHP_MSHUTDOWN_FUNCTION(zip) { #ifdef PHP_ZIP_USE_OO zend_hash_destroy(&zip_prop_handlers); php_unregister_url_stream_wrapper("zip" TSRMLS_CC); #endif return SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Fixed bug #70350: ZipArchive::extractTo allows for directory traversal when creating directories'</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 ZIPARCHIVE_METHOD(addFromString) { struct zip *intern; zval *this = getThis(); char *buffer, *name; int buffer_len, name_len; ze_zip_object *ze_obj; struct zip_source *zs; int pos = 0; int cur_idx; if (!this) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, this); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &name, &name_len, &buffer, &buffer_len) == FAILURE) { return; } ze_obj = (ze_zip_object*) zend_object_store_get_object(this TSRMLS_CC); if (ze_obj->buffers_cnt) { ze_obj->buffers = (char **)erealloc(ze_obj->buffers, sizeof(char *) * (ze_obj->buffers_cnt+1)); pos = ze_obj->buffers_cnt++; } else { ze_obj->buffers = (char **)emalloc(sizeof(char *)); ze_obj->buffers_cnt++; pos = 0; } ze_obj->buffers[pos] = (char *)emalloc(buffer_len + 1); memcpy(ze_obj->buffers[pos], buffer, buffer_len + 1); zs = zip_source_buffer(intern, ze_obj->buffers[pos], buffer_len, 0); if (zs == NULL) { RETURN_FALSE; } cur_idx = zip_name_locate(intern, (const char *)name, 0); /* TODO: fix _zip_replace */ if (cur_idx >= 0) { if (zip_delete(intern, cur_idx) == -1) { goto fail; } } if (zip_add(intern, name, zs) != -1) { RETURN_TRUE; } fail: zip_source_free(zs); RETURN_FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Fixed bug #70350: ZipArchive::extractTo allows for directory traversal when creating directories'</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: tile_make_weights (PixopsFilterDimension *dim, double scale) { int n = ceil (1 / scale + 1); double *pixel_weights = g_malloc_n (sizeof (double) * SUBSAMPLE, n); int offset; int i; dim->n = n; dim->offset = 0; dim->weights = pixel_weights; for (offset = 0; offset < SUBSAMPLE; offset++) { double x = (double)offset / SUBSAMPLE; double a = x + 1 / scale; for (i = 0; i < n; i++) { if (i < x) { if (i + 1 > x) *(pixel_weights++) = (MIN (i + 1, a) - x) * scale; else *(pixel_weights++) = 0; } else { if (a > i) *(pixel_weights++) = (MIN (i + 1, a) - i) * scale; else *(pixel_weights++) = 0; } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'pixops: Fail make_weights functions on OOM The weights could grow very large under certain circumstances, in particular in security-relevant conditions, including the testsuite. By allowing the weight allocation to fail, this can be worked around. https://bugzilla.gnome.org/show_bug.cgi?id=754387'</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: make_weights (PixopsFilter *filter, PixopsInterpType interp_type, double scale_x, double scale_y) { switch (interp_type) { case PIXOPS_INTERP_NEAREST: g_assert_not_reached (); break; case PIXOPS_INTERP_TILES: tile_make_weights (&filter->x, scale_x); tile_make_weights (&filter->y, scale_y); break; case PIXOPS_INTERP_BILINEAR: bilinear_magnify_make_weights (&filter->x, scale_x); bilinear_magnify_make_weights (&filter->y, scale_y); break; case PIXOPS_INTERP_HYPER: bilinear_box_make_weights (&filter->x, scale_x); bilinear_box_make_weights (&filter->y, scale_y); break; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'pixops: Fail make_weights functions on OOM The weights could grow very large under certain circumstances, in particular in security-relevant conditions, including the testsuite. By allowing the weight allocation to fail, this can be worked around. https://bugzilla.gnome.org/show_bug.cgi?id=754387'</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: _pixops_composite_real (guchar *dest_buf, int render_x0, int render_y0, int render_x1, int render_y1, int dest_rowstride, int dest_channels, gboolean dest_has_alpha, const guchar *src_buf, int src_width, int src_height, int src_rowstride, int src_channels, gboolean src_has_alpha, double scale_x, double scale_y, PixopsInterpType interp_type, int overall_alpha) { PixopsFilter filter; PixopsLineFunc line_func; #ifdef USE_MMX gboolean found_mmx = _pixops_have_mmx (); #endif g_return_if_fail (!(dest_channels == 3 && dest_has_alpha)); g_return_if_fail (!(src_channels == 3 && src_has_alpha)); if (scale_x == 0 || scale_y == 0) return; if (interp_type == PIXOPS_INTERP_NEAREST) { if (scale_x == 1.0 && scale_y == 1.0) pixops_composite_nearest_noscale (dest_buf, render_x0, render_y0, render_x1, render_y1, dest_rowstride, dest_channels, dest_has_alpha, src_buf, src_width, src_height, src_rowstride, src_channels, src_has_alpha, overall_alpha); else pixops_composite_nearest (dest_buf, render_x0, render_y0, render_x1, render_y1, dest_rowstride, dest_channels, dest_has_alpha, src_buf, src_width, src_height, src_rowstride, src_channels, src_has_alpha, scale_x, scale_y, overall_alpha); return; } filter.overall_alpha = overall_alpha / 255.; make_weights (&filter, interp_type, scale_x, scale_y); if (filter.x.n == 2 && filter.y.n == 2 && dest_channels == 4 && src_channels == 4 && src_has_alpha && !dest_has_alpha) { #ifdef USE_MMX if (found_mmx) line_func = composite_line_22_4a4_mmx_stub; else #endif line_func = composite_line_22_4a4; } else line_func = composite_line; pixops_process (dest_buf, render_x0, render_y0, render_x1, render_y1, dest_rowstride, dest_channels, dest_has_alpha, src_buf, src_width, src_height, src_rowstride, src_channels, src_has_alpha, scale_x, scale_y, 0, 0, 0, 0, 0, &filter, line_func, composite_pixel); g_free (filter.x.weights); g_free (filter.y.weights); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'pixops: Fail make_weights functions on OOM The weights could grow very large under certain circumstances, in particular in security-relevant conditions, including the testsuite. By allowing the weight allocation to fail, this can be worked around. https://bugzilla.gnome.org/show_bug.cgi?id=754387'</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: bilinear_magnify_make_weights (PixopsFilterDimension *dim, double scale) { double *pixel_weights; int n; int offset; int i; if (scale > 1.0) /* Linear */ { n = 2; dim->offset = 0.5 * (1 / scale - 1); } else /* Tile */ { n = ceil (1.0 + 1.0 / scale); dim->offset = 0.0; } dim->n = n; dim->weights = g_malloc_n (sizeof (double) * SUBSAMPLE, n); pixel_weights = dim->weights; for (offset=0; offset < SUBSAMPLE; offset++) { double x = (double)offset / SUBSAMPLE; if (scale > 1.0) /* Linear */ { for (i = 0; i < n; i++) *(pixel_weights++) = (((i == 0) ? (1 - x) : x) / scale) * scale; } else /* Tile */ { double a = x + 1 / scale; /* x * ---------|--.-|----|--.-|------- SRC * ------------|---------|--------- DEST */ for (i = 0; i < n; i++) { if (i < x) { if (i + 1 > x) *(pixel_weights++) = (MIN (i + 1, a) - x) * scale; else *(pixel_weights++) = 0; } else { if (a > i) *(pixel_weights++) = (MIN (i + 1, a) - i) * scale; else *(pixel_weights++) = 0; } } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'pixops: Fail make_weights functions on OOM The weights could grow very large under certain circumstances, in particular in security-relevant conditions, including the testsuite. By allowing the weight allocation to fail, this can be worked around. https://bugzilla.gnome.org/show_bug.cgi?id=754387'</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 guint parse_rle_data_pseudocolor(TGAContext *ctx) { guint rle_num, raw_num; guchar *s, tag; guint n; g_return_val_if_fail(ctx->in->size > 0, 0); s = ctx->in->data; for (n = 0; n < ctx->in->size; ) { tag = *s; s++, n++; if (tag & 0x80) { if (n == ctx->in->size) { return --n; } else { rle_num = (tag & 0x7f) + 1; write_rle_data(ctx, &ctx->cmap->cols[*s], &rle_num); s++, n++; if (ctx->pbuf_bytes_done == ctx->pbuf_bytes) { ctx->done = TRUE; return n; } } } else { raw_num = tag + 1; if (n + raw_num >= ctx->in->size) { return --n; } else { for (; raw_num; raw_num--) { *ctx->pptr++ = ctx->cmap->cols[*s].r; *ctx->pptr++ = ctx->cmap->cols[*s].g; *ctx->pptr++ = ctx->cmap->cols[*s].b; if (ctx->pbuf->n_channels == 4) *ctx->pptr++ = ctx->cmap->cols[*s].a; s++, n++; ctx->pbuf_bytes_done += ctx->pbuf->n_channels; if (ctx->pbuf_bytes_done == ctx->pbuf_bytes) { ctx->done = TRUE; return n; } } } } } if (ctx->pbuf_bytes_done == ctx->pbuf_bytes) ctx->done = TRUE; return n; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'tga: Wrap TGAColormap struct in its own API Instead of poking into it directly.'</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 write_rle_data(TGAContext *ctx, TGAColor *color, guint *rle_count) { for (; *rle_count; (*rle_count)--) { g_memmove(ctx->pptr, (guchar *) color, ctx->pbuf->n_channels); ctx->pptr += ctx->pbuf->n_channels; ctx->pbuf_bytes_done += ctx->pbuf->n_channels; if (ctx->pbuf_bytes_done == ctx->pbuf_bytes) return; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'tga: Wrap TGAColormap struct in its own API Instead of poking into it directly.'</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 gboolean fill_in_context(TGAContext *ctx, GError **err) { gboolean alpha; guint w, h; g_return_val_if_fail(ctx != NULL, FALSE); ctx->run_length_encoded = ((ctx->hdr->type == TGA_TYPE_RLE_PSEUDOCOLOR) || (ctx->hdr->type == TGA_TYPE_RLE_TRUECOLOR) || (ctx->hdr->type == TGA_TYPE_RLE_GRAYSCALE)); if (ctx->hdr->has_cmap) ctx->cmap_size = ((ctx->hdr->cmap_bpp + 7) >> 3) * LE16(ctx->hdr->cmap_n_colors); alpha = ((ctx->hdr->bpp == 16) || (ctx->hdr->bpp == 32) || (ctx->hdr->has_cmap && (ctx->hdr->cmap_bpp == 32))); w = LE16(ctx->hdr->width); h = LE16(ctx->hdr->height); if (ctx->sfunc) { gint wi = w; gint hi = h; (*ctx->sfunc) (&wi, &hi, ctx->udata); if (wi == 0 || hi == 0) return FALSE; } ctx->pbuf = get_contiguous_pixbuf (w, h, alpha); if (!ctx->pbuf) { g_set_error_literal(err, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY, _("Cannot allocate new pixbuf")); return FALSE; } ctx->pbuf_bytes = ctx->pbuf->rowstride * ctx->pbuf->height; if ((ctx->hdr->flags & TGA_ORIGIN_UPPER) || ctx->run_length_encoded) ctx->pptr = ctx->pbuf->pixels; else ctx->pptr = ctx->pbuf->pixels + (ctx->pbuf->height - 1)*ctx->pbuf->rowstride; if (ctx->hdr->type == TGA_TYPE_PSEUDOCOLOR) ctx->rowstride = ctx->pbuf->width; else if (ctx->hdr->type == TGA_TYPE_GRAYSCALE) ctx->rowstride = (alpha ? ctx->pbuf->width * 2 : ctx->pbuf->width); else if (ctx->hdr->type == TGA_TYPE_TRUECOLOR) ctx->rowstride = ctx->pbuf->rowstride; ctx->completed_lines = 0; return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'io-tga: Colormaps are always present, so always parse them. We might end up with a colormap with 0 entries, but whatever, it's a colormap.'</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 gboolean try_preload(TGAContext *ctx, GError **err) { if (!ctx->hdr) { if (ctx->in->size >= sizeof(TGAHeader)) { ctx->hdr = g_try_malloc(sizeof(TGAHeader)); if (!ctx->hdr) { g_set_error_literal(err, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY, _("Cannot allocate TGA header memory")); return FALSE; } g_memmove(ctx->hdr, ctx->in->data, sizeof(TGAHeader)); ctx->in = io_buffer_free_segment(ctx->in, sizeof(TGAHeader), err); #ifdef DEBUG_TGA g_print ("infolen %d " "has_cmap %d " "type %d " "cmap_start %d " "cmap_n_colors %d " "cmap_bpp %d " "x %d y %d width %d height %d bpp %d " "flags %#x", ctx->hdr->infolen, ctx->hdr->has_cmap, ctx->hdr->type, LE16(ctx->hdr->cmap_start), LE16(ctx->hdr->cmap_n_colors), ctx->hdr->cmap_bpp, LE16(ctx->hdr->x_origin), LE16(ctx->hdr->y_origin), LE16(ctx->hdr->width), LE16(ctx->hdr->height), ctx->hdr->bpp, ctx->hdr->flags); #endif if (!ctx->in) return FALSE; if (LE16(ctx->hdr->width) == 0 || LE16(ctx->hdr->height) == 0) { g_set_error_literal(err, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE, _("TGA image has invalid dimensions")); return FALSE; } if ((ctx->hdr->flags & TGA_INTERLEAVE_MASK) != TGA_INTERLEAVE_NONE) { g_set_error_literal(err, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_UNKNOWN_TYPE, _("TGA image type not supported")); return FALSE; } switch (ctx->hdr->type) { case TGA_TYPE_PSEUDOCOLOR: case TGA_TYPE_RLE_PSEUDOCOLOR: if (ctx->hdr->bpp != 8) { g_set_error_literal(err, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_UNKNOWN_TYPE, _("TGA image type not supported")); return FALSE; } break; case TGA_TYPE_TRUECOLOR: case TGA_TYPE_RLE_TRUECOLOR: if (ctx->hdr->bpp != 24 && ctx->hdr->bpp != 32) { g_set_error_literal(err, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_UNKNOWN_TYPE, _("TGA image type not supported")); return FALSE; } break; case TGA_TYPE_GRAYSCALE: case TGA_TYPE_RLE_GRAYSCALE: if (ctx->hdr->bpp != 8 && ctx->hdr->bpp != 16) { g_set_error_literal(err, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_UNKNOWN_TYPE, _("TGA image type not supported")); return FALSE; } break; default: g_set_error_literal(err, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_UNKNOWN_TYPE, _("TGA image type not supported")); return FALSE; } if (!fill_in_context(ctx, err)) return FALSE; } else { return TRUE; } } if (!ctx->skipped_info) { if (ctx->in->size >= ctx->hdr->infolen) { ctx->in = io_buffer_free_segment(ctx->in, ctx->hdr->infolen, err); if (!ctx->in) return FALSE; ctx->skipped_info = TRUE; } else { return TRUE; } } if (ctx->hdr->has_cmap && !ctx->cmap) { if (ctx->in->size >= ctx->cmap_size) { if (!try_colormap(ctx, err)) return FALSE; } else { return TRUE; } } if (!ctx->prepared) { if (ctx->pfunc) (*ctx->pfunc) (ctx->pbuf, NULL, ctx->udata); ctx->prepared = TRUE; } /* We shouldn't get here anyway. */ return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'io-tga: Colormaps are always present, so always parse them. We might end up with a colormap with 0 entries, but whatever, it's a colormap.'</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 OPJ_BOOL opj_j2k_write_mco( opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager ) { OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_mco_size; opj_tcp_t * l_tcp = 00; opj_simple_mcc_decorrelation_data_t * l_mcc_record; OPJ_UINT32 i; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_tcp =&(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]); l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; l_mco_size = 5 + l_tcp->m_nb_mcc_records; if (l_mco_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCO marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mco_size; } opj_write_bytes(l_current_data,J2K_MS_MCO,2); /* MCO */ l_current_data += 2; opj_write_bytes(l_current_data,l_mco_size-2,2); /* Lmco */ l_current_data += 2; opj_write_bytes(l_current_data,l_tcp->m_nb_mcc_records,1); /* Nmco : only one tranform stage*/ ++l_current_data; l_mcc_record = l_tcp->m_mcc_records; for (i=0;i<l_tcp->m_nb_mcc_records;++i) { opj_write_bytes(l_current_data,l_mcc_record->m_index,1);/* Imco -> use the mcc indicated by 1*/ ++l_current_data; ++l_mcc_record; } if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_mco_size,p_manager) != l_mco_size) { return OPJ_FALSE; } return OPJ_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix potential use-after-free in opj_j2k_write_mco function Fixes #563'</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 flush_completed_IO(struct inode *inode) { ext4_io_end_t *io; int ret = 0; int ret2 = 0; if (list_empty(&EXT4_I(inode)->i_completed_io_list)) return ret; dump_completed_IO(inode); while (!list_empty(&EXT4_I(inode)->i_completed_io_list)){ io = list_entry(EXT4_I(inode)->i_completed_io_list.next, ext4_io_end_t, list); /* * Calling ext4_end_io_nolock() to convert completed * IO to written. * * When ext4_sync_file() is called, run_queue() may already * about to flush the work corresponding to this io structure. * It will be upset if it founds the io structure related * to the work-to-be schedule is freed. * * Thus we need to keep the io structure still valid here after * convertion finished. The io structure has a flag to * avoid double converting from both fsync and background work * queue work. */ ret = ext4_end_io_nolock(io); if (ret < 0) ret2 = ret; else list_del_init(&io->list); } return (ret2 < 0) ? ret2 : 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ext4_write_begin(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata) { struct inode *inode = mapping->host; int ret, needed_blocks; handle_t *handle; int retries = 0; struct page *page; pgoff_t index; unsigned from, to; trace_ext4_write_begin(inode, pos, len, flags); /* * Reserve one block more for addition to orphan list in case * we allocate blocks but write fails for some reason */ needed_blocks = ext4_writepage_trans_blocks(inode) + 1; index = pos >> PAGE_CACHE_SHIFT; from = pos & (PAGE_CACHE_SIZE - 1); to = from + len; retry: handle = ext4_journal_start(inode, needed_blocks); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out; } /* We cannot recurse into the filesystem as the transaction is already * started */ flags |= AOP_FLAG_NOFS; page = grab_cache_page_write_begin(mapping, index, flags); if (!page) { ext4_journal_stop(handle); ret = -ENOMEM; goto out; } *pagep = page; ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata, ext4_get_block); if (!ret && ext4_should_journal_data(inode)) { ret = walk_page_buffers(handle, page_buffers(page), from, to, NULL, do_journal_get_write_access); } if (ret) { unlock_page(page); page_cache_release(page); /* * block_write_begin may have instantiated a few blocks * outside i_size. Trim these off again. Don't need * i_size_read because we hold i_mutex. * * Add inode to orphan list in case we crash before * truncate finishes */ if (pos + len > inode->i_size && ext4_can_truncate(inode)) ext4_orphan_add(handle, inode); ext4_journal_stop(handle); if (pos + len > inode->i_size) { ext4_truncate_failed_write(inode); /* * If truncate failed early the inode might * still be on the orphan list; we need to * make sure the inode is removed from the * orphan list in that case. */ if (inode->i_nlink) ext4_orphan_del(NULL, inode); } } if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) goto retry; out: return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]>'</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: ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode, ext4_lblk_t iblock, unsigned int max_blocks, struct ext4_ext_path *path, int flags, unsigned int allocated, struct buffer_head *bh_result, ext4_fsblk_t newblock) { int ret = 0; int err = 0; ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio; ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical" "block %llu, max_blocks %u, flags %d, allocated %u", inode->i_ino, (unsigned long long)iblock, max_blocks, flags, allocated); ext4_ext_show_leaf(inode, path); /* get_block() before submit the IO, split the extent */ if (flags == EXT4_GET_BLOCKS_PRE_IO) { ret = ext4_split_unwritten_extents(handle, inode, path, iblock, max_blocks, flags); /* * Flag the inode(non aio case) or end_io struct (aio case) * that this IO needs to convertion to written when IO is * completed */ if (io) io->flag = EXT4_IO_UNWRITTEN; else ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN); goto out; } /* IO end_io complete, convert the filled extent to written */ if (flags == EXT4_GET_BLOCKS_CONVERT) { ret = ext4_convert_unwritten_extents_endio(handle, inode, path); if (ret >= 0) ext4_update_inode_fsync_trans(handle, inode, 1); goto out2; } /* buffered IO case */ /* * repeat fallocate creation request * we already have an unwritten extent */ if (flags & EXT4_GET_BLOCKS_UNINIT_EXT) goto map_out; /* buffered READ or buffered write_begin() lookup */ if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) { /* * We have blocks reserved already. We * return allocated blocks so that delalloc * won't do block reservation for us. But * the buffer head will be unmapped so that * a read from the block returns 0s. */ set_buffer_unwritten(bh_result); goto out1; } /* buffered write, writepage time, convert*/ ret = ext4_ext_convert_to_initialized(handle, inode, path, iblock, max_blocks); if (ret >= 0) ext4_update_inode_fsync_trans(handle, inode, 1); out: if (ret <= 0) { err = ret; goto out2; } else allocated = ret; set_buffer_new(bh_result); /* * if we allocated more blocks than requested * we need to make sure we unmap the extra block * allocated. The actual needed block will get * unmapped later when we find the buffer_head marked * new. */ if (allocated > max_blocks) { unmap_underlying_metadata_blocks(inode->i_sb->s_bdev, newblock + max_blocks, allocated - max_blocks); allocated = max_blocks; } /* * If we have done fallocate with the offset that is already * delayed allocated, we would have block reservation * and quota reservation done in the delayed write path. * But fallocate would have already updated quota and block * count for this offset. So cancel these reservation */ if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) ext4_da_update_reserve_space(inode, allocated, 0); map_out: set_buffer_mapped(bh_result); out1: if (allocated > max_blocks) allocated = max_blocks; ext4_ext_show_leaf(inode, path); bh_result->b_bdev = inode->i_sb->s_bdev; bh_result->b_blocknr = newblock; out2: if (path) { ext4_ext_drop_refs(path); kfree(path); } return err ? err : allocated; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ext4_get_block_write(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { handle_t *handle = NULL; int ret = 0; unsigned max_blocks = bh_result->b_size >> inode->i_blkbits; int dio_credits; ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n", inode->i_ino, create); /* * ext4_get_block in prepare for a DIO write or buffer write. * We allocate an uinitialized extent if blocks haven't been allocated. * The extent will be converted to initialized after IO complete. */ create = EXT4_GET_BLOCKS_IO_CREATE_EXT; if (max_blocks > DIO_MAX_BLOCKS) max_blocks = DIO_MAX_BLOCKS; dio_credits = ext4_chunk_trans_blocks(inode, max_blocks); handle = ext4_journal_start(inode, dio_credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out; } ret = ext4_get_blocks(handle, inode, iblock, max_blocks, bh_result, create); if (ret > 0) { bh_result->b_size = (ret << inode->i_blkbits); ret = 0; } ext4_journal_stop(handle); out: return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ext4_writepage(struct page *page, struct writeback_control *wbc) { int ret = 0; loff_t size; unsigned int len; struct buffer_head *page_bufs; struct inode *inode = page->mapping->host; trace_ext4_writepage(inode, page); size = i_size_read(inode); if (page->index == size >> PAGE_CACHE_SHIFT) len = size & ~PAGE_CACHE_MASK; else len = PAGE_CACHE_SIZE; if (page_has_buffers(page)) { page_bufs = page_buffers(page); if (walk_page_buffers(NULL, page_bufs, 0, len, NULL, ext4_bh_delay_or_unwritten)) { /* * We don't want to do block allocation * So redirty the page and return * We may reach here when we do a journal commit * via journal_submit_inode_data_buffers. * If we don't have mapping block we just ignore * them. We can also reach here via shrink_page_list */ redirty_page_for_writepage(wbc, page); unlock_page(page); return 0; } } else { /* * The test for page_has_buffers() is subtle: * We know the page is dirty but it lost buffers. That means * that at some moment in time after write_begin()/write_end() * has been called all buffers have been clean and thus they * must have been written at least once. So they are all * mapped and we can happily proceed with mapping them * and writing the page. * * Try to initialize the buffer_heads and check whether * all are mapped and non delay. We don't want to * do block allocation here. */ ret = block_prepare_write(page, 0, len, noalloc_get_block_write); if (!ret) { page_bufs = page_buffers(page); /* check whether all are mapped and non delay */ if (walk_page_buffers(NULL, page_bufs, 0, len, NULL, ext4_bh_delay_or_unwritten)) { redirty_page_for_writepage(wbc, page); unlock_page(page); return 0; } } else { /* * We can't do block allocation here * so just redity the page and unlock * and return */ redirty_page_for_writepage(wbc, page); unlock_page(page); return 0; } /* now mark the buffer_heads as dirty and uptodate */ block_commit_write(page, 0, len); } if (PageChecked(page) && ext4_should_journal_data(inode)) { /* * It's mmapped pagecache. Add buffers and journal it. There * doesn't seem much point in redirtying the page here. */ ClearPageChecked(page); return __ext4_journalled_writepage(page, len); } if (test_opt(inode->i_sb, NOBH) && ext4_should_writeback_data(inode)) ret = nobh_writepage(page, noalloc_get_block_write, wbc); else ret = block_write_full_page(page, noalloc_get_block_write, wbc); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]>'</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 ext4_ext_get_blocks(handle_t *handle, struct inode *inode, ext4_lblk_t iblock, unsigned int max_blocks, struct buffer_head *bh_result, int flags) { struct ext4_ext_path *path = NULL; struct ext4_extent_header *eh; struct ext4_extent newex, *ex, *last_ex; ext4_fsblk_t newblock; int err = 0, depth, ret, cache_type; unsigned int allocated = 0; struct ext4_allocation_request ar; ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio; __clear_bit(BH_New, &bh_result->b_state); ext_debug("blocks %u/%u requested for inode %lu\n", iblock, max_blocks, inode->i_ino); /* check in cache */ cache_type = ext4_ext_in_cache(inode, iblock, &newex); if (cache_type) { if (cache_type == EXT4_EXT_CACHE_GAP) { if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) { /* * block isn't allocated yet and * user doesn't want to allocate it */ goto out2; } /* we should allocate requested block */ } else if (cache_type == EXT4_EXT_CACHE_EXTENT) { /* block is already allocated */ newblock = iblock - le32_to_cpu(newex.ee_block) + ext_pblock(&newex); /* number of remaining blocks in the extent */ allocated = ext4_ext_get_actual_len(&newex) - (iblock - le32_to_cpu(newex.ee_block)); goto out; } else { BUG(); } } /* find extent for this block */ path = ext4_ext_find_extent(inode, iblock, NULL); if (IS_ERR(path)) { err = PTR_ERR(path); path = NULL; goto out2; } depth = ext_depth(inode); /* * consistent leaf must not be empty; * this situation is possible, though, _during_ tree modification; * this is why assert can't be put in ext4_ext_find_extent() */ if (path[depth].p_ext == NULL && depth != 0) { ext4_error(inode->i_sb, "bad extent address " "inode: %lu, iblock: %d, depth: %d", inode->i_ino, iblock, depth); err = -EIO; goto out2; } eh = path[depth].p_hdr; ex = path[depth].p_ext; if (ex) { ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block); ext4_fsblk_t ee_start = ext_pblock(ex); unsigned short ee_len; /* * Uninitialized extents are treated as holes, except that * we split out initialized portions during a write. */ ee_len = ext4_ext_get_actual_len(ex); /* if found extent covers block, simply return it */ if (iblock >= ee_block && iblock < ee_block + ee_len) { newblock = iblock - ee_block + ee_start; /* number of remaining blocks in the extent */ allocated = ee_len - (iblock - ee_block); ext_debug("%u fit into %u:%d -> %llu\n", iblock, ee_block, ee_len, newblock); /* Do not put uninitialized extent in the cache */ if (!ext4_ext_is_uninitialized(ex)) { ext4_ext_put_in_cache(inode, ee_block, ee_len, ee_start, EXT4_EXT_CACHE_EXTENT); goto out; } ret = ext4_ext_handle_uninitialized_extents(handle, inode, iblock, max_blocks, path, flags, allocated, bh_result, newblock); return ret; } } /* * requested block isn't allocated yet; * we couldn't try to create block if create flag is zero */ if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) { /* * put just found gap into cache to speed up * subsequent requests */ ext4_ext_put_gap_in_cache(inode, path, iblock); goto out2; } /* * Okay, we need to do block allocation. */ /* find neighbour allocated blocks */ ar.lleft = iblock; err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft); if (err) goto out2; ar.lright = iblock; err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright); if (err) goto out2; /* * See if request is beyond maximum number of blocks we can have in * a single extent. For an initialized extent this limit is * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is * EXT_UNINIT_MAX_LEN. */ if (max_blocks > EXT_INIT_MAX_LEN && !(flags & EXT4_GET_BLOCKS_UNINIT_EXT)) max_blocks = EXT_INIT_MAX_LEN; else if (max_blocks > EXT_UNINIT_MAX_LEN && (flags & EXT4_GET_BLOCKS_UNINIT_EXT)) max_blocks = EXT_UNINIT_MAX_LEN; /* Check if we can really insert (iblock)::(iblock+max_blocks) extent */ newex.ee_block = cpu_to_le32(iblock); newex.ee_len = cpu_to_le16(max_blocks); err = ext4_ext_check_overlap(inode, &newex, path); if (err) allocated = ext4_ext_get_actual_len(&newex); else allocated = max_blocks; /* allocate new block */ ar.inode = inode; ar.goal = ext4_ext_find_goal(inode, path, iblock); ar.logical = iblock; ar.len = allocated; if (S_ISREG(inode->i_mode)) ar.flags = EXT4_MB_HINT_DATA; else /* disable in-core preallocation for non-regular files */ ar.flags = 0; newblock = ext4_mb_new_blocks(handle, &ar, &err); if (!newblock) goto out2; ext_debug("allocate new block: goal %llu, found %llu/%u\n", ar.goal, newblock, allocated); /* try to insert new extent into found leaf and return */ ext4_ext_store_pblock(&newex, newblock); newex.ee_len = cpu_to_le16(ar.len); /* Mark uninitialized */ if (flags & EXT4_GET_BLOCKS_UNINIT_EXT){ ext4_ext_mark_uninitialized(&newex); /* * io_end structure was created for every async * direct IO write to the middle of the file. * To avoid unecessary convertion for every aio dio rewrite * to the mid of file, here we flag the IO that is really * need the convertion. * For non asycn direct IO case, flag the inode state * that we need to perform convertion when IO is done. */ if (flags == EXT4_GET_BLOCKS_PRE_IO) { if (io) io->flag = EXT4_IO_UNWRITTEN; else ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN); } } if (unlikely(EXT4_I(inode)->i_flags & EXT4_EOFBLOCKS_FL)) { if (eh->eh_entries) { last_ex = EXT_LAST_EXTENT(eh); if (iblock + ar.len > le32_to_cpu(last_ex->ee_block) + ext4_ext_get_actual_len(last_ex)) EXT4_I(inode)->i_flags &= ~EXT4_EOFBLOCKS_FL; } else { WARN_ON(eh->eh_entries == 0); ext4_error(inode->i_sb, __func__, "inode#%lu, eh->eh_entries = 0!", inode->i_ino); } } err = ext4_ext_insert_extent(handle, inode, path, &newex, flags); if (err) { /* free data blocks we just allocated */ /* not a good idea to call discard here directly, * but otherwise we'd need to call it every free() */ ext4_discard_preallocations(inode); ext4_free_blocks(handle, inode, 0, ext_pblock(&newex), ext4_ext_get_actual_len(&newex), 0); goto out2; } /* previous routine could use block we allocated */ newblock = ext_pblock(&newex); allocated = ext4_ext_get_actual_len(&newex); if (allocated > max_blocks) allocated = max_blocks; set_buffer_new(bh_result); /* * Update reserved blocks/metadata blocks after successful * block allocation which had been deferred till now. */ if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) ext4_da_update_reserve_space(inode, allocated, 1); /* * Cache the extent and update transaction to commit on fdatasync only * when it is _not_ an uninitialized extent. */ if ((flags & EXT4_GET_BLOCKS_UNINIT_EXT) == 0) { ext4_ext_put_in_cache(inode, iblock, allocated, newblock, EXT4_EXT_CACHE_EXTENT); ext4_update_inode_fsync_trans(handle, inode, 1); } else ext4_update_inode_fsync_trans(handle, inode, 0); out: if (allocated > max_blocks) allocated = max_blocks; ext4_ext_show_leaf(inode, path); set_buffer_mapped(bh_result); bh_result->b_bdev = inode->i_sb->s_bdev; bh_result->b_blocknr = newblock; out2: if (path) { ext4_ext_drop_refs(path); kfree(path); } return err ? err : allocated; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]>'</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 ext4_ext_insert_extent(handle_t *handle, struct inode *inode, struct ext4_ext_path *path, struct ext4_extent *newext, int flag) { struct ext4_extent_header *eh; struct ext4_extent *ex, *fex; struct ext4_extent *nearex; /* nearest extent */ struct ext4_ext_path *npath = NULL; int depth, len, err; ext4_lblk_t next; unsigned uninitialized = 0; BUG_ON(ext4_ext_get_actual_len(newext) == 0); depth = ext_depth(inode); ex = path[depth].p_ext; BUG_ON(path[depth].p_hdr == NULL); /* try to insert block into found extent and return */ if (ex && (flag != EXT4_GET_BLOCKS_PRE_IO) && ext4_can_extents_be_merged(inode, ex, newext)) { ext_debug("append [%d]%d block to %d:[%d]%d (from %llu)\n", ext4_ext_is_uninitialized(newext), ext4_ext_get_actual_len(newext), le32_to_cpu(ex->ee_block), ext4_ext_is_uninitialized(ex), ext4_ext_get_actual_len(ex), ext_pblock(ex)); err = ext4_ext_get_access(handle, inode, path + depth); if (err) return err; /* * ext4_can_extents_be_merged should have checked that either * both extents are uninitialized, or both aren't. Thus we * need to check only one of them here. */ if (ext4_ext_is_uninitialized(ex)) uninitialized = 1; ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex) + ext4_ext_get_actual_len(newext)); if (uninitialized) ext4_ext_mark_uninitialized(ex); eh = path[depth].p_hdr; nearex = ex; goto merge; } repeat: depth = ext_depth(inode); eh = path[depth].p_hdr; if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) goto has_space; /* probably next leaf has space for us? */ fex = EXT_LAST_EXTENT(eh); next = ext4_ext_next_leaf_block(inode, path); if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block) && next != EXT_MAX_BLOCK) { ext_debug("next leaf block - %d\n", next); BUG_ON(npath != NULL); npath = ext4_ext_find_extent(inode, next, NULL); if (IS_ERR(npath)) return PTR_ERR(npath); BUG_ON(npath->p_depth != path->p_depth); eh = npath[depth].p_hdr; if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) { ext_debug("next leaf isnt full(%d)\n", le16_to_cpu(eh->eh_entries)); path = npath; goto repeat; } ext_debug("next leaf has no free space(%d,%d)\n", le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max)); } /* * There is no free space in the found leaf. * We're gonna add a new leaf in the tree. */ err = ext4_ext_create_new_leaf(handle, inode, path, newext); if (err) goto cleanup; depth = ext_depth(inode); eh = path[depth].p_hdr; has_space: nearex = path[depth].p_ext; err = ext4_ext_get_access(handle, inode, path + depth); if (err) goto cleanup; if (!nearex) { /* there is no extent in this leaf, create first one */ ext_debug("first extent in the leaf: %d:%llu:[%d]%d\n", le32_to_cpu(newext->ee_block), ext_pblock(newext), ext4_ext_is_uninitialized(newext), ext4_ext_get_actual_len(newext)); path[depth].p_ext = EXT_FIRST_EXTENT(eh); } else if (le32_to_cpu(newext->ee_block) > le32_to_cpu(nearex->ee_block)) { /* BUG_ON(newext->ee_block == nearex->ee_block); */ if (nearex != EXT_LAST_EXTENT(eh)) { len = EXT_MAX_EXTENT(eh) - nearex; len = (len - 1) * sizeof(struct ext4_extent); len = len < 0 ? 0 : len; ext_debug("insert %d:%llu:[%d]%d after: nearest 0x%p, " "move %d from 0x%p to 0x%p\n", le32_to_cpu(newext->ee_block), ext_pblock(newext), ext4_ext_is_uninitialized(newext), ext4_ext_get_actual_len(newext), nearex, len, nearex + 1, nearex + 2); memmove(nearex + 2, nearex + 1, len); } path[depth].p_ext = nearex + 1; } else { BUG_ON(newext->ee_block == nearex->ee_block); len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent); len = len < 0 ? 0 : len; ext_debug("insert %d:%llu:[%d]%d before: nearest 0x%p, " "move %d from 0x%p to 0x%p\n", le32_to_cpu(newext->ee_block), ext_pblock(newext), ext4_ext_is_uninitialized(newext), ext4_ext_get_actual_len(newext), nearex, len, nearex + 1, nearex + 2); memmove(nearex + 1, nearex, len); path[depth].p_ext = nearex; } le16_add_cpu(&eh->eh_entries, 1); nearex = path[depth].p_ext; nearex->ee_block = newext->ee_block; ext4_ext_store_pblock(nearex, ext_pblock(newext)); nearex->ee_len = newext->ee_len; merge: /* try to merge extents to the right */ if (flag != EXT4_GET_BLOCKS_PRE_IO) ext4_ext_try_to_merge(inode, path, nearex); /* try to merge extents to the left */ /* time to correct all indexes above */ err = ext4_ext_correct_indexes(handle, inode, path); if (err) goto cleanup; err = ext4_ext_dirty(handle, inode, path + depth); cleanup: if (npath) { ext4_ext_drop_refs(npath); kfree(npath); } ext4_ext_invalidate_cache(inode); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]>'</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 ext4_io_end_t *ext4_init_io_end (struct inode *inode) { ext4_io_end_t *io = NULL; io = kmalloc(sizeof(*io), GFP_NOFS); if (io) { igrab(inode); io->inode = inode; io->flag = 0; io->offset = 0; io->size = 0; io->error = 0; INIT_WORK(&io->work, ext4_end_io_work); INIT_LIST_HEAD(&io->list); } return io; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ext4_end_io_work(struct work_struct *work) { ext4_io_end_t *io = container_of(work, ext4_io_end_t, work); struct inode *inode = io->inode; int ret = 0; mutex_lock(&inode->i_mutex); ret = ext4_end_io_nolock(io); if (ret >= 0) { if (!list_empty(&io->list)) list_del_init(&io->list); ext4_free_io_end(io); } mutex_unlock(&inode->i_mutex); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]>'</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 dump_completed_IO(struct inode * inode) { #ifdef EXT4_DEBUG struct list_head *cur, *before, *after; ext4_io_end_t *io, *io0, *io1; if (list_empty(&EXT4_I(inode)->i_completed_io_list)){ ext4_debug("inode %lu completed_io list is empty\n", inode->i_ino); return; } ext4_debug("Dump inode %lu completed_io list \n", inode->i_ino); list_for_each_entry(io, &EXT4_I(inode)->i_completed_io_list, list){ cur = &io->list; before = cur->prev; io0 = container_of(before, ext4_io_end_t, list); after = cur->next; io1 = container_of(after, ext4_io_end_t, list); ext4_debug("io 0x%p from inode %lu,prev 0x%p,next 0x%p\n", io, inode->i_ino, io0, io1); } #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool cgroupfs_mount_cgroup(void *hdata, const char *root, int type) { size_t bufsz = strlen(root) + sizeof("/sys/fs/cgroup"); char *path = NULL; char **parts = NULL; char *dirname = NULL; char *abs_path = NULL; char *abs_path2 = NULL; struct cgfs_data *cgfs_d; struct cgroup_process_info *info, *base_info; int r, saved_errno = 0; cgfs_d = hdata; if (!cgfs_d) return false; base_info = cgfs_d->info; /* If we get passed the _NOSPEC types, we default to _MIXED, since we don't * have access to the lxc_conf object at this point. It really should be up * to the caller to fix this, but this doesn't really hurt. */ if (type == LXC_AUTO_CGROUP_FULL_NOSPEC) type = LXC_AUTO_CGROUP_FULL_MIXED; else if (type == LXC_AUTO_CGROUP_NOSPEC) type = LXC_AUTO_CGROUP_MIXED; if (type < LXC_AUTO_CGROUP_RO || type > LXC_AUTO_CGROUP_FULL_MIXED) { ERROR("could not mount cgroups into container: invalid type specified internally"); errno = EINVAL; return false; } path = calloc(1, bufsz); if (!path) return false; snprintf(path, bufsz, "%s/sys/fs/cgroup", root); r = mount("cgroup_root", path, "tmpfs", MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_RELATIME, "size=10240k,mode=755"); if (r < 0) { SYSERROR("could not mount tmpfs to /sys/fs/cgroup in the container"); return false; } /* now mount all the hierarchies we care about */ for (info = base_info; info; info = info->next) { size_t subsystem_count, i; struct cgroup_mount_point *mp = info->designated_mount_point; if (!mp) mp = lxc_cgroup_find_mount_point(info->hierarchy, info->cgroup_path, true); if (!mp) { SYSERROR("could not find original mount point for cgroup hierarchy while trying to mount cgroup filesystem"); goto out_error; } subsystem_count = lxc_array_len((void **)info->hierarchy->subsystems); parts = calloc(subsystem_count + 1, sizeof(char *)); if (!parts) goto out_error; for (i = 0; i < subsystem_count; i++) { if (!strncmp(info->hierarchy->subsystems[i], "name=", 5)) parts[i] = info->hierarchy->subsystems[i] + 5; else parts[i] = info->hierarchy->subsystems[i]; } dirname = lxc_string_join(",", (const char **)parts, false); if (!dirname) goto out_error; /* create subsystem directory */ abs_path = lxc_append_paths(path, dirname); if (!abs_path) goto out_error; r = mkdir_p(abs_path, 0755); if (r < 0 && errno != EEXIST) { SYSERROR("could not create cgroup subsystem directory /sys/fs/cgroup/%s", dirname); goto out_error; } abs_path2 = lxc_append_paths(abs_path, info->cgroup_path); if (!abs_path2) goto out_error; if (type == LXC_AUTO_CGROUP_FULL_RO || type == LXC_AUTO_CGROUP_FULL_RW || type == LXC_AUTO_CGROUP_FULL_MIXED) { /* bind-mount the cgroup entire filesystem there */ if (strcmp(mp->mount_prefix, "/") != 0) { /* FIXME: maybe we should just try to remount the entire hierarchy * with a regular mount command? may that works? */ ERROR("could not automatically mount cgroup-full to /sys/fs/cgroup/%s: host has no mount point for this cgroup filesystem that has access to the root cgroup", dirname); goto out_error; } r = mount(mp->mount_point, abs_path, "none", MS_BIND, 0); if (r < 0) { SYSERROR("error bind-mounting %s to %s", mp->mount_point, abs_path); goto out_error; } /* main cgroup path should be read-only */ if (type == LXC_AUTO_CGROUP_FULL_RO || type == LXC_AUTO_CGROUP_FULL_MIXED) { r = mount(NULL, abs_path, NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL); if (r < 0) { SYSERROR("error re-mounting %s readonly", abs_path); goto out_error; } } /* own cgroup should be read-write */ if (type == LXC_AUTO_CGROUP_FULL_MIXED) { r = mount(abs_path2, abs_path2, NULL, MS_BIND, NULL); if (r < 0) { SYSERROR("error bind-mounting %s onto itself", abs_path2); goto out_error; } r = mount(NULL, abs_path2, NULL, MS_REMOUNT|MS_BIND, NULL); if (r < 0) { SYSERROR("error re-mounting %s readwrite", abs_path2); goto out_error; } } } else { /* create path for container's cgroup */ r = mkdir_p(abs_path2, 0755); if (r < 0 && errno != EEXIST) { SYSERROR("could not create cgroup directory /sys/fs/cgroup/%s%s", dirname, info->cgroup_path); goto out_error; } /* for read-only and mixed cases, we have to bind-mount the tmpfs directory * that points to the hierarchy itself (i.e. /sys/fs/cgroup/cpu etc.) onto * itself and then bind-mount it read-only, since we keep the tmpfs itself * read-write (see comment below) */ if (type == LXC_AUTO_CGROUP_MIXED || type == LXC_AUTO_CGROUP_RO) { r = mount(abs_path, abs_path, NULL, MS_BIND, NULL); if (r < 0) { SYSERROR("error bind-mounting %s onto itself", abs_path); goto out_error; } r = mount(NULL, abs_path, NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL); if (r < 0) { SYSERROR("error re-mounting %s readonly", abs_path); goto out_error; } } free(abs_path); abs_path = NULL; /* bind-mount container's cgroup to that directory */ abs_path = cgroup_to_absolute_path(mp, info->cgroup_path, NULL); if (!abs_path) goto out_error; r = mount(abs_path, abs_path2, "none", MS_BIND, 0); if (r < 0) { SYSERROR("error bind-mounting %s to %s", abs_path, abs_path2); goto out_error; } if (type == LXC_AUTO_CGROUP_RO) { r = mount(NULL, abs_path2, NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL); if (r < 0) { SYSERROR("error re-mounting %s readonly", abs_path2); goto out_error; } } } free(abs_path); free(abs_path2); abs_path = NULL; abs_path2 = NULL; /* add symlinks for every single subsystem */ if (subsystem_count > 1) { for (i = 0; i < subsystem_count; i++) { abs_path = lxc_append_paths(path, parts[i]); if (!abs_path) goto out_error; r = symlink(dirname, abs_path); if (r < 0) WARN("could not create symlink %s -> %s in /sys/fs/cgroup of container", parts[i], dirname); free(abs_path); abs_path = NULL; } } free(dirname); free(parts); dirname = NULL; parts = NULL; } /* We used to remount the entire tmpfs readonly if any :ro or * :mixed mode was specified. However, Ubuntu's mountall has the * unfortunate behavior to block bootup if /sys/fs/cgroup is * mounted read-only and cannot be remounted read-write. * (mountall reads /lib/init/fstab and tries to (re-)mount all of * these if they are not already mounted with the right options; * it contains an entry for /sys/fs/cgroup. In case it can't do * that, it prompts for the user to either manually fix it or * boot anyway. But without user input, booting of the container * hangs.) * * Instead of remounting the entire tmpfs readonly, we only * remount the paths readonly that are part of the cgroup * hierarchy. */ free(path); return true; out_error: saved_errno = errno; free(path); free(dirname); free(parts); free(abs_path); free(abs_path2); errno = saved_errno; return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <[email protected]> Acked-by: Stéphane Graber <[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 mount_proc_if_needed(const char *rootfs) { char path[MAXPATHLEN]; char link[20]; int linklen, ret; int mypid; ret = snprintf(path, MAXPATHLEN, "%s/proc/self", rootfs); if (ret < 0 || ret >= MAXPATHLEN) { SYSERROR("proc path name too long"); return -1; } memset(link, 0, 20); linklen = readlink(path, link, 20); mypid = (int)getpid(); INFO("I am %d, /proc/self points to '%s'", mypid, link); ret = snprintf(path, MAXPATHLEN, "%s/proc", rootfs); if (ret < 0 || ret >= MAXPATHLEN) { SYSERROR("proc path name too long"); return -1; } if (linklen < 0) /* /proc not mounted */ goto domount; if (atoi(link) != mypid) { /* wrong /procs mounted */ umount2(path, MNT_DETACH); /* ignore failure */ goto domount; } /* the right proc is already mounted */ return 0; domount: if (mount("proc", path, "proc", 0, NULL)) return -1; INFO("Mounted /proc in container for security transition"); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <[email protected]> Acked-by: Stéphane Graber <[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 lxc_execute_bind_init(struct lxc_conf *conf) { int ret; char path[PATH_MAX], destpath[PATH_MAX], *p; /* If init exists in the container, don't bind mount a static one */ p = choose_init(conf->rootfs.mount); if (p) { free(p); return; } ret = snprintf(path, PATH_MAX, SBINDIR "/init.lxc.static"); if (ret < 0 || ret >= PATH_MAX) { WARN("Path name too long searching for lxc.init.static"); return; } if (!file_exists(path)) { INFO("%s does not exist on host", path); return; } ret = snprintf(destpath, PATH_MAX, "%s%s", conf->rootfs.mount, "/init.lxc.static"); if (ret < 0 || ret >= PATH_MAX) { WARN("Path name too long for container's lxc.init.static"); return; } if (!file_exists(destpath)) { FILE * pathfile = fopen(destpath, "wb"); if (!pathfile) { SYSERROR("Failed to create mount target '%s'", destpath); return; } fclose(pathfile); } ret = mount(path, destpath, "none", MS_BIND, NULL); if (ret < 0) SYSERROR("Failed to bind lxc.init.static into container"); INFO("lxc.init.static bound into container at %s", path); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <[email protected]> Acked-by: Stéphane Graber <[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 setup_ttydir_console(const struct lxc_rootfs *rootfs, const struct lxc_console *console, char *ttydir) { char path[MAXPATHLEN], lxcpath[MAXPATHLEN]; int ret; /* create rootfs/dev/<ttydir> directory */ ret = snprintf(path, sizeof(path), "%s/dev/%s", rootfs->mount, ttydir); if (ret >= sizeof(path)) return -1; ret = mkdir(path, 0755); if (ret && errno != EEXIST) { SYSERROR("failed with errno %d to create %s", errno, path); return -1; } INFO("created %s", path); ret = snprintf(lxcpath, sizeof(lxcpath), "%s/dev/%s/console", rootfs->mount, ttydir); if (ret >= sizeof(lxcpath)) { ERROR("console path too long"); return -1; } snprintf(path, sizeof(path), "%s/dev/console", rootfs->mount); ret = unlink(path); if (ret && errno != ENOENT) { SYSERROR("error unlinking %s", path); return -1; } ret = creat(lxcpath, 0660); if (ret==-1 && errno != EEXIST) { SYSERROR("error %d creating %s", errno, lxcpath); return -1; } if (ret >= 0) close(ret); if (console->master < 0) { INFO("no console"); return 0; } if (mount(console->name, lxcpath, "none", MS_BIND, 0)) { ERROR("failed to mount '%s' on '%s'", console->name, lxcpath); return -1; } /* create symlink from rootfs/dev/console to 'lxc/console' */ ret = snprintf(lxcpath, sizeof(lxcpath), "%s/console", ttydir); if (ret >= sizeof(lxcpath)) { ERROR("lxc/console path too long"); return -1; } ret = symlink(lxcpath, path); if (ret) { SYSERROR("failed to create symlink for console"); return -1; } INFO("console has been setup on %s", lxcpath); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <[email protected]> Acked-by: Stéphane Graber <[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 mount_entry_on_absolute_rootfs(struct mntent *mntent, const struct lxc_rootfs *rootfs, const char *lxc_name) { char *aux; char path[MAXPATHLEN]; int r, ret = 0, offset; const char *lxcpath; lxcpath = lxc_global_config_value("lxc.lxcpath"); if (!lxcpath) { ERROR("Out of memory"); return -1; } /* if rootfs->path is a blockdev path, allow container fstab to * use $lxcpath/CN/rootfs as the target prefix */ r = snprintf(path, MAXPATHLEN, "%s/%s/rootfs", lxcpath, lxc_name); if (r < 0 || r >= MAXPATHLEN) goto skipvarlib; aux = strstr(mntent->mnt_dir, path); if (aux) { offset = strlen(path); goto skipabs; } skipvarlib: aux = strstr(mntent->mnt_dir, rootfs->path); if (!aux) { WARN("ignoring mount point '%s'", mntent->mnt_dir); return ret; } offset = strlen(rootfs->path); skipabs: r = snprintf(path, MAXPATHLEN, "%s/%s", rootfs->mount, aux + offset); if (r < 0 || r >= MAXPATHLEN) { WARN("pathnme too long for '%s'", mntent->mnt_dir); return -1; } return mount_entry_on_generic(mntent, path); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <[email protected]> Acked-by: Stéphane Graber <[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 mount_autodev(const char *name, const struct lxc_rootfs *rootfs, const char *lxcpath) { int ret; size_t clen; char *path; INFO("Mounting container /dev"); /* $(rootfs->mount) + "/dev/pts" + '\0' */ clen = (rootfs->path ? strlen(rootfs->mount) : 0) + 9; path = alloca(clen); ret = snprintf(path, clen, "%s/dev", rootfs->path ? rootfs->mount : ""); if (ret < 0 || ret >= clen) return -1; if (!dir_exists(path)) { WARN("No /dev in container."); WARN("Proceeding without autodev setup"); return 0; } if (mount("none", path, "tmpfs", 0, "size=100000,mode=755")) { SYSERROR("Failed mounting tmpfs onto %s\n", path); return false; } INFO("Mounted tmpfs onto %s", path); ret = snprintf(path, clen, "%s/dev/pts", rootfs->path ? rootfs->mount : ""); if (ret < 0 || ret >= clen) return -1; /* * If we are running on a devtmpfs mapping, dev/pts may already exist. * If not, then create it and exit if that fails... */ if (!dir_exists(path)) { ret = mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); if (ret) { SYSERROR("Failed to create /dev/pts in container"); return -1; } } INFO("Mounted container /dev"); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <[email protected]> Acked-by: Stéphane Graber <[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 bool cgm_bind_dir(const char *root, const char *dirname) { nih_local char *cgpath = NULL; /* /sys should have been mounted by now */ cgpath = NIH_MUST( nih_strdup(NULL, root) ); NIH_MUST( nih_strcat(&cgpath, NULL, "/sys/fs/cgroup") ); if (!dir_exists(cgpath)) { ERROR("%s does not exist", cgpath); return false; } /* mount a tmpfs there so we can create subdirs */ if (mount("cgroup", cgpath, "tmpfs", 0, "size=10000,mode=755")) { SYSERROR("Failed to mount tmpfs at %s", cgpath); return false; } NIH_MUST( nih_strcat(&cgpath, NULL, "/cgmanager") ); if (mkdir(cgpath, 0755) < 0) { SYSERROR("Failed to create %s", cgpath); return false; } if (mount(dirname, cgpath, "none", MS_BIND, 0)) { SYSERROR("Failed to bind mount %s to %s", dirname, cgpath); return false; } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <[email protected]> Acked-by: Stéphane Graber <[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 Image *ReadICONImage(const ImageInfo *image_info, ExceptionInfo *exception) { IconFile icon_file; IconInfo icon_info; Image *image; MagickBooleanType status; register ssize_t i, x; register Quantum *q; register unsigned char *p; size_t bit, byte, bytes_per_line, one, scanline_pad; ssize_t count, offset, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"%s",image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } icon_file.reserved=(short) ReadBlobLSBShort(image); icon_file.resource_type=(short) ReadBlobLSBShort(image); icon_file.count=(short) ReadBlobLSBShort(image); if ((icon_file.reserved != 0) || ((icon_file.resource_type != 1) && (icon_file.resource_type != 2)) || (icon_file.count > MaxIcons)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); for (i=0; i < icon_file.count; i++) { icon_file.directory[i].width=(unsigned char) ReadBlobByte(image); icon_file.directory[i].height=(unsigned char) ReadBlobByte(image); icon_file.directory[i].colors=(unsigned char) ReadBlobByte(image); icon_file.directory[i].reserved=(unsigned char) ReadBlobByte(image); icon_file.directory[i].planes=(unsigned short) ReadBlobLSBShort(image); icon_file.directory[i].bits_per_pixel=(unsigned short) ReadBlobLSBShort(image); icon_file.directory[i].size=ReadBlobLSBLong(image); icon_file.directory[i].offset=ReadBlobLSBLong(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } one=1; for (i=0; i < icon_file.count; i++) { /* Verify Icon identifier. */ offset=(ssize_t) SeekBlob(image,(MagickOffsetType) icon_file.directory[i].offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); icon_info.size=ReadBlobLSBLong(image); icon_info.width=(unsigned char) ((int) ReadBlobLSBLong(image)); icon_info.height=(unsigned char) ((int) ReadBlobLSBLong(image)/2); icon_info.planes=ReadBlobLSBShort(image); icon_info.bits_per_pixel=ReadBlobLSBShort(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (((icon_info.planes == 18505) && (icon_info.bits_per_pixel == 21060)) || (icon_info.size == 0x474e5089)) { Image *icon_image; ImageInfo *read_info; size_t length; unsigned char *png; /* Icon image encoded as a compressed PNG image. */ length=icon_file.directory[i].size; png=(unsigned char *) AcquireQuantumMemory(length+16,sizeof(*png)); if (png == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickMemory(png,"\211PNG\r\n\032\n\000\000\000\015",12); png[12]=(unsigned char) icon_info.planes; png[13]=(unsigned char) (icon_info.planes >> 8); png[14]=(unsigned char) icon_info.bits_per_pixel; png[15]=(unsigned char) (icon_info.bits_per_pixel >> 8); count=ReadBlob(image,length-16,png+16); icon_image=(Image *) NULL; if (count > 0) { read_info=CloneImageInfo(image_info); (void) CopyMagickString(read_info->magick,"PNG",MagickPathExtent); icon_image=BlobToImage(read_info,png,length+16,exception); read_info=DestroyImageInfo(read_info); } png=(unsigned char *) RelinquishMagickMemory(png); if (icon_image == (Image *) NULL) { if (count != (ssize_t) (length-16)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); image=DestroyImageList(image); return((Image *) NULL); } DestroyBlob(icon_image); icon_image->blob=ReferenceBlob(image->blob); ReplaceImageInList(&image,icon_image); } else { if (icon_info.bits_per_pixel > 32) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); icon_info.compression=ReadBlobLSBLong(image); icon_info.image_size=ReadBlobLSBLong(image); icon_info.x_pixels=ReadBlobLSBLong(image); icon_info.y_pixels=ReadBlobLSBLong(image); icon_info.number_colors=ReadBlobLSBLong(image); icon_info.colors_important=ReadBlobLSBLong(image); image->alpha_trait=BlendPixelTrait; image->columns=(size_t) icon_file.directory[i].width; if ((ssize_t) image->columns > icon_info.width) image->columns=(size_t) icon_info.width; if (image->columns == 0) image->columns=256; image->rows=(size_t) icon_file.directory[i].height; if ((ssize_t) image->rows > icon_info.height) image->rows=(size_t) icon_info.height; if (image->rows == 0) image->rows=256; image->depth=icon_info.bits_per_pixel; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene = %.20g",(double) i); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " size = %.20g",(double) icon_info.size); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width = %.20g",(double) icon_file.directory[i].width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height = %.20g",(double) icon_file.directory[i].height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " colors = %.20g",(double ) icon_info.number_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " planes = %.20g",(double) icon_info.planes); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bpp = %.20g",(double) icon_info.bits_per_pixel); } if ((icon_info.number_colors != 0) || (icon_info.bits_per_pixel <= 16U)) { image->storage_class=PseudoClass; image->colors=icon_info.number_colors; if (image->colors == 0) image->colors=one << icon_info.bits_per_pixel; } if (image->storage_class == PseudoClass) { register ssize_t i; unsigned char *icon_colormap; /* Read Icon raster colormap. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); icon_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4UL*sizeof(*icon_colormap)); if (icon_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) (4*image->colors),icon_colormap); if (count != (ssize_t) (4*image->colors)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); p=icon_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(Quantum) ScaleCharToQuantum(*p++); image->colormap[i].green=(Quantum) ScaleCharToQuantum(*p++); image->colormap[i].red=(Quantum) ScaleCharToQuantum(*p++); p++; } icon_colormap=(unsigned char *) RelinquishMagickMemory(icon_colormap); } /* Convert Icon raster image to pixel packets. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); bytes_per_line=(((image->columns*icon_info.bits_per_pixel)+31) & ~31) >> 3; (void) bytes_per_line; scanline_pad=((((image->columns*icon_info.bits_per_pixel)+31) & ~31)- (image->columns*icon_info.bits_per_pixel)) >> 3; switch (icon_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) (image->columns-7); x+=8) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < 8; bit++) { SetPixelIndex(image,((byte & (0x80 >> bit)) != 0 ? 0x01 : 0x00),q); q+=GetPixelChannels(image); } } if ((image->columns % 8) != 0) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < (image->columns % 8); bit++) { SetPixelIndex(image,((byte & (0x80 >> bit)) != 0 ? 0x01 : 0x00),q); q+=GetPixelChannels(image); } } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 4: { /* Read 4-bit Icon scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(image,((byte >> 4) & 0xf),q); q+=GetPixelChannels(image); SetPixelIndex(image,((byte) & 0xf),q); q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(image,((byte >> 4) & 0xf),q); q+=GetPixelChannels(image); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(image,byte,q); q+=GetPixelChannels(image); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 16: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { byte=(size_t) ReadBlobByte(image); byte|=(size_t) (ReadBlobByte(image) << 8); SetPixelIndex(image,byte,q); q+=GetPixelChannels(image); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 24: case 32: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); SetPixelRed(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); if (icon_info.bits_per_pixel == 32) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); q+=GetPixelChannels(image); } if (icon_info.bits_per_pixel == 24) for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (image_info->ping == MagickFalse) (void) SyncImage(image,exception); if (icon_info.bits_per_pixel != 32) { /* Read the ICON alpha mask. */ image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < 8; bit++) { SetPixelAlpha(image,(((byte & (0x80 >> bit)) != 0) ? TransparentAlpha : OpaqueAlpha),q); q+=GetPixelChannels(image); } } if ((image->columns % 8) != 0) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < (image->columns % 8); bit++) { SetPixelAlpha(image,(((byte & (0x80 >> bit)) != 0) ? TransparentAlpha : OpaqueAlpha),q); q+=GetPixelChannels(image); } } if ((image->columns % 32) != 0) for (x=0; x < (ssize_t) ((32-(image->columns % 32))/8); x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (i < (ssize_t) (icon_file.count-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-189', 'CWE-703'], 'message': ''</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count, const size_t quantum) { MemoryInfo *memory_info; size_t length; length=count*quantum; if ((count == 0) || (quantum != (length/count))) { errno=ENOMEM; return((MemoryInfo *) NULL); } memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1, sizeof(*memory_info))); if (memory_info == (MemoryInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(memory_info,0,sizeof(*memory_info)); memory_info->length=length; memory_info->signature=MagickSignature; if (AcquireMagickResource(MemoryResource,length) != MagickFalse) { memory_info->blob=AcquireAlignedMemory(1,length); if (memory_info->blob != NULL) memory_info->type=AlignedVirtualMemory; else RelinquishMagickResource(MemoryResource,length); } if ((memory_info->blob == NULL) && (AcquireMagickResource(MapResource,length) != MagickFalse)) { /* Heap memory failed, try anonymous memory mapping. */ memory_info->blob=MapBlob(-1,IOMode,0,length); if (memory_info->blob != NULL) memory_info->type=MapVirtualMemory; else RelinquishMagickResource(MapResource,length); } if (memory_info->blob == NULL) { int file; /* Anonymous memory mapping failed, try file-backed memory mapping. */ file=AcquireUniqueFileResource(memory_info->filename); if (file != -1) { if ((lseek(file,length-1,SEEK_SET) >= 0) && (write(file,"",1) == 1)) { memory_info->blob=MapBlob(file,IOMode,0,length); if (memory_info->blob != NULL) { memory_info->type=MapVirtualMemory; (void) AcquireMagickResource(MapResource,length); } } (void) close(file); } } if (memory_info->blob == NULL) { memory_info->blob=AcquireMagickMemory(length); if (memory_info->blob != NULL) memory_info->type=UnalignedVirtualMemory; } if (memory_info->blob == NULL) memory_info=RelinquishVirtualMemory(memory_info); return(memory_info); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-189', 'CWE-703'], 'message': ''</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info) { assert(memory_info != (MemoryInfo *) NULL); assert(memory_info->signature == MagickSignature); if (memory_info->blob != (void *) NULL) switch (memory_info->type) { case AlignedVirtualMemory: { memory_info->blob=RelinquishAlignedMemory(memory_info->blob); RelinquishMagickResource(MemoryResource,memory_info->length); break; } case MapVirtualMemory: { (void) UnmapBlob(memory_info->blob,memory_info->length); memory_info->blob=NULL; RelinquishMagickResource(MapResource,memory_info->length); if (*memory_info->filename != '\0') (void) RelinquishUniqueFileResource(memory_info->filename); break; } case UnalignedVirtualMemory: default: { memory_info->blob=RelinquishMagickMemory(memory_info->blob); break; } } memory_info->signature=(~MagickSignature); memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info); return(memory_info); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-189', 'CWE-703'], 'message': ''</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 usbvision_probe(struct usb_interface *intf, const struct usb_device_id *devid) { struct usb_device *dev = usb_get_dev(interface_to_usbdev(intf)); struct usb_interface *uif; __u8 ifnum = intf->altsetting->desc.bInterfaceNumber; const struct usb_host_interface *interface; struct usb_usbvision *usbvision = NULL; const struct usb_endpoint_descriptor *endpoint; int model, i, ret; PDEBUG(DBG_PROBE, "VID=%#04x, PID=%#04x, ifnum=%u", dev->descriptor.idVendor, dev->descriptor.idProduct, ifnum); model = devid->driver_info; if (model < 0 || model >= usbvision_device_data_size) { PDEBUG(DBG_PROBE, "model out of bounds %d", model); ret = -ENODEV; goto err_usb; } printk(KERN_INFO "%s: %s found\n", __func__, usbvision_device_data[model].model_string); /* * this is a security check. * an exploit using an incorrect bInterfaceNumber is known */ if (ifnum >= USB_MAXINTERFACES || !dev->actconfig->interface[ifnum]) return -ENODEV; if (usbvision_device_data[model].interface >= 0) interface = &dev->actconfig->interface[usbvision_device_data[model].interface]->altsetting[0]; else interface = &dev->actconfig->interface[ifnum]->altsetting[0]; endpoint = &interface->endpoint[1].desc; if (!usb_endpoint_xfer_isoc(endpoint)) { dev_err(&intf->dev, "%s: interface %d. has non-ISO endpoint!\n", __func__, ifnum); dev_err(&intf->dev, "%s: Endpoint attributes %d", __func__, endpoint->bmAttributes); ret = -ENODEV; goto err_usb; } if (usb_endpoint_dir_out(endpoint)) { dev_err(&intf->dev, "%s: interface %d. has ISO OUT endpoint!\n", __func__, ifnum); ret = -ENODEV; goto err_usb; } usbvision = usbvision_alloc(dev, intf); if (usbvision == NULL) { dev_err(&intf->dev, "%s: couldn't allocate USBVision struct\n", __func__); ret = -ENOMEM; goto err_usb; } if (dev->descriptor.bNumConfigurations > 1) usbvision->bridge_type = BRIDGE_NT1004; else if (model == DAZZLE_DVC_90_REV_1_SECAM) usbvision->bridge_type = BRIDGE_NT1005; else usbvision->bridge_type = BRIDGE_NT1003; PDEBUG(DBG_PROBE, "bridge_type %d", usbvision->bridge_type); /* compute alternate max packet sizes */ uif = dev->actconfig->interface[0]; usbvision->num_alt = uif->num_altsetting; PDEBUG(DBG_PROBE, "Alternate settings: %i", usbvision->num_alt); usbvision->alt_max_pkt_size = kmalloc(32 * usbvision->num_alt, GFP_KERNEL); if (usbvision->alt_max_pkt_size == NULL) { dev_err(&intf->dev, "usbvision: out of memory!\n"); ret = -ENOMEM; goto err_pkt; } for (i = 0; i < usbvision->num_alt; i++) { u16 tmp = le16_to_cpu(uif->altsetting[i].endpoint[1].desc. wMaxPacketSize); usbvision->alt_max_pkt_size[i] = (tmp & 0x07ff) * (((tmp & 0x1800) >> 11) + 1); PDEBUG(DBG_PROBE, "Alternate setting %i, max size= %i", i, usbvision->alt_max_pkt_size[i]); } usbvision->nr = usbvision_nr++; spin_lock_init(&usbvision->queue_lock); init_waitqueue_head(&usbvision->wait_frame); init_waitqueue_head(&usbvision->wait_stream); usbvision->have_tuner = usbvision_device_data[model].tuner; if (usbvision->have_tuner) usbvision->tuner_type = usbvision_device_data[model].tuner_type; usbvision->dev_model = model; usbvision->remove_pending = 0; usbvision->iface = ifnum; usbvision->iface_alt = 0; usbvision->video_endp = endpoint->bEndpointAddress; usbvision->isoc_packet_size = 0; usbvision->usb_bandwidth = 0; usbvision->user = 0; usbvision->streaming = stream_off; usbvision_configure_video(usbvision); usbvision_register_video(usbvision); usbvision_create_sysfs(&usbvision->vdev); PDEBUG(DBG_PROBE, "success"); return 0; err_pkt: usbvision_release(usbvision); err_usb: usb_put_dev(dev); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-17'], 'message': '[media] usbvision: fix crash on detecting device with invalid configuration The usbvision driver crashes when a specially crafted usb device with invalid number of interfaces or endpoints is detected. This fix adds checks that the device has proper configuration expected by the driver. Reported-by: Ralf Spenneberg <[email protected]> Signed-off-by: Vladis Dronov <[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 void ssl_write_renegotiation_ext( ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; *olen = 0; if( ssl->renegotiation != SSL_RENEGOTIATION ) return; SSL_DEBUG_MSG( 3, ( "client hello, adding renegotiation extension" ) ); /* * Secure renegotiation */ *p++ = (unsigned char)( ( TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( TLS_EXT_RENEGOTIATION_INFO ) & 0xFF ); *p++ = 0x00; *p++ = ( ssl->verify_data_len + 1 ) & 0xFF; *p++ = ssl->verify_data_len & 0xFF; memcpy( p, ssl->own_verify_data, ssl->verify_data_len ); *olen = 5 + ssl->verify_data_len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Added bounds checking for TLS extensions IOTSSL-478 - Added checks to prevent buffer overflows.'</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 ssl_write_hostname_ext( ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; *olen = 0; if( ssl->hostname == NULL ) return; SSL_DEBUG_MSG( 3, ( "client hello, adding server name extension: %s", ssl->hostname ) ); /* * struct { * NameType name_type; * select (name_type) { * case host_name: HostName; * } name; * } ServerName; * * enum { * host_name(0), (255) * } NameType; * * opaque HostName<1..2^16-1>; * * struct { * ServerName server_name_list<1..2^16-1> * } ServerNameList; */ *p++ = (unsigned char)( ( TLS_EXT_SERVERNAME >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( TLS_EXT_SERVERNAME ) & 0xFF ); *p++ = (unsigned char)( ( (ssl->hostname_len + 5) >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( (ssl->hostname_len + 5) ) & 0xFF ); *p++ = (unsigned char)( ( (ssl->hostname_len + 3) >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( (ssl->hostname_len + 3) ) & 0xFF ); *p++ = (unsigned char)( ( TLS_EXT_SERVERNAME_HOSTNAME ) & 0xFF ); *p++ = (unsigned char)( ( ssl->hostname_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->hostname_len ) & 0xFF ); memcpy( p, ssl->hostname, ssl->hostname_len ); *olen = ssl->hostname_len + 9; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Added bounds checking for TLS extensions IOTSSL-478 - Added checks to prevent buffer overflows.'</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 ssl_write_renegotiation_ext( ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; const unsigned char *end = ssl->out_msg + SSL_MAX_CONTENT_LEN; *olen = 0; if( ssl->renegotiation != SSL_RENEGOTIATION ) return; SSL_DEBUG_MSG( 3, ( "client hello, adding renegotiation extension" ) ); if( (size_t)(end - p) < 5 + ssl->verify_data_len ) { SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); return; } /* * Secure renegotiation */ *p++ = (unsigned char)( ( TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( TLS_EXT_RENEGOTIATION_INFO ) & 0xFF ); *p++ = 0x00; *p++ = ( ssl->verify_data_len + 1 ) & 0xFF; *p++ = ssl->verify_data_len & 0xFF; memcpy( p, ssl->own_verify_data, ssl->verify_data_len ); *olen = 5 + ssl->verify_data_len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Add extra check before integer conversion end < p should never happen, but just be extra sure'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt) { struct iovec *l2_hdr, *l3_hdr; size_t bytes_read; size_t full_ip6hdr_len; uint16_t l3_proto; assert(pkt); l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG]; l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG]; bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base, ETH_MAX_L2_HDR_LEN); if (bytes_read < ETH_MAX_L2_HDR_LEN) { l2_hdr->iov_len = 0; return false; } else { l2_hdr->iov_len = eth_get_l2_hdr_length(l2_hdr->iov_base); } l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len); switch (l3_proto) { case ETH_P_IP: l3_hdr->iov_base = g_malloc(ETH_MAX_IP4_HDR_LEN); bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, l3_hdr->iov_base, sizeof(struct ip_header)); if (bytes_read < sizeof(struct ip_header)) { l3_hdr->iov_len = 0; return false; } l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base); pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p; /* copy optional IPv4 header data */ bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len + sizeof(struct ip_header), l3_hdr->iov_base + sizeof(struct ip_header), l3_hdr->iov_len - sizeof(struct ip_header)); if (bytes_read < l3_hdr->iov_len - sizeof(struct ip_header)) { l3_hdr->iov_len = 0; return false; } break; case ETH_P_IPV6: if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, &pkt->l4proto, &full_ip6hdr_len)) { l3_hdr->iov_len = 0; return false; } l3_hdr->iov_base = g_malloc(full_ip6hdr_len); bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, l3_hdr->iov_base, full_ip6hdr_len); if (bytes_read < full_ip6hdr_len) { l3_hdr->iov_len = 0; return false; } else { l3_hdr->iov_len = full_ip6hdr_len; } break; default: l3_hdr->iov_len = 0; break; } vmxnet_tx_pkt_calculate_hdr_len(pkt); pkt->packet_type = get_eth_packet_type(l2_hdr->iov_base); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'net/vmxnet3: Refine l2 header validation Validation of l2 header length assumed minimal packet size as eth_header + 2 * vlan_header regardless of the actual protocol. This caused crash for valid non-IP packets shorter than 22 bytes, as 'tx_pkt->packet_type' hasn't been assigned for such packets, and 'vmxnet3_on_tx_done_update_stats()' expects it to be properly set. Refine header length validation in 'vmxnet_tx_pkt_parse_headers'. Check its return value during packet processing flow. As a side effect, in case IPv4 and IPv6 header validation failure, corrupt packets will be dropped. Signed-off-by: Dana Rubin <[email protected]> Signed-off-by: Shmulik Ladkani <[email protected]> Signed-off-by: Jason Wang <[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 on_page_prepare(GtkNotebook *assistant, GtkWidget *page, gpointer user_data) { //int page_no = gtk_assistant_get_current_page(g_assistant); //log_ready_state(); /* This suppresses [Last] button: assistant thinks that * we never have this page ready unless we are on it * -> therefore there is at least one non-ready page * -> therefore it won't show [Last] */ // Doesn't work: if Completeness:[++++++-+++], // then [Last] btn will still be shown. //gtk_assistant_set_page_complete(g_assistant, // pages[PAGENO_REVIEW_DATA].page_widget, // pages[PAGENO_REVIEW_DATA].page_widget == page //); /* If processing is finished and if it was terminated because of an error * the event progress page is selected. So, it does not make sense to show * the next step button and we MUST NOT clear warnings. */ if (!is_processing_finished()) { /* some pages hide it, so restore it to it's default */ show_next_step_button(); clear_warnings(); } gtk_widget_hide(g_btn_detail); gtk_widget_hide(g_btn_onfail); if (!g_expert_mode) gtk_widget_hide(g_btn_repeat); /* Save text fields if changed */ /* Must be called before any GUI operation because the following two * functions causes recreating of the text items tabs, thus all updates to * these tabs will be lost */ save_items_from_notepad(); save_text_from_text_view(g_tv_comment, FILENAME_COMMENT); if (pages[PAGENO_SUMMARY].page_widget == page) { if (!g_expert_mode) { /* Skip intro screen */ int n = select_next_page_no(pages[PAGENO_SUMMARY].page_no, NULL); log_info("switching to page_no:%d", n); gtk_notebook_set_current_page(assistant, n); return; } } if (pages[PAGENO_EDIT_ELEMENTS].page_widget == page) { if (highlight_forbidden()) { add_sensitive_data_warning(); show_warnings(); gtk_expander_set_expanded(g_exp_search, TRUE); } else gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(g_rb_custom_search), TRUE); show_warnings(); } if (pages[PAGENO_REVIEW_DATA].page_widget == page) { update_ls_details_checkboxes(g_event_selected); gtk_widget_set_sensitive(g_btn_next, gtk_toggle_button_get_active(g_tb_approve_bt)); } if (pages[PAGENO_EDIT_COMMENT].page_widget == page) { gtk_widget_show(g_btn_detail); gtk_widget_set_sensitive(g_btn_next, false); on_comment_changed(gtk_text_view_get_buffer(g_tv_comment), NULL); } //log_ready_state(); if (pages[PAGENO_EVENT_PROGRESS].page_widget == page) { log_info("g_event_selected:'%s'", g_event_selected); if (g_event_selected && g_event_selected[0] ) { clear_warnings(); start_event_run(g_event_selected); } } if(pages[PAGENO_EVENT_SELECTOR].page_widget == page) { if (!g_expert_mode && !g_auto_event_list) hide_next_step_button(); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'wizard: fix save users changes after reviewing dump dir files If the user reviewed the dump dir's files during reporting the crash, the changes was thrown away and original data was passed to the bugzilla bug report. report-gtk saves the first text view buffer and then reloads data from the reported problem directory, which causes that the changes made to those text views are thrown away. Function save_text_if_changed(), except of saving text, also reload the files from dump dir and update gui state from the dump dir. The commit moves the reloading and updating gui functions away from this function. Related to rhbz#1270235 Signed-off-by: Matej Habrnal <[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: xmlParseConditionalSections(xmlParserCtxtPtr ctxt) { int id = ctxt->input->id; SKIP(3); SKIP_BLANKS; if (CMP7(CUR_PTR, 'I', 'N', 'C', 'L', 'U', 'D', 'E')) { SKIP(7); SKIP_BLANKS; if (RAW != '[') { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } NEXT; } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Entering INCLUDE Conditional Section\n"); } while (((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') || (NXT(2) != '>'))) && (ctxt->instate != XML_PARSER_EOF)) { const xmlChar *check = CUR_PTR; unsigned int cons = ctxt->input->consumed; if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { xmlParseConditionalSections(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else if (RAW == '%') { xmlParsePEReference(ctxt); } else xmlParseMarkupDecl(ctxt); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); break; } } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Leaving INCLUDE Conditional Section\n"); } } else if (CMP6(CUR_PTR, 'I', 'G', 'N', 'O', 'R', 'E')) { int state; xmlParserInputState instate; int depth = 0; SKIP(6); SKIP_BLANKS; if (RAW != '[') { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } NEXT; } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Entering IGNORE Conditional Section\n"); } /* * Parse up to the end of the conditional section * But disable SAX event generating DTD building in the meantime */ state = ctxt->disableSAX; instate = ctxt->instate; if (ctxt->recovery == 0) ctxt->disableSAX = 1; ctxt->instate = XML_PARSER_IGNORE; while (((depth >= 0) && (RAW != 0)) && (ctxt->instate != XML_PARSER_EOF)) { if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { depth++; SKIP(3); continue; } if ((RAW == ']') && (NXT(1) == ']') && (NXT(2) == '>')) { if (--depth >= 0) SKIP(3); continue; } NEXT; continue; } ctxt->disableSAX = state; ctxt->instate = instate; if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Leaving IGNORE Conditional Section\n"); } } else { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID_KEYWORD, NULL); } if (RAW == 0) SHRINK; if (RAW == 0) { xmlFatalErr(ctxt, XML_ERR_CONDSEC_NOT_FINISHED, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } SKIP(3); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Cleanup conditional section error handling For https://bugzilla.gnome.org/show_bug.cgi?id=744980 The error handling of Conditional Section also need to be straightened as the structure of the document can't be guessed on a failure there and it's better to stop parsing as further errors are likely to be irrelevant.'</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: crypto_bob2( struct exten *ep, /* extension pointer */ struct value *vp /* value pointer */ ) { RSA *rsa; /* GQ parameters */ DSA_SIG *sdsa; /* DSA parameters */ BN_CTX *bctx; /* BIGNUM context */ EVP_MD_CTX ctx; /* signature context */ tstamp_t tstamp; /* NTP timestamp */ BIGNUM *r, *k, *g, *y; u_char *ptr; u_int len; int s_len; /* * If the GQ parameters are not valid, something awful * happened or we are being tormented. */ if (gqkey_info == NULL) { msyslog(LOG_NOTICE, "crypto_bob2: scheme unavailable"); return (XEVNT_ID); } rsa = gqkey_info->pkey->pkey.rsa; /* * Extract r from the challenge. */ len = ntohl(ep->vallen); if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) { msyslog(LOG_ERR, "crypto_bob2: %s", ERR_error_string(ERR_get_error(), NULL)); return (XEVNT_ERR); } /* * Bob rolls random k (0 < k < n), computes y = k u^r mod n and * x = k^b mod n, then sends (y, hash(x)) to Alice. */ bctx = BN_CTX_new(); k = BN_new(); g = BN_new(); y = BN_new(); sdsa = DSA_SIG_new(); BN_rand(k, len * 8, -1, 1); /* k */ BN_mod(k, k, rsa->n, bctx); BN_mod_exp(y, rsa->p, r, rsa->n, bctx); /* u^r mod n */ BN_mod_mul(y, k, y, rsa->n, bctx); /* k u^r mod n */ sdsa->r = BN_dup(y); BN_mod_exp(g, k, rsa->e, rsa->n, bctx); /* k^b mod n */ bighash(g, g); sdsa->s = BN_dup(g); BN_CTX_free(bctx); BN_free(r); BN_free(k); BN_free(g); BN_free(y); #ifdef DEBUG if (debug > 1) RSA_print_fp(stdout, rsa, 0); #endif /* * Encode the values in ASN.1 and sign. The filestamp is from * the local file. */ len = s_len = i2d_DSA_SIG(sdsa, NULL); if (s_len <= 0) { msyslog(LOG_ERR, "crypto_bob2: %s", ERR_error_string(ERR_get_error(), NULL)); DSA_SIG_free(sdsa); return (XEVNT_ERR); } memset(vp, 0, sizeof(struct value)); tstamp = crypto_time(); vp->tstamp = htonl(tstamp); vp->fstamp = htonl(gqkey_info->fstamp); vp->vallen = htonl(len); ptr = emalloc(len); vp->ptr = ptr; i2d_DSA_SIG(sdsa, &ptr); DSA_SIG_free(sdsa); if (tstamp == 0) return (XEVNT_OK); vp->sig = emalloc(sign_siglen); EVP_SignInit(&ctx, sign_digest); EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12); EVP_SignUpdate(&ctx, vp->ptr, len); if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) { INSIST(len <= sign_siglen); vp->siglen = htonl(len); } return (XEVNT_OK); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2014-9297'</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: crypto_recv( struct peer *peer, /* peer structure pointer */ struct recvbuf *rbufp /* packet buffer pointer */ ) { const EVP_MD *dp; /* message digest algorithm */ u_int32 *pkt; /* receive packet pointer */ struct autokey *ap, *bp; /* autokey pointer */ struct exten *ep, *fp; /* extension pointers */ struct cert_info *xinfo; /* certificate info pointer */ int has_mac; /* length of MAC field */ int authlen; /* offset of MAC field */ associd_t associd; /* association ID */ tstamp_t fstamp = 0; /* filestamp */ u_int len; /* extension field length */ u_int code; /* extension field opcode */ u_int vallen = 0; /* value length */ X509 *cert; /* X509 certificate */ char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */ keyid_t cookie; /* crumbles */ int hismode; /* packet mode */ int rval = XEVNT_OK; const u_char *puch; u_int32 temp32; /* * Initialize. Note that the packet has already been checked for * valid format and extension field lengths. First extract the * field length, command code and association ID in host byte * order. These are used with all commands and modes. Then check * the version number, which must be 2, and length, which must * be at least 8 for requests and VALUE_LEN (24) for responses. * Packets that fail either test sink without a trace. The * association ID is saved only if nonzero. */ authlen = LEN_PKT_NOMAC; hismode = (int)PKT_MODE((&rbufp->recv_pkt)->li_vn_mode); while ((has_mac = rbufp->recv_length - authlen) > (int)MAX_MAC_LEN) { pkt = (u_int32 *)&rbufp->recv_pkt + authlen / 4; ep = (struct exten *)pkt; code = ntohl(ep->opcode) & 0xffff0000; len = ntohl(ep->opcode) & 0x0000ffff; // HMS: Why pkt[1] instead of ep->associd ? associd = (associd_t)ntohl(pkt[1]); rval = XEVNT_OK; DPRINTF(1, ("crypto_recv: flags 0x%x ext offset %d len %u code 0x%x associd %d\n", peer->crypto, authlen, len, code >> 16, associd)); /* * Check version number and field length. If bad, * quietly ignore the packet. */ if (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8) { sys_badlength++; code |= CRYPTO_ERROR; } if (len >= VALUE_LEN) { fstamp = ntohl(ep->fstamp); vallen = ntohl(ep->vallen); /* * Bug 2761: I hope this isn't too early... */ if ( vallen == 0 || len - VALUE_LEN < vallen) return XEVNT_LEN; } switch (code) { /* * Install status word, host name, signature scheme and * association ID. In OpenSSL the signature algorithm is * bound to the digest algorithm, so the NID completely * defines the signature scheme. Note the request and * response are identical, but neither is validated by * signature. The request is processed here only in * symmetric modes. The server name field might be * useful to implement access controls in future. */ case CRYPTO_ASSOC: /* * If our state machine is running when this * message arrives, the other fellow might have * restarted. However, this could be an * intruder, so just clamp the poll interval and * find out for ourselves. Otherwise, pass the * extension field to the transmit side. */ if (peer->crypto & CRYPTO_FLAG_CERT) { rval = XEVNT_ERR; break; } if (peer->cmmd) { if (peer->assoc != associd) { rval = XEVNT_ERR; break; } } fp = emalloc(len); memcpy(fp, ep, len); fp->associd = htonl(peer->associd); peer->cmmd = fp; /* fall through */ case CRYPTO_ASSOC | CRYPTO_RESP: /* * Discard the message if it has already been * stored or the message has been amputated. */ if (peer->crypto) { if (peer->assoc != associd) rval = XEVNT_ERR; break; } INSIST(len >= VALUE_LEN); if (vallen == 0 || vallen > MAXHOSTNAME || len - VALUE_LEN < vallen) { rval = XEVNT_LEN; break; } DPRINTF(1, ("crypto_recv: ident host 0x%x %d server 0x%x %d\n", crypto_flags, peer->associd, fstamp, peer->assoc)); temp32 = crypto_flags & CRYPTO_FLAG_MASK; /* * If the client scheme is PC, the server scheme * must be PC. The public key and identity are * presumed valid, so we skip the certificate * and identity exchanges and move immediately * to the cookie exchange which confirms the * server signature. */ if (crypto_flags & CRYPTO_FLAG_PRIV) { if (!(fstamp & CRYPTO_FLAG_PRIV)) { rval = XEVNT_KEY; break; } fstamp |= CRYPTO_FLAG_CERT | CRYPTO_FLAG_VRFY | CRYPTO_FLAG_SIGN; /* * It is an error if either peer supports * identity, but the other does not. */ } else if (hismode == MODE_ACTIVE || hismode == MODE_PASSIVE) { if ((temp32 && !(fstamp & CRYPTO_FLAG_MASK)) || (!temp32 && (fstamp & CRYPTO_FLAG_MASK))) { rval = XEVNT_KEY; break; } } /* * Discard the message if the signature digest * NID is not supported. */ temp32 = (fstamp >> 16) & 0xffff; dp = (const EVP_MD *)EVP_get_digestbynid(temp32); if (dp == NULL) { rval = XEVNT_MD; break; } /* * Save status word, host name and message * digest/signature type. If this is from a * broadcast and the association ID has changed, * request the autokey values. */ peer->assoc = associd; if (hismode == MODE_SERVER) fstamp |= CRYPTO_FLAG_AUTO; if (!(fstamp & CRYPTO_FLAG_TAI)) fstamp |= CRYPTO_FLAG_LEAP; RAND_bytes((u_char *)&peer->hcookie, 4); peer->crypto = fstamp; peer->digest = dp; if (peer->subject != NULL) free(peer->subject); peer->subject = emalloc(vallen + 1); memcpy(peer->subject, ep->pkt, vallen); peer->subject[vallen] = '\0'; if (peer->issuer != NULL) free(peer->issuer); peer->issuer = estrdup(peer->subject); snprintf(statstr, sizeof(statstr), "assoc %d %d host %s %s", peer->associd, peer->assoc, peer->subject, OBJ_nid2ln(temp32)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * Decode X509 certificate in ASN.1 format and extract * the data containing, among other things, subject * name and public key. In the default identification * scheme, the certificate trail is followed to a self * signed trusted certificate. */ case CRYPTO_CERT | CRYPTO_RESP: /* * Discard the message if empty or invalid. */ if (len < VALUE_LEN) break; if ((rval = crypto_verify(ep, NULL, peer)) != XEVNT_OK) break; /* * Scan the certificate list to delete old * versions and link the newest version first on * the list. Then, verify the signature. If the * certificate is bad or missing, just ignore * it. */ if ((xinfo = cert_install(ep, peer)) == NULL) { rval = XEVNT_CRT; break; } if ((rval = cert_hike(peer, xinfo)) != XEVNT_OK) break; /* * We plug in the public key and lifetime from * the first certificate received. However, note * that this certificate might not be signed by * the server, so we can't check the * signature/digest NID. */ if (peer->pkey == NULL) { puch = xinfo->cert.ptr; cert = d2i_X509(NULL, &puch, ntohl(xinfo->cert.vallen)); peer->pkey = X509_get_pubkey(cert); X509_free(cert); } peer->flash &= ~TEST8; temp32 = xinfo->nid; snprintf(statstr, sizeof(statstr), "cert %s %s 0x%x %s (%u) fs %u", xinfo->subject, xinfo->issuer, xinfo->flags, OBJ_nid2ln(temp32), temp32, ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * Schnorr (IFF) identity scheme. This scheme is * designed for use with shared secret server group keys * and where the certificate may be generated by a third * party. The client sends a challenge to the server, * which performs a calculation and returns the result. * A positive result is possible only if both client and * server contain the same secret group key. */ case CRYPTO_IFF | CRYPTO_RESP: /* * Discard the message if invalid. */ if ((rval = crypto_verify(ep, NULL, peer)) != XEVNT_OK) break; /* * If the challenge matches the response, the * server public key, signature and identity are * all verified at the same time. The server is * declared trusted, so we skip further * certificate exchanges and move immediately to * the cookie exchange. */ if ((rval = crypto_iff(ep, peer)) != XEVNT_OK) break; peer->crypto |= CRYPTO_FLAG_VRFY; peer->flash &= ~TEST8; snprintf(statstr, sizeof(statstr), "iff %s fs %u", peer->issuer, ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * Guillou-Quisquater (GQ) identity scheme. This scheme * is designed for use with public certificates carrying * the GQ public key in an extension field. The client * sends a challenge to the server, which performs a * calculation and returns the result. A positive result * is possible only if both client and server contain * the same group key and the server has the matching GQ * private key. */ case CRYPTO_GQ | CRYPTO_RESP: /* * Discard the message if invalid */ if ((rval = crypto_verify(ep, NULL, peer)) != XEVNT_OK) break; /* * If the challenge matches the response, the * server public key, signature and identity are * all verified at the same time. The server is * declared trusted, so we skip further * certificate exchanges and move immediately to * the cookie exchange. */ if ((rval = crypto_gq(ep, peer)) != XEVNT_OK) break; peer->crypto |= CRYPTO_FLAG_VRFY; peer->flash &= ~TEST8; snprintf(statstr, sizeof(statstr), "gq %s fs %u", peer->issuer, ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * Mu-Varadharajan (MV) identity scheme. This scheme is * designed for use with three levels of trust, trusted * host, server and client. The trusted host key is * opaque to servers and clients; the server keys are * opaque to clients and each client key is different. * Client keys can be revoked without requiring new key * generations. */ case CRYPTO_MV | CRYPTO_RESP: /* * Discard the message if invalid. */ if ((rval = crypto_verify(ep, NULL, peer)) != XEVNT_OK) break; /* * If the challenge matches the response, the * server public key, signature and identity are * all verified at the same time. The server is * declared trusted, so we skip further * certificate exchanges and move immediately to * the cookie exchange. */ if ((rval = crypto_mv(ep, peer)) != XEVNT_OK) break; peer->crypto |= CRYPTO_FLAG_VRFY; peer->flash &= ~TEST8; snprintf(statstr, sizeof(statstr), "mv %s fs %u", peer->issuer, ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * Cookie response in client and symmetric modes. If the * cookie bit is set, the working cookie is the EXOR of * the current and new values. */ case CRYPTO_COOK | CRYPTO_RESP: /* * Discard the message if invalid or signature * not verified with respect to the cookie * values. */ if ((rval = crypto_verify(ep, &peer->cookval, peer)) != XEVNT_OK) break; /* * Decrypt the cookie, hunting all the time for * errors. */ if (vallen == (u_int)EVP_PKEY_size(host_pkey)) { u_int32 *cookiebuf = malloc( RSA_size(host_pkey->pkey.rsa)); if (!cookiebuf) { rval = XEVNT_CKY; break; } if (RSA_private_decrypt(vallen, (u_char *)ep->pkt, (u_char *)cookiebuf, host_pkey->pkey.rsa, RSA_PKCS1_OAEP_PADDING) != 4) { rval = XEVNT_CKY; free(cookiebuf); break; } else { cookie = ntohl(*cookiebuf); free(cookiebuf); } } else { rval = XEVNT_CKY; break; } /* * Install cookie values and light the cookie * bit. If this is not broadcast client mode, we * are done here. */ key_expire(peer); if (hismode == MODE_ACTIVE || hismode == MODE_PASSIVE) peer->pcookie = peer->hcookie ^ cookie; else peer->pcookie = cookie; peer->crypto |= CRYPTO_FLAG_COOK; peer->flash &= ~TEST8; snprintf(statstr, sizeof(statstr), "cook %x ts %u fs %u", peer->pcookie, ntohl(ep->tstamp), ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * Install autokey values in broadcast client and * symmetric modes. We have to do this every time the * sever/peer cookie changes or a new keylist is * rolled. Ordinarily, this is automatic as this message * is piggybacked on the first NTP packet sent upon * either of these events. Note that a broadcast client * or symmetric peer can receive this response without a * matching request. */ case CRYPTO_AUTO | CRYPTO_RESP: /* * Discard the message if invalid or signature * not verified with respect to the receive * autokey values. */ if ((rval = crypto_verify(ep, &peer->recval, peer)) != XEVNT_OK) break; /* * Discard the message if a broadcast client and * the association ID does not match. This might * happen if a broacast server restarts the * protocol. A protocol restart will occur at * the next ASSOC message. */ if ((peer->cast_flags & MDF_BCLNT) && peer->assoc != associd) break; /* * Install autokey values and light the * autokey bit. This is not hard. */ if (ep->tstamp == 0) break; if (peer->recval.ptr == NULL) peer->recval.ptr = emalloc(sizeof(struct autokey)); bp = (struct autokey *)peer->recval.ptr; peer->recval.tstamp = ep->tstamp; peer->recval.fstamp = ep->fstamp; ap = (struct autokey *)ep->pkt; bp->seq = ntohl(ap->seq); bp->key = ntohl(ap->key); peer->pkeyid = bp->key; peer->crypto |= CRYPTO_FLAG_AUTO; peer->flash &= ~TEST8; snprintf(statstr, sizeof(statstr), "auto seq %d key %x ts %u fs %u", bp->seq, bp->key, ntohl(ep->tstamp), ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * X509 certificate sign response. Validate the * certificate signed by the server and install. Later * this can be provided to clients of this server in * lieu of the self signed certificate in order to * validate the public key. */ case CRYPTO_SIGN | CRYPTO_RESP: /* * Discard the message if invalid. */ if ((rval = crypto_verify(ep, NULL, peer)) != XEVNT_OK) break; /* * Scan the certificate list to delete old * versions and link the newest version first on * the list. */ if ((xinfo = cert_install(ep, peer)) == NULL) { rval = XEVNT_CRT; break; } peer->crypto |= CRYPTO_FLAG_SIGN; peer->flash &= ~TEST8; temp32 = xinfo->nid; snprintf(statstr, sizeof(statstr), "sign %s %s 0x%x %s (%u) fs %u", xinfo->subject, xinfo->issuer, xinfo->flags, OBJ_nid2ln(temp32), temp32, ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * Install leapseconds values. While the leapsecond * values epoch, TAI offset and values expiration epoch * are retained, only the current TAI offset is provided * via the kernel to other applications. */ case CRYPTO_LEAP | CRYPTO_RESP: /* * Discard the message if invalid. We can't * compare the value timestamps here, as they * can be updated by different servers. */ rval = crypto_verify(ep, NULL, peer); if ((rval != XEVNT_OK ) || (vallen != 3*sizeof(uint32_t)) ) break; /* Check if we can update the basic TAI offset * for our current leap frame. This is a hack * and ignores the time stamps in the autokey * message. */ if (sys_leap != LEAP_NOTINSYNC) leapsec_autokey_tai(ntohl(ep->pkt[0]), rbufp->recv_time.l_ui, NULL); tai_leap.tstamp = ep->tstamp; tai_leap.fstamp = ep->fstamp; crypto_update(); mprintf_event(EVNT_TAI, peer, "%d seconds", ntohl(ep->pkt[0])); peer->crypto |= CRYPTO_FLAG_LEAP; peer->flash &= ~TEST8; snprintf(statstr, sizeof(statstr), "leap TAI offset %d at %u expire %u fs %u", ntohl(ep->pkt[0]), ntohl(ep->pkt[1]), ntohl(ep->pkt[2]), ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * We come here in symmetric modes for miscellaneous * commands that have value fields but are processed on * the transmit side. All we need do here is check for * valid field length. Note that ASSOC is handled * separately. */ case CRYPTO_CERT: case CRYPTO_IFF: case CRYPTO_GQ: case CRYPTO_MV: case CRYPTO_COOK: case CRYPTO_SIGN: if (len < VALUE_LEN) { rval = XEVNT_LEN; break; } /* fall through */ /* * We come here in symmetric modes for requests * requiring a response (above plus AUTO and LEAP) and * for responses. If a request, save the extension field * for later; invalid requests will be caught on the * transmit side. If an error or invalid response, * declare a protocol error. */ default: if (code & (CRYPTO_RESP | CRYPTO_ERROR)) { rval = XEVNT_ERR; } else if (peer->cmmd == NULL) { fp = emalloc(len); memcpy(fp, ep, len); peer->cmmd = fp; } } /* * The first error found terminates the extension field * scan and we return the laundry to the caller. */ if (rval != XEVNT_OK) { snprintf(statstr, sizeof(statstr), "%04x %d %02x %s", htonl(ep->opcode), associd, rval, eventstr(rval)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); return (rval); } authlen += (len + 3) / 4 * 4; } return (rval); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2014-9297'</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: crypto_bob( struct exten *ep, /* extension pointer */ struct value *vp /* value pointer */ ) { DSA *dsa; /* IFF parameters */ DSA_SIG *sdsa; /* DSA signature context fake */ BN_CTX *bctx; /* BIGNUM context */ EVP_MD_CTX ctx; /* signature context */ tstamp_t tstamp; /* NTP timestamp */ BIGNUM *bn, *bk, *r; u_char *ptr; u_int len; /* extension field length */ u_int vallen = 0; /* value length */ /* * If the IFF parameters are not valid, something awful * happened or we are being tormented. */ if (iffkey_info == NULL) { msyslog(LOG_NOTICE, "crypto_bob: scheme unavailable"); return (XEVNT_ID); } dsa = iffkey_info->pkey->pkey.dsa; /* * Extract r from the challenge. */ vallen = ntohl(ep->vallen); len = ntohl(ep->opcode) & 0x0000ffff; if (vallen == 0 || len < VALUE_LEN || len - VALUE_LEN < vallen) return XEVNT_LEN; if ((r = BN_bin2bn((u_char *)ep->pkt, vallen, NULL)) == NULL) { msyslog(LOG_ERR, "crypto_bob: %s", ERR_error_string(ERR_get_error(), NULL)); return (XEVNT_ERR); } /* * Bob rolls random k (0 < k < q), computes y = k + b r mod q * and x = g^k mod p, then sends (y, hash(x)) to Alice. */ bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new(); sdsa = DSA_SIG_new(); BN_rand(bk, vallen * 8, -1, 1); /* k */ BN_mod_mul(bn, dsa->priv_key, r, dsa->q, bctx); /* b r mod q */ BN_add(bn, bn, bk); BN_mod(bn, bn, dsa->q, bctx); /* k + b r mod q */ sdsa->r = BN_dup(bn); BN_mod_exp(bk, dsa->g, bk, dsa->p, bctx); /* g^k mod p */ bighash(bk, bk); sdsa->s = BN_dup(bk); BN_CTX_free(bctx); BN_free(r); BN_free(bn); BN_free(bk); #ifdef DEBUG if (debug > 1) DSA_print_fp(stdout, dsa, 0); #endif /* * Encode the values in ASN.1 and sign. The filestamp is from * the local file. */ vallen = i2d_DSA_SIG(sdsa, NULL); if (vallen == 0) { msyslog(LOG_ERR, "crypto_bob: %s", ERR_error_string(ERR_get_error(), NULL)); DSA_SIG_free(sdsa); return (XEVNT_ERR); } if (vallen > MAX_VALLEN) { msyslog(LOG_ERR, "crypto_bob: signature is too big: %d", vallen); DSA_SIG_free(sdsa); return (XEVNT_LEN); } memset(vp, 0, sizeof(struct value)); tstamp = crypto_time(); vp->tstamp = htonl(tstamp); vp->fstamp = htonl(iffkey_info->fstamp); vp->vallen = htonl(vallen); ptr = emalloc(vallen); vp->ptr = ptr; i2d_DSA_SIG(sdsa, &ptr); DSA_SIG_free(sdsa); if (tstamp == 0) return (XEVNT_OK); /* XXX: more validation to make sure the sign fits... */ vp->sig = emalloc(sign_siglen); EVP_SignInit(&ctx, sign_digest); EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12); EVP_SignUpdate(&ctx, vp->ptr, vallen); if (EVP_SignFinal(&ctx, vp->sig, &vallen, sign_pkey)) { INSIST(vallen <= sign_siglen); vp->siglen = htonl(vallen); } return (XEVNT_OK); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2014-9297'</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: do_restrict( sockaddr_u *srcadr, endpt *inter, struct req_pkt *inpkt, int op ) { char * datap; struct conf_restrict cr; u_short items; size_t item_sz; sockaddr_u matchaddr; sockaddr_u matchmask; int bad; /* * Do a check of the flags to make sure that only * the NTPPORT flag is set, if any. If not, complain * about it. Note we are very picky here. */ items = INFO_NITEMS(inpkt->err_nitems); item_sz = INFO_ITEMSIZE(inpkt->mbz_itemsize); datap = inpkt->u.data; if (item_sz > sizeof(cr)) { req_ack(srcadr, inter, inpkt, INFO_ERR_FMT); return; } bad = FALSE; while (items-- > 0 && !bad) { memcpy(&cr, datap, item_sz); cr.flags = ntohs(cr.flags); cr.mflags = ntohs(cr.mflags); if (~RESM_NTPONLY & cr.mflags) bad |= 1; if (~RES_ALLFLAGS & cr.flags) bad |= 2; if (INADDR_ANY != cr.mask) { if (client_v6_capable && cr.v6_flag) { if (IN6_IS_ADDR_UNSPECIFIED(&cr.addr6)) bad |= 4; } else { if (INADDR_ANY == cr.addr) bad |= 8; } } datap += item_sz; } if (bad) { msyslog(LOG_ERR, "do_restrict: bad = %#x", bad); req_ack(srcadr, inter, inpkt, INFO_ERR_FMT); return; } /* * Looks okay, try it out */ ZERO_SOCK(&matchaddr); ZERO_SOCK(&matchmask); datap = inpkt->u.data; while (items-- > 0) { memcpy(&cr, datap, item_sz); cr.flags = ntohs(cr.flags); cr.mflags = ntohs(cr.mflags); if (client_v6_capable && cr.v6_flag) { AF(&matchaddr) = AF_INET6; AF(&matchmask) = AF_INET6; SOCK_ADDR6(&matchaddr) = cr.addr6; SOCK_ADDR6(&matchmask) = cr.mask6; } else { AF(&matchaddr) = AF_INET; AF(&matchmask) = AF_INET; NSRCADR(&matchaddr) = cr.addr; NSRCADR(&matchmask) = cr.mask; } hack_restrict(op, &matchaddr, &matchmask, cr.mflags, cr.flags, 0); datap += item_sz; } req_ack(srcadr, inter, inpkt, INFO_OKAY); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': '[TALOS-CAN-0052] crash by loop counter underrun.'</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: MD5auth_setkey( keyid_t keyno, int keytype, const u_char *key, size_t len ) { symkey * sk; symkey ** bucket; u_char * secret; size_t secretsize; DEBUG_ENSURE(keytype <= USHRT_MAX); DEBUG_ENSURE(len < 4 * 1024); /* * See if we already have the key. If so just stick in the * new value. */ bucket = &key_hash[KEYHASH(keyno)]; for (sk = *bucket; sk != NULL; sk = sk->hlink) { if (keyno == sk->keyid) { /* TALOS-CAN-0054: make sure we have a buffer! */ if (NULL == sk->secret) sk->secret = emalloc(len); sk->type = (u_short)keytype; secretsize = len; sk->secretsize = (u_short)secretsize; #ifndef DISABLE_BUG1243_FIX memcpy(sk->secret, key, secretsize); #else strlcpy((char *)sk->secret, (const char *)key, secretsize); #endif if (cache_keyid == keyno) { cache_flags = 0; cache_keyid = 0; } return; } } /* * Need to allocate new structure. Do it. */ secretsize = len; secret = emalloc(secretsize); #ifndef DISABLE_BUG1243_FIX memcpy(secret, key, secretsize); #else strlcpy((char *)secret, (const char *)key, secretsize); #endif allocsymkey(bucket, keyno, 0, (u_short)keytype, 0, (u_short)secretsize, secret); #ifdef DEBUG if (debug >= 4) { size_t j; printf("auth_setkey: key %d type %d len %d ", (int)keyno, keytype, (int)secretsize); for (j = 0; j < secretsize; j++) printf("%02x", secret[j]); printf("\n"); } #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': '[TALOS-CAN-0054] memory corruption - make sure there's *always* a new buffer for storing the key again'</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: save_config( struct recvbuf *rbufp, int restrict_mask ) { char reply[128]; #ifdef SAVECONFIG char filespec[128]; char filename[128]; char fullpath[512]; const char savedconfig_eq[] = "savedconfig="; char savedconfig[sizeof(savedconfig_eq) + sizeof(filename)]; time_t now; int fd; FILE *fptr; #endif if (RES_NOMODIFY & restrict_mask) { snprintf(reply, sizeof(reply), "saveconfig prohibited by restrict ... nomodify"); ctl_putdata(reply, strlen(reply), 0); ctl_flushpkt(0); NLOG(NLOG_SYSINFO) msyslog(LOG_NOTICE, "saveconfig from %s rejected due to nomodify restriction", stoa(&rbufp->recv_srcadr)); sys_restricted++; return; } #ifdef SAVECONFIG if (NULL == saveconfigdir) { snprintf(reply, sizeof(reply), "saveconfig prohibited, no saveconfigdir configured"); ctl_putdata(reply, strlen(reply), 0); ctl_flushpkt(0); NLOG(NLOG_SYSINFO) msyslog(LOG_NOTICE, "saveconfig from %s rejected, no saveconfigdir", stoa(&rbufp->recv_srcadr)); return; } if (0 == reqend - reqpt) return; strlcpy(filespec, reqpt, sizeof(filespec)); time(&now); /* * allow timestamping of the saved config filename with * strftime() format such as: * ntpq -c "saveconfig ntp-%Y%m%d-%H%M%S.conf" * XXX: Nice feature, but not too safe. */ if (0 == strftime(filename, sizeof(filename), filespec, localtime(&now))) strlcpy(filename, filespec, sizeof(filename)); /* * Conceptually we should be searching for DIRSEP in filename, * however Windows actually recognizes both forward and * backslashes as equivalent directory separators at the API * level. On POSIX systems we could allow '\\' but such * filenames are tricky to manipulate from a shell, so just * reject both types of slashes on all platforms. */ if (strchr(filename, '\\') || strchr(filename, '/')) { snprintf(reply, sizeof(reply), "saveconfig does not allow directory in filename"); ctl_putdata(reply, strlen(reply), 0); ctl_flushpkt(0); msyslog(LOG_NOTICE, "saveconfig with path from %s rejected", stoa(&rbufp->recv_srcadr)); return; } snprintf(fullpath, sizeof(fullpath), "%s%s", saveconfigdir, filename); fd = open(fullpath, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR); if (-1 == fd) fptr = NULL; else fptr = fdopen(fd, "w"); if (NULL == fptr || -1 == dump_all_config_trees(fptr, 1)) { snprintf(reply, sizeof(reply), "Unable to save configuration to file %s", filename); msyslog(LOG_ERR, "saveconfig %s from %s failed", filename, stoa(&rbufp->recv_srcadr)); } else { snprintf(reply, sizeof(reply), "Configuration saved to %s", filename); msyslog(LOG_NOTICE, "Configuration saved to %s (requested by %s)", fullpath, stoa(&rbufp->recv_srcadr)); /* * save the output filename in system variable * savedconfig, retrieved with: * ntpq -c "rv 0 savedconfig" */ snprintf(savedconfig, sizeof(savedconfig), "%s%s", savedconfig_eq, filename); set_sys_var(savedconfig, strlen(savedconfig) + 1, RO); } if (NULL != fptr) fclose(fptr); #else /* !SAVECONFIG follows */ snprintf(reply, sizeof(reply), "saveconfig unavailable, configured with --disable-saveconfig"); #endif ctl_putdata(reply, strlen(reply), 0); ctl_flushpkt(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': '[TALOS-CAN-0062] prevent directory traversal for VMS, too, when using 'saveconfig' command.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: auth_delkeys(void) { symkey * sk; ITER_DLIST_BEGIN(key_listhead, sk, llink, symkey) if (sk->keyid > NTP_MAXKEY) { /* autokey */ continue; } /* * Don't lose info as to which keys are trusted. */ if (KEY_TRUSTED & sk->flags) { if (sk->secret != NULL) { memset(sk->secret, '\0', sk->secretsize); free(sk->secret); } sk->secretsize = 0; sk->lifetime = 0; } else { freesymkey(sk, &key_hash[KEYHASH(sk->keyid)]); } ITER_DLIST_END() } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': '[TALOS-CAN-0054] memory corruption in password store'</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: decodenetnum( const char *num, sockaddr_u *netnum ) { struct addrinfo hints, *ai = NULL; int err; u_short port; const char *cp; const char *port_str; char *pp; char *np; char name[80]; REQUIRE(num != NULL); REQUIRE(strlen(num) < sizeof(name)); port_str = NULL; if ('[' != num[0]) { /* * to distinguish IPv6 embedded colons from a port * specification on an IPv4 address, assume all * legal IPv6 addresses have at least two colons. */ pp = strchr(num, ':'); if (NULL == pp) cp = num; /* no colons */ else if (NULL != strchr(pp + 1, ':')) cp = num; /* two or more colons */ else { /* one colon */ strlcpy(name, num, sizeof(name)); cp = name; pp = strchr(cp, ':'); *pp = '\0'; port_str = pp + 1; } } else { cp = num + 1; np = name; while (*cp && ']' != *cp) *np++ = *cp++; *np = 0; if (']' == cp[0] && ':' == cp[1] && '\0' != cp[2]) port_str = &cp[2]; cp = name; } ZERO(hints); hints.ai_flags = Z_AI_NUMERICHOST; err = getaddrinfo(cp, "ntp", &hints, &ai); if (err != 0) return 0; INSIST(ai->ai_addrlen <= sizeof(*netnum)); ZERO(*netnum); memcpy(netnum, ai->ai_addr, ai->ai_addrlen); freeaddrinfo(ai); if (NULL == port_str || 1 != sscanf(port_str, "%hu", &port)) port = NTP_PORT; SET_PORT(netnum, port); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': '[Sec 2922] decodenetnum() will ASSERT botch instead of returning FAIL on some bogus values. Harlan Stenn.'</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 vivid_fb_ioctl(struct fb_info *info, unsigned cmd, unsigned long arg) { struct vivid_dev *dev = (struct vivid_dev *)info->par; switch (cmd) { case FBIOGET_VBLANK: { struct fb_vblank vblank; vblank.flags = FB_VBLANK_HAVE_COUNT | FB_VBLANK_HAVE_VCOUNT | FB_VBLANK_HAVE_VSYNC; vblank.count = 0; vblank.vcount = 0; vblank.hcount = 0; if (copy_to_user((void __user *)arg, &vblank, sizeof(vblank))) return -EFAULT; return 0; } default: dprintk(dev, 1, "Unknown ioctl %08x\n", cmd); return -EINVAL; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[media] media/vivid-osd: fix info leak in ioctl The vivid_fb_ioctl() code fails to initialize the 16 _reserved bytes of struct fb_vblank after the ->hcount member. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Salva Peiró <[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: build_principal_va(krb5_context context, krb5_principal princ, unsigned int rlen, const char *realm, va_list ap) { krb5_error_code retval = 0; char *r = NULL; krb5_data *data = NULL; krb5_int32 count = 0; krb5_int32 size = 2; /* initial guess at needed space */ char *component = NULL; data = malloc(size * sizeof(krb5_data)); if (!data) { retval = ENOMEM; } if (!retval) { r = strdup(realm); if (!r) { retval = ENOMEM; } } while (!retval && (component = va_arg(ap, char *))) { if (count == size) { krb5_data *new_data = NULL; size *= 2; new_data = realloc(data, size * sizeof(krb5_data)); if (new_data) { data = new_data; } else { retval = ENOMEM; } } if (!retval) { data[count].length = strlen(component); data[count].data = strdup(component); if (!data[count].data) { retval = ENOMEM; } count++; } } if (!retval) { princ->type = KRB5_NT_UNKNOWN; princ->magic = KV5M_PRINCIPAL; princ->realm = make_data(r, rlen); princ->data = data; princ->length = count; r = NULL; /* take ownership */ data = NULL; /* take ownership */ } if (data) { while (--count >= 0) { free(data[count].data); } free(data); } free(r); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-125'], 'message': 'Fix build_principal memory bug [CVE-2015-2697] In build_principal_va(), use k5memdup0() instead of strdup() to make a copy of the realm, to ensure that we allocate the correct number of bytes and do not read past the end of the input string. This bug affects krb5_build_principal(), krb5_build_principal_va(), and krb5_build_principal_alloc_va(). krb5_build_principal_ext() is not affected. CVE-2015-2697: In MIT krb5 1.7 and later, an authenticated attacker may be able to cause a KDC to crash using a TGS request with a large realm field beginning with a null byte. If the KDC attempts to find a referral to answer the request, it constructs a principal name for lookup using krb5_build_principal() with the requested realm. Due to a bug in this function, the null byte causes only one byte be allocated for the realm field of the constructed principal, far less than its length. Subsequent operations on the lookup principal may cause a read beyond the end of the mapped memory region, causing the KDC process to crash. CVSSv2: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8252 (new) target_version: 1.14 tags: pullup'</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: iakerb_gss_accept_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_cred_id_t verifier_cred_handle, gss_buffer_t input_token, gss_channel_bindings_t input_chan_bindings, gss_name_t *src_name, gss_OID *mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec, gss_cred_id_t *delegated_cred_handle) { OM_uint32 major_status = GSS_S_FAILURE; OM_uint32 code; iakerb_ctx_id_t ctx; int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT); if (initialContextToken) { code = iakerb_alloc_context(&ctx); if (code != 0) goto cleanup; } else ctx = (iakerb_ctx_id_t)*context_handle; if (iakerb_is_iakerb_token(input_token)) { if (ctx->gssc != GSS_C_NO_CONTEXT) { /* We shouldn't get an IAKERB token now. */ code = G_WRONG_TOKID; major_status = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } code = iakerb_acceptor_step(ctx, initialContextToken, input_token, output_token); if (code == (OM_uint32)KRB5_BAD_MSIZE) major_status = GSS_S_DEFECTIVE_TOKEN; if (code != 0) goto cleanup; if (initialContextToken) { *context_handle = (gss_ctx_id_t)ctx; ctx = NULL; } if (src_name != NULL) *src_name = GSS_C_NO_NAME; if (mech_type != NULL) *mech_type = (gss_OID)gss_mech_iakerb; if (ret_flags != NULL) *ret_flags = 0; if (time_rec != NULL) *time_rec = 0; if (delegated_cred_handle != NULL) *delegated_cred_handle = GSS_C_NO_CREDENTIAL; major_status = GSS_S_CONTINUE_NEEDED; } else { krb5_gss_ctx_ext_rec exts; iakerb_make_exts(ctx, &exts); major_status = krb5_gss_accept_sec_context_ext(&code, &ctx->gssc, verifier_cred_handle, input_token, input_chan_bindings, src_name, NULL, output_token, ret_flags, time_rec, delegated_cred_handle, &exts); if (major_status == GSS_S_COMPLETE) { *context_handle = ctx->gssc; ctx->gssc = NULL; iakerb_release_context(ctx); } if (mech_type != NULL) *mech_type = (gss_OID)gss_mech_krb5; } cleanup: if (initialContextToken && GSS_ERROR(major_status)) { iakerb_release_context(ctx); *context_handle = GSS_C_NO_CONTEXT; } *minor_status = code; return major_status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18'], 'message': 'Fix IAKERB context aliasing bugs [CVE-2015-2696] The IAKERB mechanism currently replaces its context handle with the krb5 mechanism handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the IAKERB context structure after context establishment and add new IAKERB entry points to refer to it with that type. Add initiate and established flags to the IAKERB context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2696: In MIT krb5 1.9 and later, applications which call gss_inquire_context() on a partially-established IAKERB context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted IAKERB packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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 gss_iakerbmechglue_init(void) { struct gss_mech_config mech_iakerb; struct gss_config iakerb_mechanism = krb5_mechanism; /* IAKERB mechanism mirrors krb5, but with different context SPIs */ iakerb_mechanism.gss_accept_sec_context = iakerb_gss_accept_sec_context; iakerb_mechanism.gss_init_sec_context = iakerb_gss_init_sec_context; iakerb_mechanism.gss_delete_sec_context = iakerb_gss_delete_sec_context; iakerb_mechanism.gss_acquire_cred = iakerb_gss_acquire_cred; iakerb_mechanism.gssspi_acquire_cred_with_password = iakerb_gss_acquire_cred_with_password; memset(&mech_iakerb, 0, sizeof(mech_iakerb)); mech_iakerb.mech = &iakerb_mechanism; mech_iakerb.mechNameStr = "iakerb"; mech_iakerb.mech_type = (gss_OID)gss_mech_iakerb; gssint_register_mechinfo(&mech_iakerb); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18'], 'message': 'Fix IAKERB context aliasing bugs [CVE-2015-2696] The IAKERB mechanism currently replaces its context handle with the krb5 mechanism handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the IAKERB context structure after context establishment and add new IAKERB entry points to refer to it with that type. Add initiate and established flags to the IAKERB context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2696: In MIT krb5 1.9 and later, applications which call gss_inquire_context() on a partially-established IAKERB context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted IAKERB packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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: spnego_gss_unwrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 ret; ret = gss_unwrap_iov(minor_status, context_handle, conf_state, qop_state, iov, iov_count); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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: spnego_gss_accept_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_cred_id_t verifier_cred_handle, gss_buffer_t input_token, gss_channel_bindings_t input_chan_bindings, gss_name_t *src_name, gss_OID *mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec, gss_cred_id_t *delegated_cred_handle) { OM_uint32 ret, tmpmin, negState; send_token_flag return_token; gss_buffer_t mechtok_in, mic_in, mic_out; gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER; spnego_gss_ctx_id_t sc = NULL; spnego_gss_cred_id_t spcred = NULL; int sendTokenInit = 0, tmpret; mechtok_in = mic_in = mic_out = GSS_C_NO_BUFFER; /* * This function works in three steps: * * 1. Perform mechanism negotiation. * 2. Invoke the negotiated mech's gss_accept_sec_context function * and examine the results. * 3. Process or generate MICs if necessary. * * Step one determines whether the negotiation requires a MIC exchange, * while steps two and three share responsibility for determining when * the exchange is complete. If the selected mech completes in this * call and no MIC exchange is expected, then step 2 will decide. If a * MIC exchange is expected, then step 3 will decide. If an error * occurs in any step, the exchange will be aborted, possibly with an * error token. * * negState determines the state of the negotiation, and is * communicated to the acceptor if a continuing token is sent. * return_token is used to indicate what type of token, if any, should * be generated. */ /* Validate arguments. */ if (minor_status != NULL) *minor_status = 0; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } if (minor_status == NULL || output_token == GSS_C_NO_BUFFER || context_handle == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; if (input_token == GSS_C_NO_BUFFER) return GSS_S_CALL_INACCESSIBLE_READ; /* Step 1: Perform mechanism negotiation. */ sc = (spnego_gss_ctx_id_t)*context_handle; spcred = (spnego_gss_cred_id_t)verifier_cred_handle; if (sc == NULL || sc->internal_mech == GSS_C_NO_OID) { /* Process an initial token or request for NegHints. */ if (src_name != NULL) *src_name = GSS_C_NO_NAME; if (mech_type != NULL) *mech_type = GSS_C_NO_OID; if (time_rec != NULL) *time_rec = 0; if (ret_flags != NULL) *ret_flags = 0; if (delegated_cred_handle != NULL) *delegated_cred_handle = GSS_C_NO_CREDENTIAL; if (input_token->length == 0) { ret = acc_ctx_hints(minor_status, context_handle, spcred, &mic_out, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; sendTokenInit = 1; ret = GSS_S_CONTINUE_NEEDED; } else { /* Can set negState to REQUEST_MIC */ ret = acc_ctx_new(minor_status, input_token, context_handle, spcred, &mechtok_in, &mic_in, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; ret = GSS_S_CONTINUE_NEEDED; } } else { /* Process a response token. Can set negState to * ACCEPT_INCOMPLETE. */ ret = acc_ctx_cont(minor_status, input_token, context_handle, &mechtok_in, &mic_in, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; ret = GSS_S_CONTINUE_NEEDED; } /* Step 2: invoke the negotiated mechanism's gss_accept_sec_context * function. */ sc = (spnego_gss_ctx_id_t)*context_handle; /* * Handle mechtok_in and mic_in only if they are * present in input_token. If neither is present, whether * this is an error depends on whether this is the first * round-trip. RET is set to a default value according to * whether it is the first round-trip. */ if (negState != REQUEST_MIC && mechtok_in != GSS_C_NO_BUFFER) { ret = acc_ctx_call_acc(minor_status, sc, spcred, mechtok_in, mech_type, &mechtok_out, ret_flags, time_rec, delegated_cred_handle, &negState, &return_token); } /* Step 3: process or generate the MIC, if the negotiated mech is * complete and supports MICs. */ if (!HARD_ERROR(ret) && sc->mech_complete && (sc->ctx_flags & GSS_C_INTEG_FLAG)) { ret = handle_mic(minor_status, mic_in, (mechtok_out.length != 0), sc, &mic_out, &negState, &return_token); } cleanup: if (return_token == INIT_TOKEN_SEND && sendTokenInit) { assert(sc != NULL); tmpret = make_spnego_tokenInit_msg(sc, 1, mic_out, 0, GSS_C_NO_BUFFER, return_token, output_token); if (tmpret < 0) ret = GSS_S_FAILURE; } else if (return_token != NO_TOKEN_SEND && return_token != CHECK_MIC) { tmpret = make_spnego_tokenTarg_msg(negState, sc ? sc->internal_mech : GSS_C_NO_OID, &mechtok_out, mic_out, return_token, output_token); if (tmpret < 0) ret = GSS_S_FAILURE; } if (ret == GSS_S_COMPLETE) { *context_handle = (gss_ctx_id_t)sc->ctx_handle; if (sc->internal_name != GSS_C_NO_NAME && src_name != NULL) { *src_name = sc->internal_name; sc->internal_name = GSS_C_NO_NAME; } release_spnego_ctx(&sc); } else if (ret != GSS_S_CONTINUE_NEEDED) { if (sc != NULL) { gss_delete_sec_context(&tmpmin, &sc->ctx_handle, GSS_C_NO_BUFFER); release_spnego_ctx(&sc); } *context_handle = GSS_C_NO_CONTEXT; } gss_release_buffer(&tmpmin, &mechtok_out); if (mechtok_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechtok_in); free(mechtok_in); } if (mic_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mic_in); free(mic_in); } if (mic_out != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mic_out); free(mic_out); } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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: spnego_gss_delete_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t output_token) { OM_uint32 ret = GSS_S_COMPLETE; spnego_gss_ctx_id_t *ctx = (spnego_gss_ctx_id_t *)context_handle; *minor_status = 0; if (context_handle == NULL) return (GSS_S_FAILURE); if (*ctx == NULL) return (GSS_S_COMPLETE); /* * If this is still an SPNEGO mech, release it locally. */ if ((*ctx)->magic_num == SPNEGO_MAGIC_ID) { (void) gss_delete_sec_context(minor_status, &(*ctx)->ctx_handle, output_token); (void) release_spnego_ctx(ctx); } else { ret = gss_delete_sec_context(minor_status, context_handle, output_token); } return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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: spnego_gss_complete_auth_token( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer) { OM_uint32 ret; ret = gss_complete_auth_token(minor_status, context_handle, input_message_buffer); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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: spnego_gss_get_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t qop_req, gss_iov_buffer_desc *iov, int iov_count) { return gss_get_mic_iov(minor_status, context_handle, qop_req, iov, iov_count); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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: spnego_gss_wrap_aead(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, gss_buffer_t input_assoc_buffer, gss_buffer_t input_payload_buffer, int *conf_state, gss_buffer_t output_message_buffer) { OM_uint32 ret; ret = gss_wrap_aead(minor_status, context_handle, conf_req_flag, qop_req, input_assoc_buffer, input_payload_buffer, conf_state, output_message_buffer); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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: spnego_gss_pseudo_random(OM_uint32 *minor_status, gss_ctx_id_t context, int prf_key, const gss_buffer_t prf_in, ssize_t desired_output_len, gss_buffer_t prf_out) { OM_uint32 ret; ret = gss_pseudo_random(minor_status, context, prf_key, prf_in, desired_output_len, prf_out); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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: spnego_gss_unwrap_aead(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer, gss_buffer_t input_assoc_buffer, gss_buffer_t output_payload_buffer, int *conf_state, gss_qop_t *qop_state) { OM_uint32 ret; ret = gss_unwrap_aead(minor_status, context_handle, input_message_buffer, input_assoc_buffer, output_payload_buffer, conf_state, qop_state); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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: spnego_gss_init_sec_context( OM_uint32 *minor_status, gss_cred_id_t claimant_cred_handle, gss_ctx_id_t *context_handle, gss_name_t target_name, gss_OID mech_type, OM_uint32 req_flags, OM_uint32 time_req, gss_channel_bindings_t input_chan_bindings, gss_buffer_t input_token, gss_OID *actual_mech, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec) { send_token_flag send_token = NO_TOKEN_SEND; OM_uint32 tmpmin, ret, negState; gss_buffer_t mechtok_in, mechListMIC_in, mechListMIC_out; gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER; spnego_gss_cred_id_t spcred = NULL; spnego_gss_ctx_id_t spnego_ctx = NULL; dsyslog("Entering init_sec_context\n"); mechtok_in = mechListMIC_out = mechListMIC_in = GSS_C_NO_BUFFER; negState = REJECT; /* * This function works in three steps: * * 1. Perform mechanism negotiation. * 2. Invoke the negotiated or optimistic mech's gss_init_sec_context * function and examine the results. * 3. Process or generate MICs if necessary. * * The three steps share responsibility for determining when the * exchange is complete. If the selected mech completed in a previous * call and no MIC exchange is expected, then step 1 will decide. If * the selected mech completes in this call and no MIC exchange is * expected, then step 2 will decide. If a MIC exchange is expected, * then step 3 will decide. If an error occurs in any step, the * exchange will be aborted, possibly with an error token. * * negState determines the state of the negotiation, and is * communicated to the acceptor if a continuing token is sent. * send_token is used to indicate what type of token, if any, should be * generated. */ /* Validate arguments. */ if (minor_status != NULL) *minor_status = 0; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } if (minor_status == NULL || output_token == GSS_C_NO_BUFFER || context_handle == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; if (actual_mech != NULL) *actual_mech = GSS_C_NO_OID; /* Step 1: perform mechanism negotiation. */ spcred = (spnego_gss_cred_id_t)claimant_cred_handle; if (*context_handle == GSS_C_NO_CONTEXT) { ret = init_ctx_new(minor_status, spcred, context_handle, &send_token); if (ret != GSS_S_CONTINUE_NEEDED) { goto cleanup; } } else { ret = init_ctx_cont(minor_status, context_handle, input_token, &mechtok_in, &mechListMIC_in, &negState, &send_token); if (HARD_ERROR(ret)) { goto cleanup; } } /* Step 2: invoke the selected or optimistic mechanism's * gss_init_sec_context function, if it didn't complete previously. */ spnego_ctx = (spnego_gss_ctx_id_t)*context_handle; if (!spnego_ctx->mech_complete) { ret = init_ctx_call_init( minor_status, spnego_ctx, spcred, target_name, req_flags, time_req, mechtok_in, actual_mech, &mechtok_out, ret_flags, time_rec, &negState, &send_token); /* Give the mechanism a chance to force a mechlistMIC. */ if (!HARD_ERROR(ret) && mech_requires_mechlistMIC(spnego_ctx)) spnego_ctx->mic_reqd = 1; } /* Step 3: process or generate the MIC, if the negotiated mech is * complete and supports MICs. */ if (!HARD_ERROR(ret) && spnego_ctx->mech_complete && (spnego_ctx->ctx_flags & GSS_C_INTEG_FLAG)) { ret = handle_mic(minor_status, mechListMIC_in, (mechtok_out.length != 0), spnego_ctx, &mechListMIC_out, &negState, &send_token); } cleanup: if (send_token == INIT_TOKEN_SEND) { if (make_spnego_tokenInit_msg(spnego_ctx, 0, mechListMIC_out, req_flags, &mechtok_out, send_token, output_token) < 0) { ret = GSS_S_FAILURE; } } else if (send_token != NO_TOKEN_SEND) { if (make_spnego_tokenTarg_msg(negState, GSS_C_NO_OID, &mechtok_out, mechListMIC_out, send_token, output_token) < 0) { ret = GSS_S_FAILURE; } } gss_release_buffer(&tmpmin, &mechtok_out); if (ret == GSS_S_COMPLETE) { /* * Now, switch the output context to refer to the * negotiated mechanism's context. */ *context_handle = (gss_ctx_id_t)spnego_ctx->ctx_handle; if (actual_mech != NULL) *actual_mech = spnego_ctx->actual_mech; if (ret_flags != NULL) *ret_flags = spnego_ctx->ctx_flags; release_spnego_ctx(&spnego_ctx); } else if (ret != GSS_S_CONTINUE_NEEDED) { if (spnego_ctx != NULL) { gss_delete_sec_context(&tmpmin, &spnego_ctx->ctx_handle, GSS_C_NO_BUFFER); release_spnego_ctx(&spnego_ctx); } *context_handle = GSS_C_NO_CONTEXT; } if (mechtok_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechtok_in); free(mechtok_in); } if (mechListMIC_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechListMIC_in); free(mechListMIC_in); } if (mechListMIC_out != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechListMIC_out); free(mechListMIC_out); } return ret; } /* init_sec_context */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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: spnego_gss_export_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t interprocess_token) { OM_uint32 ret; ret = gss_export_sec_context(minor_status, context_handle, interprocess_token); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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: spnego_gss_wrap( OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, gss_buffer_t input_message_buffer, int *conf_state, gss_buffer_t output_message_buffer) { OM_uint32 ret; ret = gss_wrap(minor_status, context_handle, conf_req_flag, qop_req, input_message_buffer, conf_state, output_message_buffer); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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: spnego_gss_inquire_context( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, gss_name_t *src_name, gss_name_t *targ_name, OM_uint32 *lifetime_rec, gss_OID *mech_type, OM_uint32 *ctx_flags, int *locally_initiated, int *opened) { OM_uint32 ret = GSS_S_COMPLETE; ret = gss_inquire_context(minor_status, context_handle, src_name, targ_name, lifetime_rec, mech_type, ctx_flags, locally_initiated, opened); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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: spnego_gss_verify_mic( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_buffer_t msg_buffer, const gss_buffer_t token_buffer, gss_qop_t *qop_state) { OM_uint32 ret; ret = gss_verify_mic(minor_status, context_handle, msg_buffer, token_buffer, qop_state); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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: spnego_gss_get_mic( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, gss_qop_t qop_req, const gss_buffer_t message_buffer, gss_buffer_t message_token) { OM_uint32 ret; ret = gss_get_mic(minor_status, context_handle, qop_req, message_buffer, message_token); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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: spnego_gss_wrap_size_limit( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 *max_input_size) { OM_uint32 ret; ret = gss_wrap_size_limit(minor_status, context_handle, conf_req_flag, qop_req, req_output_size, max_input_size); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</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: xmlParseConditionalSections(xmlParserCtxtPtr ctxt) { int id = ctxt->input->id; SKIP(3); SKIP_BLANKS; if (CMP7(CUR_PTR, 'I', 'N', 'C', 'L', 'U', 'D', 'E')) { SKIP(7); SKIP_BLANKS; if (RAW != '[') { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL); xmlStopParser(ctxt); return; } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } NEXT; } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Entering INCLUDE Conditional Section\n"); } while (((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') || (NXT(2) != '>'))) && (ctxt->instate != XML_PARSER_EOF)) { const xmlChar *check = CUR_PTR; unsigned int cons = ctxt->input->consumed; if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { xmlParseConditionalSections(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else if (RAW == '%') { xmlParsePEReference(ctxt); } else xmlParseMarkupDecl(ctxt); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); break; } } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Leaving INCLUDE Conditional Section\n"); } } else if (CMP6(CUR_PTR, 'I', 'G', 'N', 'O', 'R', 'E')) { int state; xmlParserInputState instate; int depth = 0; SKIP(6); SKIP_BLANKS; if (RAW != '[') { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL); xmlStopParser(ctxt); return; } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } NEXT; } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Entering IGNORE Conditional Section\n"); } /* * Parse up to the end of the conditional section * But disable SAX event generating DTD building in the meantime */ state = ctxt->disableSAX; instate = ctxt->instate; if (ctxt->recovery == 0) ctxt->disableSAX = 1; ctxt->instate = XML_PARSER_IGNORE; while (((depth >= 0) && (RAW != 0)) && (ctxt->instate != XML_PARSER_EOF)) { if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { depth++; SKIP(3); continue; } if ((RAW == ']') && (NXT(1) == ']') && (NXT(2) == '>')) { if (--depth >= 0) SKIP(3); continue; } NEXT; continue; } ctxt->disableSAX = state; ctxt->instate = instate; if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Leaving IGNORE Conditional Section\n"); } } else { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID_KEYWORD, NULL); xmlStopParser(ctxt); return; } if (RAW == 0) SHRINK; if (RAW == 0) { xmlFatalErr(ctxt, XML_ERR_CONDSEC_NOT_FINISHED, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } SKIP(3); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Another variation of overflow in Conditional sections Which happen after the previous fix to https://bugzilla.gnome.org/show_bug.cgi?id=756456 But stopping the parser and exiting we didn't pop the intermediary entities and doing the SKIP there applies on an input which may be too small'</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 EbmlMaster::Read(EbmlStream & inDataStream, const EbmlSemanticContext & sContext, int & UpperEltFound, EbmlElement * & FoundElt, bool AllowDummyElt, ScopeMode ReadFully) { if (ReadFully == SCOPE_NO_DATA) return; EbmlElement * ElementLevelA; // remove all existing elements, including the mandatory ones... size_t Index; for (Index=0; Index<ElementList.size(); Index++) { if (!(*ElementList[Index]).IsLocked()) { delete ElementList[Index]; } } ElementList.clear(); uint64 MaxSizeToRead; if (IsFiniteSize()) MaxSizeToRead = GetSize(); else MaxSizeToRead = 0x7FFFFFFF; // read blocks and discard the ones we don't care about if (MaxSizeToRead > 0) { inDataStream.I_O().setFilePointer(GetSizePosition() + GetSizeLength(), seek_beginning); ElementLevelA = inDataStream.FindNextElement(sContext, UpperEltFound, MaxSizeToRead, AllowDummyElt); while (ElementLevelA != NULL && UpperEltFound <= 0 && MaxSizeToRead > 0) { if (IsFiniteSize() && ElementLevelA->IsFiniteSize()) MaxSizeToRead = GetEndPosition() - ElementLevelA->GetEndPosition(); // even if it's the default value if (!AllowDummyElt && ElementLevelA->IsDummy()) { if (ElementLevelA->IsFiniteSize()) { ElementLevelA->SkipData(inDataStream, sContext); delete ElementLevelA; // forget this unknown element } else { delete ElementLevelA; // forget this unknown element break; } } else { ElementLevelA->Read(inDataStream, EBML_CONTEXT(ElementLevelA), UpperEltFound, FoundElt, AllowDummyElt, ReadFully); // Discard elements that couldn't be read properly if // SCOPE_ALL_DATA has been requested. This can happen // e.g. if block data is defective. bool DeleteElement = true; if (ElementLevelA->ValueIsSet() || (ReadFully != SCOPE_ALL_DATA)) { ElementList.push_back(ElementLevelA); DeleteElement = false; } // just in case if (ElementLevelA->IsFiniteSize()) { ElementLevelA->SkipData(inDataStream, EBML_CONTEXT(ElementLevelA)); if (DeleteElement) delete ElementLevelA; } else { if (DeleteElement) delete ElementLevelA; break; } } if (UpperEltFound > 0) { UpperEltFound--; if (UpperEltFound > 0 || MaxSizeToRead <= 0) goto processCrc; ElementLevelA = FoundElt; continue; } if (UpperEltFound < 0) { UpperEltFound++; if (UpperEltFound < 0) goto processCrc; } if (MaxSizeToRead <= 0) goto processCrc;// this level is finished ElementLevelA = inDataStream.FindNextElement(sContext, UpperEltFound, MaxSizeToRead, AllowDummyElt); } if (UpperEltFound > 0) { FoundElt = ElementLevelA; } } processCrc: EBML_MASTER_ITERATOR Itr, CrcItr; for (Itr = ElementList.begin(); Itr != ElementList.end();) { if ((EbmlId)(*(*Itr)) == EBML_ID(EbmlCrc32)) { bChecksumUsed = true; // remove the element Checksum = *(static_cast<EbmlCrc32*>(*Itr)); CrcItr = Itr; break; } ++Itr; } if (bChecksumUsed) { delete *CrcItr; Remove(CrcItr); } SetValueIsSet(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'EbmlMaster: propagate upper level element after infinite sized one correctly When the parser encountered a deeply nested element with an infinite size then a following element of an upper level was not propagated correctly. Instead the element with the infinite size was added into the EBML element tree a second time resulting in memory access after freeing it and multiple attempts to free the same memory address during destruction. Fixes the issue reported as Cisco TALOS-CAN-0037.'</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 huft_build(const unsigned *b, const unsigned n, const unsigned s, const unsigned short *d, const unsigned char *e, huft_t **t, unsigned *m) { unsigned a; /* counter for codes of length k */ unsigned c[BMAX + 1]; /* bit length count table */ unsigned eob_len; /* length of end-of-block code (value 256) */ unsigned f; /* i repeats in table every f entries */ int g; /* maximum code length */ int htl; /* table level */ unsigned i; /* counter, current code */ unsigned j; /* counter */ int k; /* number of bits in current code */ unsigned *p; /* pointer into c[], b[], or v[] */ huft_t *q; /* points to current table */ huft_t r; /* table entry for structure assignment */ huft_t *u[BMAX]; /* table stack */ unsigned v[N_MAX]; /* values in order of bit length */ int ws[BMAX + 1]; /* bits decoded stack */ int w; /* bits decoded */ unsigned x[BMAX + 1]; /* bit offsets, then code stack */ unsigned *xp; /* pointer into x */ int y; /* number of dummy codes added */ unsigned z; /* number of entries in current table */ /* Length of EOB code, if any */ eob_len = n > 256 ? b[256] : BMAX; *t = NULL; /* Generate counts for each bit length */ memset(c, 0, sizeof(c)); p = (unsigned *) b; /* cast allows us to reuse p for pointing to b */ i = n; do { c[*p]++; /* assume all entries <= BMAX */ p++; /* can't combine with above line (Solaris bug) */ } while (--i); if (c[0] == n) { /* null input - all zero length codes */ *m = 0; return 2; } /* Find minimum and maximum length, bound *m by those */ for (j = 1; (j <= BMAX) && (c[j] == 0); j++) continue; k = j; /* minimum code length */ for (i = BMAX; (c[i] == 0) && i; i--) continue; g = i; /* maximum code length */ *m = (*m < j) ? j : ((*m > i) ? i : *m); /* Adjust last length count to fill out codes, if needed */ for (y = 1 << j; j < i; j++, y <<= 1) { y -= c[j]; if (y < 0) return 2; /* bad input: more codes than bits */ } y -= c[i]; if (y < 0) return 2; c[i] += y; /* Generate starting offsets into the value table for each length */ x[1] = j = 0; p = c + 1; xp = x + 2; while (--i) { /* note that i == g from above */ j += *p++; *xp++ = j; } /* Make a table of values in order of bit lengths */ p = (unsigned *) b; i = 0; do { j = *p++; if (j != 0) { v[x[j]++] = i; } } while (++i < n); /* Generate the Huffman codes and for each, make the table entries */ x[0] = i = 0; /* first Huffman code is zero */ p = v; /* grab values in bit order */ htl = -1; /* no tables yet--level -1 */ w = ws[0] = 0; /* bits decoded */ u[0] = NULL; /* just to keep compilers happy */ q = NULL; /* ditto */ z = 0; /* ditto */ /* go through the bit lengths (k already is bits in shortest code) */ for (; k <= g; k++) { a = c[k]; while (a--) { /* here i is the Huffman code of length k bits for value *p */ /* make tables up to required level */ while (k > ws[htl + 1]) { w = ws[++htl]; /* compute minimum size table less than or equal to *m bits */ z = g - w; z = z > *m ? *m : z; /* upper limit on table size */ j = k - w; f = 1 << j; if (f > a + 1) { /* try a k-w bit table */ /* too few codes for k-w bit table */ f -= a + 1; /* deduct codes from patterns left */ xp = c + k; while (++j < z) { /* try smaller tables up to z bits */ f <<= 1; if (f <= *++xp) { break; /* enough codes to use up j bits */ } f -= *xp; /* else deduct codes from patterns */ } } j = (w + j > eob_len && w < eob_len) ? eob_len - w : j; /* make EOB code end at table */ z = 1 << j; /* table entries for j-bit table */ ws[htl+1] = w + j; /* set bits decoded in stack */ /* allocate and link in new table */ q = xzalloc((z + 1) * sizeof(huft_t)); *t = q + 1; /* link to list for huft_free() */ t = &(q->v.t); u[htl] = ++q; /* table starts after link */ /* connect to last table, if there is one */ if (htl) { x[htl] = i; /* save pattern for backing up */ r.b = (unsigned char) (w - ws[htl - 1]); /* bits to dump before this table */ r.e = (unsigned char) (16 + j); /* bits in this table */ r.v.t = q; /* pointer to this table */ j = (i & ((1 << w) - 1)) >> ws[htl - 1]; u[htl - 1][j] = r; /* connect to last table */ } } /* set up table entry in r */ r.b = (unsigned char) (k - w); if (p >= v + n) { r.e = 99; /* out of values--invalid code */ } else if (*p < s) { r.e = (unsigned char) (*p < 256 ? 16 : 15); /* 256 is EOB code */ r.v.n = (unsigned short) (*p++); /* simple code is just the value */ } else { r.e = (unsigned char) e[*p - s]; /* non-simple--look up in lists */ r.v.n = d[*p++ - s]; } /* fill code-like entries with r */ f = 1 << (k - w); for (j = i >> w; j < z; j += f) { q[j] = r; } /* backwards increment the k-bit code i */ for (j = 1 << (k - 1); i & j; j >>= 1) { i ^= j; } i ^= j; /* backup over finished tables */ while ((i & ((1 << w) - 1)) != x[htl]) { w = ws[--htl]; } } } /* return actual size of base table */ *m = ws[1]; /* Return 1 if we were given an incomplete table */ return y != 0 && g != 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'unzip: test for bad archive SEGVing function old new delta huft_build 1296 1300 +4 Signed-off-by: Denys Vlasenko <[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: xz_decomp(xz_statep state) { int ret; unsigned had; unsigned long crc, len; lzma_stream *strm = &(state->strm); lzma_action action = LZMA_RUN; /* fill output buffer up to end of deflate stream */ had = strm->avail_out; do { /* get more input for inflate() */ if (strm->avail_in == 0 && xz_avail(state) == -1) return -1; if (strm->avail_in == 0) { xz_error(state, LZMA_DATA_ERROR, "unexpected end of file"); return -1; } if (state->eof) action = LZMA_FINISH; /* decompress and handle errors */ #ifdef HAVE_ZLIB_H if (state->how == GZIP) { state->zstrm.avail_in = (uInt) state->strm.avail_in; state->zstrm.next_in = (Bytef *) state->strm.next_in; state->zstrm.avail_out = (uInt) state->strm.avail_out; state->zstrm.next_out = (Bytef *) state->strm.next_out; ret = inflate(&state->zstrm, Z_NO_FLUSH); if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) { xz_error(state, Z_STREAM_ERROR, "internal error: inflate stream corrupt"); return -1; } if (ret == Z_MEM_ERROR) ret = LZMA_MEM_ERROR; if (ret == Z_DATA_ERROR) ret = LZMA_DATA_ERROR; if (ret == Z_STREAM_END) ret = LZMA_STREAM_END; state->strm.avail_in = state->zstrm.avail_in; state->strm.next_in = state->zstrm.next_in; state->strm.avail_out = state->zstrm.avail_out; state->strm.next_out = state->zstrm.next_out; } else /* state->how == LZMA */ #endif ret = lzma_code(strm, action); if (ret == LZMA_MEM_ERROR) { xz_error(state, LZMA_MEM_ERROR, "out of memory"); return -1; } if (ret == LZMA_DATA_ERROR) { xz_error(state, LZMA_DATA_ERROR, "compressed data error"); return -1; } } while (strm->avail_out && ret != LZMA_STREAM_END); /* update available output and crc check value */ state->have = had - strm->avail_out; state->next = strm->next_out - state->have; #ifdef HAVE_ZLIB_H state->zstrm.adler = crc32(state->zstrm.adler, state->next, state->have); #endif if (ret == LZMA_STREAM_END) { #ifdef HAVE_ZLIB_H if (state->how == GZIP) { if (gz_next4(state, &crc) == -1 || gz_next4(state, &len) == -1) { xz_error(state, LZMA_DATA_ERROR, "unexpected end of file"); return -1; } if (crc != state->zstrm.adler) { xz_error(state, LZMA_DATA_ERROR, "incorrect data check"); return -1; } if (len != (state->zstrm.total_out & 0xffffffffL)) { xz_error(state, LZMA_DATA_ERROR, "incorrect length check"); return -1; } state->strm.avail_in = 0; state->strm.next_in = NULL; state->strm.avail_out = 0; state->strm.next_out = NULL; } else #endif if (strm->avail_in != 0 || !state->eof) { xz_error(state, LZMA_DATA_ERROR, "trailing garbage"); return -1; } state->how = LOOK; /* ready for next stream, once have is 0 (leave * state->direct unchanged to remember how) */ } /* good decompression */ return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-8035 Fix XZ compression support loop For https://bugzilla.gnome.org/show_bug.cgi?id=757466 DoS when parsing specially crafted XML document if XZ support is compiled in (which wasn't the case for 2.9.2 and master since Nov 2013, fixed in next commit !)'</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: iakerb_gss_export_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t interprocess_token) { OM_uint32 maj; iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; /* We don't currently support exporting partially established contexts. */ if (!ctx->established) return GSS_S_UNAVAILABLE; maj = krb5_gss_export_sec_context(minor_status, &ctx->gssc, interprocess_token); if (ctx->gssc == GSS_C_NO_CONTEXT) { iakerb_release_context(ctx); *context_handle = GSS_C_NO_CONTEXT; } return maj; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix IAKERB context export/import [CVE-2015-2698] The patches for CVE-2015-2696 contained a regression in the newly added IAKERB iakerb_gss_export_sec_context() function, which could cause it to corrupt memory. Fix the regression by properly dereferencing the context_handle pointer before casting it. Also, the patches did not implement an IAKERB gss_import_sec_context() function, under the erroneous belief that an exported IAKERB context would be tagged as a krb5 context. Implement it now to allow IAKERB contexts to be successfully exported and imported after establishment. CVE-2015-2698: In any MIT krb5 release with the patches for CVE-2015-2696 applied, an application which calls gss_export_sec_context() may experience memory corruption if the context was established using the IAKERB mechanism. Historically, some vulnerabilities of this nature can be translated into remote code execution, though the necessary exploits must be tailored to the individual application and are usually quite complicated. CVSSv2 Vector: AV:N/AC:H/Au:S/C:C/I:C/A:C/E:POC/RL:OF/RC:C ticket: 8273 (new) target_version: 1.14 tags: pullup'</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 ldb_dn_escape_internal(char *dst, const char *src, int len) { const char *p, *s; char *d; size_t l; p = s = src; d = dst; while (p - src < len) { p += strcspn(p, ",=\n\r+<>#;\\\" "); if (p - src == len) /* found no escapable chars */ break; /* copy the part of the string before the stop */ memcpy(d, s, p - s); d += (p - s); /* move to current position */ switch (*p) { case ' ': if (p == src || (p-src)==(len-1)) { /* if at the beginning or end * of the string then escape */ *d++ = '\\'; *d++ = *p++; } else { /* otherwise don't escape */ *d++ = *p++; } break; case '#': /* despite the RFC, windows escapes a # anywhere in the string */ case ',': case '+': case '"': case '\\': case '<': case '>': case '?': /* these must be escaped using \c form */ *d++ = '\\'; *d++ = *p++; break; default: { /* any others get \XX form */ unsigned char v; const char *hexbytes = "0123456789ABCDEF"; v = *(const unsigned char *)p; *d++ = '\\'; *d++ = hexbytes[v>>4]; *d++ = hexbytes[v&0xF]; p++; break; } } s = p; /* move forward */ } /* copy the last part (with zero) and return */ l = len - (s - src); memcpy(d, s, l + 1); /* return the length of the resulting string */ return (l + (d - dst)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2015-5330: ldb_dn: simplify and fix ldb_dn_escape_internal() Previously we relied on NUL terminated strings and jumped back and forth between copying escaped bytes and memcpy()ing un-escaped chunks. This simple version is easier to reason about and works with unterminated strings. It may also be faster as it avoids reading the string twice (first with strcspn, then with memcpy). Bug: https://bugzilla.samba.org/show_bug.cgi?id=11599 Signed-off-by: Douglas Bagnall <[email protected]> Pair-programmed-with: Andrew Bartlett <[email protected]> Reviewed-by: Ralph Boehme <[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 bool ldb_dn_explode(struct ldb_dn *dn) { char *p, *ex_name = NULL, *ex_value = NULL, *data, *d, *dt, *t; bool trim = true; bool in_extended = true; bool in_ex_name = false; bool in_ex_value = false; bool in_attr = false; bool in_value = false; bool in_quote = false; bool is_oid = false; bool escape = false; unsigned int x; size_t l = 0; int ret; char *parse_dn; bool is_index; if ( ! dn || dn->invalid) return false; if (dn->components) { return true; } if (dn->ext_linearized) { parse_dn = dn->ext_linearized; } else { parse_dn = dn->linearized; } if ( ! parse_dn ) { return false; } is_index = (strncmp(parse_dn, "DN=@INDEX:", 10) == 0); /* Empty DNs */ if (parse_dn[0] == '\0') { return true; } /* Special DNs case */ if (dn->special) { return true; } /* make sure we free this if allocated previously before replacing */ LDB_FREE(dn->components); dn->comp_num = 0; LDB_FREE(dn->ext_components); dn->ext_comp_num = 0; /* in the common case we have 3 or more components */ /* make sure all components are zeroed, other functions depend on it */ dn->components = talloc_zero_array(dn, struct ldb_dn_component, 3); if ( ! dn->components) { return false; } /* Components data space is allocated here once */ data = talloc_array(dn->components, char, strlen(parse_dn) + 1); if (!data) { return false; } p = parse_dn; t = NULL; d = dt = data; while (*p) { if (in_extended) { if (!in_ex_name && !in_ex_value) { if (p[0] == '<') { p++; ex_name = d; in_ex_name = true; continue; } else if (p[0] == '\0') { p++; continue; } else { in_extended = false; in_attr = true; dt = d; continue; } } if (in_ex_name && *p == '=') { *d++ = '\0'; p++; ex_value = d; in_ex_name = false; in_ex_value = true; continue; } if (in_ex_value && *p == '>') { const struct ldb_dn_extended_syntax *ext_syntax; struct ldb_val ex_val = { .data = (uint8_t *)ex_value, .length = d - ex_value }; *d++ = '\0'; p++; in_ex_value = false; /* Process name and ex_value */ dn->ext_components = talloc_realloc(dn, dn->ext_components, struct ldb_dn_ext_component, dn->ext_comp_num + 1); if ( ! dn->ext_components) { /* ouch ! */ goto failed; } ext_syntax = ldb_dn_extended_syntax_by_name(dn->ldb, ex_name); if (!ext_syntax) { /* We don't know about this type of extended DN */ goto failed; } dn->ext_components[dn->ext_comp_num].name = talloc_strdup(dn->ext_components, ex_name); if (!dn->ext_components[dn->ext_comp_num].name) { /* ouch */ goto failed; } ret = ext_syntax->read_fn(dn->ldb, dn->ext_components, &ex_val, &dn->ext_components[dn->ext_comp_num].value); if (ret != LDB_SUCCESS) { ldb_dn_mark_invalid(dn); goto failed; } dn->ext_comp_num++; if (*p == '\0') { /* We have reached the end (extended component only)! */ talloc_free(data); return true; } else if (*p == ';') { p++; continue; } else { ldb_dn_mark_invalid(dn); goto failed; } } *d++ = *p++; continue; } if (in_attr) { if (trim) { if (*p == ' ') { p++; continue; } /* first char */ trim = false; if (!isascii(*p)) { /* attr names must be ascii only */ ldb_dn_mark_invalid(dn); goto failed; } if (isdigit(*p)) { is_oid = true; } else if ( ! isalpha(*p)) { /* not a digit nor an alpha, * invalid attribute name */ ldb_dn_mark_invalid(dn); goto failed; } /* Copy this character across from parse_dn, * now we have trimmed out spaces */ *d++ = *p++; continue; } if (*p == ' ') { p++; /* valid only if we are at the end */ trim = true; continue; } if (trim && (*p != '=')) { /* spaces/tabs are not allowed */ ldb_dn_mark_invalid(dn); goto failed; } if (*p == '=') { /* attribute terminated */ in_attr = false; in_value = true; trim = true; l = 0; /* Terminate this string in d * (which is a copy of parse_dn * with spaces trimmed) */ *d++ = '\0'; dn->components[dn->comp_num].name = talloc_strdup(dn->components, dt); if ( ! dn->components[dn->comp_num].name) { /* ouch */ goto failed; } dt = d; p++; continue; } if (!isascii(*p)) { /* attr names must be ascii only */ ldb_dn_mark_invalid(dn); goto failed; } if (is_oid && ( ! (isdigit(*p) || (*p == '.')))) { /* not a digit nor a dot, * invalid attribute oid */ ldb_dn_mark_invalid(dn); goto failed; } else if ( ! (isalpha(*p) || isdigit(*p) || (*p == '-'))) { /* not ALPHA, DIGIT or HYPHEN */ ldb_dn_mark_invalid(dn); goto failed; } *d++ = *p++; continue; } if (in_value) { if (in_quote) { if (*p == '\"') { if (p[-1] != '\\') { p++; in_quote = false; continue; } } *d++ = *p++; l++; continue; } if (trim) { if (*p == ' ') { p++; continue; } /* first char */ trim = false; if (*p == '\"') { in_quote = true; p++; continue; } } switch (*p) { /* TODO: support ber encoded values case '#': */ case ',': if (escape) { *d++ = *p++; l++; escape = false; continue; } /* ok found value terminator */ if ( t ) { /* trim back */ d -= (p - t); l -= (p - t); } in_attr = true; in_value = false; trim = true; p++; *d++ = '\0'; dn->components[dn->comp_num].value.data = (uint8_t *)talloc_strdup(dn->components, dt); dn->components[dn->comp_num].value.length = l; if ( ! dn->components[dn->comp_num].value.data) { /* ouch ! */ goto failed; } dt = d; dn->comp_num++; if (dn->comp_num > 2) { dn->components = talloc_realloc(dn, dn->components, struct ldb_dn_component, dn->comp_num + 1); if ( ! dn->components) { /* ouch ! */ goto failed; } /* make sure all components are zeroed, other functions depend on this */ memset(&dn->components[dn->comp_num], '\0', sizeof(struct ldb_dn_component)); } continue; case '+': case '=': /* to main compatibility with earlier versions of ldb indexing, we have to accept the base64 encoded binary index values, which contain a '+' or '=' which should normally be escaped */ if (is_index) { if ( t ) t = NULL; *d++ = *p++; l++; break; } /* fall through */ case '\"': case '<': case '>': case ';': /* a string with not escaped specials is invalid (tested) */ if ( ! escape) { ldb_dn_mark_invalid(dn); goto failed; } escape = false; *d++ = *p++; l++; if ( t ) t = NULL; break; case '\\': if ( ! escape) { escape = true; p++; continue; } escape = false; *d++ = *p++; l++; if ( t ) t = NULL; break; default: if (escape) { if (isxdigit(p[0]) && isxdigit(p[1])) { if (sscanf(p, "%02x", &x) != 1) { /* invalid escaping sequence */ ldb_dn_mark_invalid(dn); goto failed; } p += 2; *d++ = (unsigned char)x; } else { *d++ = *p++; } escape = false; l++; if ( t ) t = NULL; break; } if (*p == ' ') { if ( ! t) t = p; } else { if ( t ) t = NULL; } *d++ = *p++; l++; break; } } } if (in_attr || in_quote) { /* invalid dn */ ldb_dn_mark_invalid(dn); goto failed; } /* save last element */ if ( t ) { /* trim back */ d -= (p - t); l -= (p - t); } *d++ = '\0'; dn->components[dn->comp_num].value.length = l; dn->components[dn->comp_num].value.data = (uint8_t *)talloc_strdup(dn->components, dt); if ( ! dn->components[dn->comp_num].value.data) { /* ouch */ goto failed; } dn->comp_num++; talloc_free(data); return true; failed: LDB_FREE(dn->components); /* "data" is implicitly free'd */ dn->comp_num = 0; LDB_FREE(dn->ext_components); dn->ext_comp_num = 0; return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2015-5330: ldb_dn_explode: copy strings by length, not terminators That is, memdup(), not strdup(). The terminators might not be there. But, we have to make sure we put the terminator on, because we tend to assume the terminator is there in other places. Use talloc_set_name_const() on the resulting chunk so talloc_report() remains unchanged. Bug: https://bugzilla.samba.org/show_bug.cgi?id=11599 Signed-off-by: Douglas Bagnall <[email protected]> Pair-programmed-with: Andrew Bartlett <[email protected]> Pair-programmed-with: Garming Sam <[email protected]> Pair-programmed-with: Stefan Metzmacher <[email protected]> Pair-programmed-with: Ralph Boehme <[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: _PUBLIC_ size_t strlen_m_ext_handle(struct smb_iconv_handle *ic, const char *s, charset_t src_charset, charset_t dst_charset) { size_t count = 0; #ifdef DEVELOPER switch (dst_charset) { case CH_DOS: case CH_UNIX: smb_panic("cannot call strlen_m_ext() with a variable dest charset (must be UTF16* or UTF8)"); default: break; } switch (src_charset) { case CH_UTF16LE: case CH_UTF16BE: smb_panic("cannot call strlen_m_ext() with a UTF16 src charset (must be DOS, UNIX, DISPLAY or UTF8)"); default: break; } #endif if (!s) { return 0; } while (*s && !(((uint8_t)*s) & 0x80)) { s++; count++; } if (!*s) { return count; } while (*s) { size_t c_size; codepoint_t c = next_codepoint_handle_ext(ic, s, src_charset, &c_size); s += c_size; switch (dst_charset) { case CH_UTF16LE: case CH_UTF16BE: case CH_UTF16MUNGED: if (c < 0x10000) { /* Unicode char fits into 16 bits. */ count += 1; } else { /* Double-width unicode char - 32 bits. */ count += 2; } break; case CH_UTF8: /* * this only checks ranges, and does not * check for invalid codepoints */ if (c < 0x80) { count += 1; } else if (c < 0x800) { count += 2; } else if (c < 0x10000) { count += 3; } else { count += 4; } break; default: /* * non-unicode encoding: * assume that each codepoint fits into * one unit in the destination encoding. */ count += 1; } } return count; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2015-5330: Fix handling of unicode near string endings Until now next_codepoint_ext() and next_codepoint_handle_ext() were using strnlen(str, 5) to determine how much string they should try to decode. This ended up looking past the end of the string when it was not null terminated and the final character looked like a multi-byte encoding. The fix is to let the caller say how long the string can be. Bug: https://bugzilla.samba.org/show_bug.cgi?id=11599 Signed-off-by: Douglas Bagnall <[email protected]> Pair-programmed-with: Andrew Bartlett <[email protected]> Reviewed-by: Ralph Boehme <[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: _PUBLIC_ codepoint_t next_codepoint_handle_ext( struct smb_iconv_handle *ic, const char *str, charset_t src_charset, size_t *bytes_consumed) { /* it cannot occupy more than 4 bytes in UTF16 format */ uint8_t buf[4]; smb_iconv_t descriptor; size_t ilen_orig; size_t ilen; size_t olen; char *outbuf; if ((str[0] & 0x80) == 0) { *bytes_consumed = 1; return (codepoint_t)str[0]; } /* * we assume that no multi-byte character can take more than 5 bytes. * This is OK as we only support codepoints up to 1M (U+100000) */ ilen_orig = strnlen(str, 5); ilen = ilen_orig; descriptor = get_conv_handle(ic, src_charset, CH_UTF16); if (descriptor == (smb_iconv_t)-1) { *bytes_consumed = 1; return INVALID_CODEPOINT; } /* * this looks a little strange, but it is needed to cope with * codepoints above 64k (U+1000) which are encoded as per RFC2781. */ olen = 2; outbuf = (char *)buf; smb_iconv(descriptor, &str, &ilen, &outbuf, &olen); if (olen == 2) { olen = 4; outbuf = (char *)buf; smb_iconv(descriptor, &str, &ilen, &outbuf, &olen); if (olen == 4) { /* we didn't convert any bytes */ *bytes_consumed = 1; return INVALID_CODEPOINT; } olen = 4 - olen; } else { olen = 2 - olen; } *bytes_consumed = ilen_orig - ilen; if (olen == 2) { return (codepoint_t)SVAL(buf, 0); } if (olen == 4) { /* decode a 4 byte UTF16 character manually */ return (codepoint_t)0x10000 + (buf[2] | ((buf[3] & 0x3)<<8) | (buf[0]<<10) | ((buf[1] & 0x3)<<18)); } /* no other length is valid */ return INVALID_CODEPOINT; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2015-5330: Fix handling of unicode near string endings Until now next_codepoint_ext() and next_codepoint_handle_ext() were using strnlen(str, 5) to determine how much string they should try to decode. This ended up looking past the end of the string when it was not null terminated and the final character looked like a multi-byte encoding. The fix is to let the caller say how long the string can be. Bug: https://bugzilla.samba.org/show_bug.cgi?id=11599 Signed-off-by: Douglas Bagnall <[email protected]> Pair-programmed-with: Andrew Bartlett <[email protected]> Reviewed-by: Ralph Boehme <[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: _PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle, TALLOC_CTX *ctx, const char *src, size_t n) { size_t size=0; char *dest; if (!src) { return NULL; } /* this takes advantage of the fact that upper/lower can't change the length of a character by more than 1 byte */ dest = talloc_array(ctx, char, 2*(n+1)); if (dest == NULL) { return NULL; } while (n-- && *src) { size_t c_size; codepoint_t c = next_codepoint_handle_ext(iconv_handle, src, n, CH_UNIX, &c_size); src += c_size; c = toupper_m(c); c_size = push_codepoint_handle(iconv_handle, dest+size, c); if (c_size == -1) { talloc_free(dest); return NULL; } size += c_size; } dest[size] = 0; /* trim it so talloc_append_string() works */ dest = talloc_realloc(ctx, dest, char, size+1); talloc_set_name_const(dest, dest); return dest; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2015-5330: strupper_talloc_n_handle(): properly count characters When a codepoint eats more than one byte we really want to know, especially if the string is not NUL terminated. Bug: https://bugzilla.samba.org/show_bug.cgi?id=11599 Signed-off-by: Douglas Bagnall <[email protected]> Pair-programmed-with: Andrew Bartlett <[email protected]> Reviewed-by: Ralph Boehme <[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: png_write_info(png_structrp png_ptr, png_const_inforp info_ptr) { #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED) int i; #endif png_debug(1, "in png_write_info"); if (png_ptr == NULL || info_ptr == NULL) return; png_write_info_before_PLTE(png_ptr, info_ptr); if ((info_ptr->valid & PNG_INFO_PLTE) != 0) png_write_PLTE(png_ptr, info_ptr->palette, (png_uint_32)info_ptr->num_palette); else if ((info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) !=0) png_error(png_ptr, "Valid palette required for paletted images"); #ifdef PNG_WRITE_tRNS_SUPPORTED if ((info_ptr->valid & PNG_INFO_tRNS) !=0) { #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED /* Invert the alpha channel (in tRNS) */ if ((png_ptr->transformations & PNG_INVERT_ALPHA) != 0 && info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { int j, jend; jend = info_ptr->num_trans; if (jend > PNG_MAX_PALETTE_LENGTH) jend = PNG_MAX_PALETTE_LENGTH; for (j = 0; j<jend; ++j) info_ptr->trans_alpha[j] = (png_byte)(255 - info_ptr->trans_alpha[j]); } #endif png_write_tRNS(png_ptr, info_ptr->trans_alpha, &(info_ptr->trans_color), info_ptr->num_trans, info_ptr->color_type); } #endif #ifdef PNG_WRITE_bKGD_SUPPORTED if ((info_ptr->valid & PNG_INFO_bKGD) != 0) png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type); #endif #ifdef PNG_WRITE_hIST_SUPPORTED if ((info_ptr->valid & PNG_INFO_hIST) != 0) png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette); #endif #ifdef PNG_WRITE_oFFs_SUPPORTED if ((info_ptr->valid & PNG_INFO_oFFs) != 0) png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset, info_ptr->offset_unit_type); #endif #ifdef PNG_WRITE_pCAL_SUPPORTED if ((info_ptr->valid & PNG_INFO_pCAL) != 0) png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0, info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams, info_ptr->pcal_units, info_ptr->pcal_params); #endif #ifdef PNG_WRITE_sCAL_SUPPORTED if ((info_ptr->valid & PNG_INFO_sCAL) != 0) png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit, info_ptr->scal_s_width, info_ptr->scal_s_height); #endif /* sCAL */ #ifdef PNG_WRITE_pHYs_SUPPORTED if ((info_ptr->valid & PNG_INFO_pHYs) != 0) png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit, info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type); #endif /* pHYs */ #ifdef PNG_WRITE_tIME_SUPPORTED if ((info_ptr->valid & PNG_INFO_tIME) != 0) { png_write_tIME(png_ptr, &(info_ptr->mod_time)); png_ptr->mode |= PNG_WROTE_tIME; } #endif /* tIME */ #ifdef PNG_WRITE_sPLT_SUPPORTED if ((info_ptr->valid & PNG_INFO_sPLT) != 0) for (i = 0; i < (int)info_ptr->splt_palettes_num; i++) png_write_sPLT(png_ptr, info_ptr->splt_palettes + i); #endif /* sPLT */ #ifdef PNG_WRITE_TEXT_SUPPORTED /* Check to see if we need to write text chunks */ for (i = 0; i < info_ptr->num_text; i++) { png_debug2(2, "Writing header text chunk %d, type %d", i, info_ptr->text[i].compression); /* An internationalized chunk? */ if (info_ptr->text[i].compression > 0) { #ifdef PNG_WRITE_iTXt_SUPPORTED /* Write international chunk */ png_write_iTXt(png_ptr, info_ptr->text[i].compression, info_ptr->text[i].key, info_ptr->text[i].lang, info_ptr->text[i].lang_key, info_ptr->text[i].text); /* Mark this chunk as written */ if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE) info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR; else info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR; #else png_warning(png_ptr, "Unable to write international text"); #endif } /* If we want a compressed text chunk */ else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt) { #ifdef PNG_WRITE_zTXt_SUPPORTED /* Write compressed chunk */ png_write_zTXt(png_ptr, info_ptr->text[i].key, info_ptr->text[i].text, info_ptr->text[i].compression); /* Mark this chunk as written */ info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR; #else png_warning(png_ptr, "Unable to write compressed text"); #endif } else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE) { #ifdef PNG_WRITE_tEXt_SUPPORTED /* Write uncompressed chunk */ png_write_tEXt(png_ptr, info_ptr->text[i].key, info_ptr->text[i].text, 0); /* Mark this chunk as written */ info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR; #else /* Can't get here */ png_warning(png_ptr, "Unable to write uncompressed text"); #endif } } #endif /* tEXt */ #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_PLTE); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': '[libpng16] Reject attempt to write over-length PLTE chunk'</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: png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_color palette[PNG_MAX_PALETTE_LENGTH]; int num, i; #ifdef PNG_POINTER_INDEXING_SUPPORTED png_colorp pal_ptr; #endif png_debug(1, "in png_handle_PLTE"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); /* Moved to before the 'after IDAT' check below because otherwise duplicate * PLTE chunks are potentially ignored (the spec says there shall not be more * than one PLTE, the error is not treated as benign, so this check trumps * the requirement that PLTE appears before IDAT.) */ else if ((png_ptr->mode & PNG_HAVE_PLTE) != 0) png_chunk_error(png_ptr, "duplicate"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { /* This is benign because the non-benign error happened before, when an * IDAT was encountered in a color-mapped image with no PLTE. */ png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } png_ptr->mode |= PNG_HAVE_PLTE; if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "ignored in grayscale PNG"); return; } #ifndef PNG_READ_OPT_PLTE_SUPPORTED if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE) { png_crc_finish(png_ptr, length); return; } #endif if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3) { png_crc_finish(png_ptr, length); if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE) png_chunk_benign_error(png_ptr, "invalid"); else png_chunk_error(png_ptr, "invalid"); return; } /* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */ num = (int)length / 3; #ifdef PNG_POINTER_INDEXING_SUPPORTED for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++) { png_byte buf[3]; png_crc_read(png_ptr, buf, 3); pal_ptr->red = buf[0]; pal_ptr->green = buf[1]; pal_ptr->blue = buf[2]; } #else for (i = 0; i < num; i++) { png_byte buf[3]; png_crc_read(png_ptr, buf, 3); /* Don't depend upon png_color being any order */ palette[i].red = buf[0]; palette[i].green = buf[1]; palette[i].blue = buf[2]; } #endif /* If we actually need the PLTE chunk (ie for a paletted image), we do * whatever the normal CRC configuration tells us. However, if we * have an RGB image, the PLTE can be considered ancillary, so * we will act as though it is. */ #ifndef PNG_READ_OPT_PLTE_SUPPORTED if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) #endif { png_crc_finish(png_ptr, 0); } #ifndef PNG_READ_OPT_PLTE_SUPPORTED else if (png_crc_error(png_ptr) != 0) /* Only if we have a CRC error */ { /* If we don't want to use the data from an ancillary chunk, * we have two options: an error abort, or a warning and we * ignore the data in this chunk (which should be OK, since * it's considered ancillary for a RGB or RGBA image). * * IMPLEMENTATION NOTE: this is only here because png_crc_finish uses the * chunk type to determine whether to check the ancillary or the critical * flags. */ if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE) == 0) { if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) != 0) return; else png_chunk_error(png_ptr, "CRC error"); } /* Otherwise, we (optionally) emit a warning and use the chunk. */ else if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0) png_chunk_warning(png_ptr, "CRC error"); } #endif /* TODO: png_set_PLTE has the side effect of setting png_ptr->palette to its * own copy of the palette. This has the side effect that when png_start_row * is called (this happens after any call to png_read_update_info) the * info_ptr palette gets changed. This is extremely unexpected and * confusing. * * Fix this by not sharing the palette in this way. */ png_set_PLTE(png_ptr, info_ptr, palette, num); /* The three chunks, bKGD, hIST and tRNS *must* appear after PLTE and before * IDAT. Prior to 1.6.0 this was not checked; instead the code merely * checked the apparent validity of a tRNS chunk inserted before PLTE on a * palette PNG. 1.6.0 attempts to rigorously follow the standard and * therefore does a benign error if the erroneous condition is detected *and* * cancels the tRNS if the benign error returns. The alternative is to * amend the standard since it would be rather hypocritical of the standards * maintainers to ignore it. */ #ifdef PNG_READ_tRNS_SUPPORTED if (png_ptr->num_trans > 0 || (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0)) { /* Cancel this because otherwise it would be used if the transforms * require it. Don't cancel the 'valid' flag because this would prevent * detection of duplicate chunks. */ png_ptr->num_trans = 0; if (info_ptr != NULL) info_ptr->num_trans = 0; png_chunk_benign_error(png_ptr, "tRNS must be after"); } #endif #ifdef PNG_READ_hIST_SUPPORTED if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0) png_chunk_benign_error(png_ptr, "hIST must be after"); #endif #ifdef PNG_READ_bKGD_SUPPORTED if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0) png_chunk_benign_error(png_ptr, "bKGD must be after"); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': '[libpng16] Prevent reading over-length PLTE chunk (Cosmin Truta).'</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: png_set_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_const_colorp palette, int num_palette) { png_debug1(1, "in %s storage function", "PLTE"); if (png_ptr == NULL || info_ptr == NULL) return; if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH) { if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) png_error(png_ptr, "Invalid palette length"); else { png_warning(png_ptr, "Invalid palette length"); return; } } if ((num_palette > 0 && palette == NULL) || (num_palette == 0 # ifdef PNG_MNG_FEATURES_SUPPORTED && (png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0 # endif )) { png_error(png_ptr, "Invalid palette"); } /* It may not actually be necessary to set png_ptr->palette here; * we do it for backward compatibility with the way the png_handle_tRNS * function used to do the allocation. * * 1.6.0: the above statement appears to be incorrect; something has to set * the palette inside png_struct on read. */ png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0); /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead * of num_palette entries, in case of an invalid PNG file that has * too-large sample values. */ png_ptr->palette = png_voidcast(png_colorp, png_calloc(png_ptr, PNG_MAX_PALETTE_LENGTH * (sizeof (png_color)))); if (num_palette > 0) memcpy(png_ptr->palette, palette, num_palette * (sizeof (png_color))); info_ptr->palette = png_ptr->palette; info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette; info_ptr->free_me |= PNG_FREE_PLTE; info_ptr->valid |= PNG_INFO_PLTE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': '[libpng16] Prevent reading over-length PLTE chunk (Cosmin Truta).'</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: png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_color palette[PNG_MAX_PALETTE_LENGTH]; int num, i; #ifdef PNG_POINTER_INDEXING_SUPPORTED png_colorp pal_ptr; #endif png_debug(1, "in png_handle_PLTE"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); /* Moved to before the 'after IDAT' check below because otherwise duplicate * PLTE chunks are potentially ignored (the spec says there shall not be more * than one PLTE, the error is not treated as benign, so this check trumps * the requirement that PLTE appears before IDAT.) */ else if ((png_ptr->mode & PNG_HAVE_PLTE) != 0) png_chunk_error(png_ptr, "duplicate"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { /* This is benign because the non-benign error happened before, when an * IDAT was encountered in a color-mapped image with no PLTE. */ png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } png_ptr->mode |= PNG_HAVE_PLTE; if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "ignored in grayscale PNG"); return; } #ifndef PNG_READ_OPT_PLTE_SUPPORTED if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE) { png_crc_finish(png_ptr, length); return; } #endif if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3) { png_crc_finish(png_ptr, length); if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE) png_chunk_benign_error(png_ptr, "invalid"); else png_chunk_error(png_ptr, "invalid"); return; } /* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */ num = (int)length / 3; #ifdef PNG_POINTER_INDEXING_SUPPORTED for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++) { png_byte buf[3]; png_crc_read(png_ptr, buf, 3); pal_ptr->red = buf[0]; pal_ptr->green = buf[1]; pal_ptr->blue = buf[2]; } #else for (i = 0; i < num; i++) { png_byte buf[3]; png_crc_read(png_ptr, buf, 3); /* Don't depend upon png_color being any order */ palette[i].red = buf[0]; palette[i].green = buf[1]; palette[i].blue = buf[2]; } #endif /* If we actually need the PLTE chunk (ie for a paletted image), we do * whatever the normal CRC configuration tells us. However, if we * have an RGB image, the PLTE can be considered ancillary, so * we will act as though it is. */ #ifndef PNG_READ_OPT_PLTE_SUPPORTED if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) #endif { png_crc_finish(png_ptr, 0); } #ifndef PNG_READ_OPT_PLTE_SUPPORTED else if (png_crc_error(png_ptr) != 0) /* Only if we have a CRC error */ { /* If we don't want to use the data from an ancillary chunk, * we have two options: an error abort, or a warning and we * ignore the data in this chunk (which should be OK, since * it's considered ancillary for a RGB or RGBA image). * * IMPLEMENTATION NOTE: this is only here because png_crc_finish uses the * chunk type to determine whether to check the ancillary or the critical * flags. */ if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE) == 0) { if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) != 0) return; else png_chunk_error(png_ptr, "CRC error"); } /* Otherwise, we (optionally) emit a warning and use the chunk. */ else if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0) png_chunk_warning(png_ptr, "CRC error"); } #endif /* TODO: png_set_PLTE has the side effect of setting png_ptr->palette to its * own copy of the palette. This has the side effect that when png_start_row * is called (this happens after any call to png_read_update_info) the * info_ptr palette gets changed. This is extremely unexpected and * confusing. * * Fix this by not sharing the palette in this way. * * Starting with libpng-1.6.19, png_set_PLTE() also issues a png_error() when * it attempts to set a palette length that is too large for the bit depth. */ png_set_PLTE(png_ptr, info_ptr, palette, num); /* The three chunks, bKGD, hIST and tRNS *must* appear after PLTE and before * IDAT. Prior to 1.6.0 this was not checked; instead the code merely * checked the apparent validity of a tRNS chunk inserted before PLTE on a * palette PNG. 1.6.0 attempts to rigorously follow the standard and * therefore does a benign error if the erroneous condition is detected *and* * cancels the tRNS if the benign error returns. The alternative is to * amend the standard since it would be rather hypocritical of the standards * maintainers to ignore it. */ #ifdef PNG_READ_tRNS_SUPPORTED if (png_ptr->num_trans > 0 || (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0)) { /* Cancel this because otherwise it would be used if the transforms * require it. Don't cancel the 'valid' flag because this would prevent * detection of duplicate chunks. */ png_ptr->num_trans = 0; if (info_ptr != NULL) info_ptr->num_trans = 0; png_chunk_benign_error(png_ptr, "tRNS must be after"); } #endif #ifdef PNG_READ_hIST_SUPPORTED if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0) png_chunk_benign_error(png_ptr, "hIST must be after"); #endif #ifdef PNG_READ_bKGD_SUPPORTED if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0) png_chunk_benign_error(png_ptr, "bKGD must be after"); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': '[libpng16] Silently truncate over-length PLTE chunk while 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: png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_color palette[PNG_MAX_PALETTE_LENGTH]; int max_palette_length, num, i; #ifdef PNG_POINTER_INDEXING_SUPPORTED png_colorp pal_ptr; #endif png_debug(1, "in png_handle_PLTE"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); /* Moved to before the 'after IDAT' check below because otherwise duplicate * PLTE chunks are potentially ignored (the spec says there shall not be more * than one PLTE, the error is not treated as benign, so this check trumps * the requirement that PLTE appears before IDAT.) */ else if ((png_ptr->mode & PNG_HAVE_PLTE) != 0) png_chunk_error(png_ptr, "duplicate"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { /* This is benign because the non-benign error happened before, when an * IDAT was encountered in a color-mapped image with no PLTE. */ png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } png_ptr->mode |= PNG_HAVE_PLTE; if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "ignored in grayscale PNG"); return; } #ifndef PNG_READ_OPT_PLTE_SUPPORTED if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE) { png_crc_finish(png_ptr, length); return; } #endif if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3) { png_crc_finish(png_ptr, length); if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE) png_chunk_benign_error(png_ptr, "invalid"); else png_chunk_error(png_ptr, "invalid"); return; } max_palette_length = (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ? (1 << png_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH; /* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */ num = (int)length / 3; /* If the palette has 256 or fewer entries but is too large for the bit depth, * we don't issue an error, to preserve the behavior of previous libpng versions. * We silently truncate the unused extra palette entries here. */ if (num > max_palette_length) num = max_palette_length; #ifdef PNG_POINTER_INDEXING_SUPPORTED for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++) { png_byte buf[3]; png_crc_read(png_ptr, buf, 3); pal_ptr->red = buf[0]; pal_ptr->green = buf[1]; pal_ptr->blue = buf[2]; } #else for (i = 0; i < num; i++) { png_byte buf[3]; png_crc_read(png_ptr, buf, 3); /* Don't depend upon png_color being any order */ palette[i].red = buf[0]; palette[i].green = buf[1]; palette[i].blue = buf[2]; } #endif /* If we actually need the PLTE chunk (ie for a paletted image), we do * whatever the normal CRC configuration tells us. However, if we * have an RGB image, the PLTE can be considered ancillary, so * we will act as though it is. */ #ifndef PNG_READ_OPT_PLTE_SUPPORTED if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) #endif { png_crc_finish(png_ptr, 0); } #ifndef PNG_READ_OPT_PLTE_SUPPORTED else if (png_crc_error(png_ptr) != 0) /* Only if we have a CRC error */ { /* If we don't want to use the data from an ancillary chunk, * we have two options: an error abort, or a warning and we * ignore the data in this chunk (which should be OK, since * it's considered ancillary for a RGB or RGBA image). * * IMPLEMENTATION NOTE: this is only here because png_crc_finish uses the * chunk type to determine whether to check the ancillary or the critical * flags. */ if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE) == 0) { if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) != 0) return; else png_chunk_error(png_ptr, "CRC error"); } /* Otherwise, we (optionally) emit a warning and use the chunk. */ else if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0) png_chunk_warning(png_ptr, "CRC error"); } #endif /* TODO: png_set_PLTE has the side effect of setting png_ptr->palette to its * own copy of the palette. This has the side effect that when png_start_row * is called (this happens after any call to png_read_update_info) the * info_ptr palette gets changed. This is extremely unexpected and * confusing. * * Fix this by not sharing the palette in this way. */ png_set_PLTE(png_ptr, info_ptr, palette, num); /* The three chunks, bKGD, hIST and tRNS *must* appear after PLTE and before * IDAT. Prior to 1.6.0 this was not checked; instead the code merely * checked the apparent validity of a tRNS chunk inserted before PLTE on a * palette PNG. 1.6.0 attempts to rigorously follow the standard and * therefore does a benign error if the erroneous condition is detected *and* * cancels the tRNS if the benign error returns. The alternative is to * amend the standard since it would be rather hypocritical of the standards * maintainers to ignore it. */ #ifdef PNG_READ_tRNS_SUPPORTED if (png_ptr->num_trans > 0 || (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0)) { /* Cancel this because otherwise it would be used if the transforms * require it. Don't cancel the 'valid' flag because this would prevent * detection of duplicate chunks. */ png_ptr->num_trans = 0; if (info_ptr != NULL) info_ptr->num_trans = 0; png_chunk_benign_error(png_ptr, "tRNS must be after"); } #endif #ifdef PNG_READ_hIST_SUPPORTED if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0) png_chunk_benign_error(png_ptr, "hIST must be after"); #endif #ifdef PNG_READ_bKGD_SUPPORTED if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0) png_chunk_benign_error(png_ptr, "bKGD must be after"); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': '[libpng16] Fixed new bug with CRC error after reading an over-length palette.'</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: xmlSwitchEncoding(xmlParserCtxtPtr ctxt, xmlCharEncoding enc) { xmlCharEncodingHandlerPtr handler; int len = -1; if (ctxt == NULL) return(-1); switch (enc) { case XML_CHAR_ENCODING_ERROR: __xmlErrEncoding(ctxt, XML_ERR_UNKNOWN_ENCODING, "encoding unknown\n", NULL, NULL); return(-1); case XML_CHAR_ENCODING_NONE: /* let's assume it's UTF-8 without the XML decl */ ctxt->charset = XML_CHAR_ENCODING_UTF8; return(0); case XML_CHAR_ENCODING_UTF8: /* default encoding, no conversion should be needed */ ctxt->charset = XML_CHAR_ENCODING_UTF8; /* * Errata on XML-1.0 June 20 2001 * Specific handling of the Byte Order Mark for * UTF-8 */ if ((ctxt->input != NULL) && (ctxt->input->cur[0] == 0xEF) && (ctxt->input->cur[1] == 0xBB) && (ctxt->input->cur[2] == 0xBF)) { ctxt->input->cur += 3; } return(0); case XML_CHAR_ENCODING_UTF16LE: case XML_CHAR_ENCODING_UTF16BE: /*The raw input characters are encoded *in UTF-16. As we expect this function *to be called after xmlCharEncInFunc, we expect *ctxt->input->cur to contain UTF-8 encoded characters. *So the raw UTF16 Byte Order Mark *has also been converted into *an UTF-8 BOM. Let's skip that BOM. */ if ((ctxt->input != NULL) && (ctxt->input->cur != NULL) && (ctxt->input->cur[0] == 0xEF) && (ctxt->input->cur[1] == 0xBB) && (ctxt->input->cur[2] == 0xBF)) { ctxt->input->cur += 3; } len = 90; break; case XML_CHAR_ENCODING_UCS2: len = 90; break; case XML_CHAR_ENCODING_UCS4BE: case XML_CHAR_ENCODING_UCS4LE: case XML_CHAR_ENCODING_UCS4_2143: case XML_CHAR_ENCODING_UCS4_3412: len = 180; break; case XML_CHAR_ENCODING_EBCDIC: case XML_CHAR_ENCODING_8859_1: case XML_CHAR_ENCODING_8859_2: case XML_CHAR_ENCODING_8859_3: case XML_CHAR_ENCODING_8859_4: case XML_CHAR_ENCODING_8859_5: case XML_CHAR_ENCODING_8859_6: case XML_CHAR_ENCODING_8859_7: case XML_CHAR_ENCODING_8859_8: case XML_CHAR_ENCODING_8859_9: case XML_CHAR_ENCODING_ASCII: case XML_CHAR_ENCODING_2022_JP: case XML_CHAR_ENCODING_SHIFT_JIS: case XML_CHAR_ENCODING_EUC_JP: len = 45; break; } handler = xmlGetCharEncodingHandler(enc); if (handler == NULL) { /* * Default handlers. */ switch (enc) { case XML_CHAR_ENCODING_ASCII: /* default encoding, no conversion should be needed */ ctxt->charset = XML_CHAR_ENCODING_UTF8; return(0); case XML_CHAR_ENCODING_UTF16LE: break; case XML_CHAR_ENCODING_UTF16BE: break; case XML_CHAR_ENCODING_UCS4LE: __xmlErrEncoding(ctxt, XML_ERR_UNSUPPORTED_ENCODING, "encoding not supported %s\n", BAD_CAST "USC4 little endian", NULL); break; case XML_CHAR_ENCODING_UCS4BE: __xmlErrEncoding(ctxt, XML_ERR_UNSUPPORTED_ENCODING, "encoding not supported %s\n", BAD_CAST "USC4 big endian", NULL); break; case XML_CHAR_ENCODING_EBCDIC: __xmlErrEncoding(ctxt, XML_ERR_UNSUPPORTED_ENCODING, "encoding not supported %s\n", BAD_CAST "EBCDIC", NULL); break; case XML_CHAR_ENCODING_UCS4_2143: __xmlErrEncoding(ctxt, XML_ERR_UNSUPPORTED_ENCODING, "encoding not supported %s\n", BAD_CAST "UCS4 2143", NULL); break; case XML_CHAR_ENCODING_UCS4_3412: __xmlErrEncoding(ctxt, XML_ERR_UNSUPPORTED_ENCODING, "encoding not supported %s\n", BAD_CAST "UCS4 3412", NULL); break; case XML_CHAR_ENCODING_UCS2: __xmlErrEncoding(ctxt, XML_ERR_UNSUPPORTED_ENCODING, "encoding not supported %s\n", BAD_CAST "UCS2", NULL); break; case XML_CHAR_ENCODING_8859_1: case XML_CHAR_ENCODING_8859_2: case XML_CHAR_ENCODING_8859_3: case XML_CHAR_ENCODING_8859_4: case XML_CHAR_ENCODING_8859_5: case XML_CHAR_ENCODING_8859_6: case XML_CHAR_ENCODING_8859_7: case XML_CHAR_ENCODING_8859_8: case XML_CHAR_ENCODING_8859_9: /* * We used to keep the internal content in the * document encoding however this turns being unmaintainable * So xmlGetCharEncodingHandler() will return non-null * values for this now. */ if ((ctxt->inputNr == 1) && (ctxt->encoding == NULL) && (ctxt->input != NULL) && (ctxt->input->encoding != NULL)) { ctxt->encoding = xmlStrdup(ctxt->input->encoding); } ctxt->charset = enc; return(0); case XML_CHAR_ENCODING_2022_JP: __xmlErrEncoding(ctxt, XML_ERR_UNSUPPORTED_ENCODING, "encoding not supported %s\n", BAD_CAST "ISO-2022-JP", NULL); break; case XML_CHAR_ENCODING_SHIFT_JIS: __xmlErrEncoding(ctxt, XML_ERR_UNSUPPORTED_ENCODING, "encoding not supported %s\n", BAD_CAST "Shift_JIS", NULL); break; case XML_CHAR_ENCODING_EUC_JP: __xmlErrEncoding(ctxt, XML_ERR_UNSUPPORTED_ENCODING, "encoding not supported %s\n", BAD_CAST "EUC-JP", NULL); break; default: break; } } if (handler == NULL) return(-1); ctxt->charset = XML_CHAR_ENCODING_UTF8; return(xmlSwitchToEncodingInt(ctxt, handler, len)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Avoid processing entities after encoding conversion failures For https://bugzilla.gnome.org/show_bug.cgi?id=756527 and was also raised by Chromium team in the past When we hit a convwersion failure when switching encoding it is bestter to stop parsing there, this was treated as a fatal error but the parser was continuing to process to extract more errors, unfortunately that makes little sense as the data is obviously corrupt and can potentially lead to unexpected behaviour.'</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: xmlParseDocument(xmlParserCtxtPtr ctxt) { xmlChar start[4]; xmlCharEncoding enc; xmlInitParser(); if ((ctxt == NULL) || (ctxt->input == NULL)) return(-1); GROW; /* * SAX: detecting the level. */ xmlDetectSAX2(ctxt); /* * SAX: beginning of the document processing. */ if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); if (ctxt->instate == XML_PARSER_EOF) return(-1); if ((ctxt->encoding == NULL) && ((ctxt->input->end - ctxt->input->cur) >= 4)) { /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. */ start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(&start[0], 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } if (CUR == 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); } /* * Check for the XMLDecl in the Prolog. * do not GROW here to avoid the detected encoder to decode more * than just the first line, unless the amount of data is really * too small to hold "<?xml version="1.0" encoding="foo" */ if ((ctxt->input->end - ctxt->input->cur) < 35) { GROW; } if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { /* * Note that we will switch encoding on the fly. */ xmlParseXMLDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right here */ return(-1); } ctxt->standalone = ctxt->input->standalone; SKIP_BLANKS; } else { ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); } if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); if (ctxt->instate == XML_PARSER_EOF) return(-1); if ((ctxt->myDoc != NULL) && (ctxt->input != NULL) && (ctxt->input->buf != NULL) && (ctxt->input->buf->compressed >= 0)) { ctxt->myDoc->compression = ctxt->input->buf->compressed; } /* * The Misc part of the Prolog */ GROW; xmlParseMisc(ctxt); /* * Then possibly doc type declaration(s) and more Misc * (doctypedecl Misc*)? */ GROW; if (CMP9(CUR_PTR, '<', '!', 'D', 'O', 'C', 'T', 'Y', 'P', 'E')) { ctxt->inSubset = 1; xmlParseDocTypeDecl(ctxt); if (RAW == '[') { ctxt->instate = XML_PARSER_DTD; xmlParseInternalSubset(ctxt); if (ctxt->instate == XML_PARSER_EOF) return(-1); } /* * Create and update the external subset. */ ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (ctxt->sax->externalSubset != NULL) && (!ctxt->disableSAX)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); if (ctxt->instate == XML_PARSER_EOF) return(-1); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); ctxt->instate = XML_PARSER_PROLOG; xmlParseMisc(ctxt); } /* * Time to start parsing the tree itself */ GROW; if (RAW != '<') { xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY, "Start tag expected, '<' not found\n"); } else { ctxt->instate = XML_PARSER_CONTENT; xmlParseElement(ctxt); ctxt->instate = XML_PARSER_EPILOG; /* * The Misc part at the end */ xmlParseMisc(ctxt); if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } ctxt->instate = XML_PARSER_EOF; } /* * SAX: end of the document processing. */ if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); /* * Remove locally kept entity definitions if the tree was not built */ if ((ctxt->myDoc != NULL) && (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) { xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } if ((ctxt->wellFormed) && (ctxt->myDoc != NULL)) { ctxt->myDoc->properties |= XML_DOC_WELLFORMED; if (ctxt->valid) ctxt->myDoc->properties |= XML_DOC_DTDVALID; if (ctxt->nsWellFormed) ctxt->myDoc->properties |= XML_DOC_NSVALID; if (ctxt->options & XML_PARSE_OLD10) ctxt->myDoc->properties |= XML_DOC_OLD10; } if (! ctxt->wellFormed) { ctxt->valid = 0; return(-1); } return(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Avoid processing entities after encoding conversion failures For https://bugzilla.gnome.org/show_bug.cgi?id=756527 and was also raised by Chromium team in the past When we hit a convwersion failure when switching encoding it is bestter to stop parsing there, this was treated as a fatal error but the parser was continuing to process to extract more errors, unfortunately that makes little sense as the data is obviously corrupt and can potentially lead to unexpected behaviour.'</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 xmlGROW (xmlParserCtxtPtr ctxt) { unsigned long curEnd = ctxt->input->end - ctxt->input->cur; unsigned long curBase = ctxt->input->cur - ctxt->input->base; if (((curEnd > (unsigned long) XML_MAX_LOOKUP_LIMIT) || (curBase > (unsigned long) XML_MAX_LOOKUP_LIMIT)) && ((ctxt->input->buf) && (ctxt->input->buf->readcallback != (xmlInputReadCallback) xmlNop)) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "Huge input lookup"); ctxt->instate = XML_PARSER_EOF; } xmlParserInputGrow(ctxt->input, INPUT_CHUNK); if ((ctxt->input->cur != NULL) && (*ctxt->input->cur == 0) && (xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0)) xmlPopInput(ctxt); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Detect incoherency on GROW the current pointer to the input has to be between the base and end if not stop everything we have an internal state error.'</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: xmlParseEncodingDecl(xmlParserCtxtPtr ctxt) { xmlChar *encoding = NULL; SKIP_BLANKS; if (CMP8(CUR_PTR, 'e', 'n', 'c', 'o', 'd', 'i', 'n', 'g')) { SKIP(8); SKIP_BLANKS; if (RAW != '=') { xmlFatalErr(ctxt, XML_ERR_EQUAL_REQUIRED, NULL); return(NULL); } NEXT; SKIP_BLANKS; if (RAW == '"') { NEXT; encoding = xmlParseEncName(ctxt); if (RAW != '"') { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL); } else NEXT; } else if (RAW == '\''){ NEXT; encoding = xmlParseEncName(ctxt); if (RAW != '\'') { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL); } else NEXT; } else { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_STARTED, NULL); } /* * Non standard parsing, allowing the user to ignore encoding */ if (ctxt->options & XML_PARSE_IGNORE_ENC) { xmlFree((xmlChar *) encoding); return(NULL); } /* * UTF-16 encoding stwich has already taken place at this stage, * more over the little-endian/big-endian selection is already done */ if ((encoding != NULL) && ((!xmlStrcasecmp(encoding, BAD_CAST "UTF-16")) || (!xmlStrcasecmp(encoding, BAD_CAST "UTF16")))) { /* * If no encoding was passed to the parser, that we are * using UTF-16 and no decoder is present i.e. the * document is apparently UTF-8 compatible, then raise an * encoding mismatch fatal error */ if ((ctxt->encoding == NULL) && (ctxt->input->buf != NULL) && (ctxt->input->buf->encoder == NULL)) { xmlFatalErrMsg(ctxt, XML_ERR_INVALID_ENCODING, "Document labelled UTF-16 but has UTF-8 content\n"); } if (ctxt->encoding != NULL) xmlFree((xmlChar *) ctxt->encoding); ctxt->encoding = encoding; } /* * UTF-8 encoding is handled natively */ else if ((encoding != NULL) && ((!xmlStrcasecmp(encoding, BAD_CAST "UTF-8")) || (!xmlStrcasecmp(encoding, BAD_CAST "UTF8")))) { if (ctxt->encoding != NULL) xmlFree((xmlChar *) ctxt->encoding); ctxt->encoding = encoding; } else if (encoding != NULL) { xmlCharEncodingHandlerPtr handler; if (ctxt->input->encoding != NULL) xmlFree((xmlChar *) ctxt->input->encoding); ctxt->input->encoding = encoding; handler = xmlFindCharEncodingHandler((const char *) encoding); if (handler != NULL) { xmlSwitchToEncoding(ctxt, handler); } else { xmlFatalErrMsgStr(ctxt, XML_ERR_UNSUPPORTED_ENCODING, "Unsupported encoding %s\n", encoding); return(NULL); } } } return(encoding); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Do not process encoding values if the declaration if broken For https://bugzilla.gnome.org/show_bug.cgi?id=751603 If the string is not properly terminated do not try to convert to the given encoding.'</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: xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref, const xmlChar **URI, int *tlen) { const xmlChar *localname; const xmlChar *prefix; const xmlChar *attname; const xmlChar *aprefix; const xmlChar *nsname; xmlChar *attvalue; const xmlChar **atts = ctxt->atts; int maxatts = ctxt->maxatts; int nratts, nbatts, nbdef; int i, j, nbNs, attval, oldline, oldcol; const xmlChar *base; unsigned long cur; int nsNr = ctxt->nsNr; if (RAW != '<') return(NULL); NEXT1; /* * NOTE: it is crucial with the SAX2 API to never call SHRINK beyond that * point since the attribute values may be stored as pointers to * the buffer and calling SHRINK would destroy them ! * The Shrinking is only possible once the full set of attribute * callbacks have been done. */ reparse: SHRINK; base = ctxt->input->base; cur = ctxt->input->cur - ctxt->input->base; oldline = ctxt->input->line; oldcol = ctxt->input->col; nbatts = 0; nratts = 0; nbdef = 0; nbNs = 0; attval = 0; /* Forget any namespaces added during an earlier parse of this element. */ ctxt->nsNr = nsNr; localname = xmlParseQName(ctxt, &prefix); if (localname == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "StartTag: invalid element name\n"); return(NULL); } *tlen = ctxt->input->cur - ctxt->input->base - cur; /* * Now parse the attributes, it ends up with the ending * * (S Attribute)* S? */ SKIP_BLANKS; GROW; if (ctxt->input->base != base) goto base_changed; while (((RAW != '>') && ((RAW != '/') || (NXT(1) != '>')) && (IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) { const xmlChar *q = CUR_PTR; unsigned int cons = ctxt->input->consumed; int len = -1, alloc = 0; attname = xmlParseAttribute2(ctxt, prefix, localname, &aprefix, &attvalue, &len, &alloc); if (ctxt->input->base != base) { if ((attvalue != NULL) && (alloc != 0)) xmlFree(attvalue); attvalue = NULL; goto base_changed; } if ((attname != NULL) && (attvalue != NULL)) { if (len < 0) len = xmlStrlen(attvalue); if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) { const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len); xmlURIPtr uri; if (URL == NULL) { xmlErrMemory(ctxt, "dictionary allocation failure"); if ((attvalue != NULL) && (alloc != 0)) xmlFree(attvalue); return(NULL); } if (*URL != 0) { uri = xmlParseURI((const char *) URL); if (uri == NULL) { xmlNsErr(ctxt, XML_WAR_NS_URI, "xmlns: '%s' is not a valid URI\n", URL, NULL, NULL); } else { if (uri->scheme == NULL) { xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE, "xmlns: URI %s is not absolute\n", URL, NULL, NULL); } xmlFreeURI(uri); } if (URL == ctxt->str_xml_ns) { if (attname != ctxt->str_xml) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "xml namespace URI cannot be the default namespace\n", NULL, NULL, NULL); } goto skip_default_ns; } if ((len == 29) && (xmlStrEqual(URL, BAD_CAST "http://www.w3.org/2000/xmlns/"))) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "reuse of the xmlns namespace name is forbidden\n", NULL, NULL, NULL); goto skip_default_ns; } } /* * check that it's not a defined namespace */ for (j = 1;j <= nbNs;j++) if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL) break; if (j <= nbNs) xmlErrAttributeDup(ctxt, NULL, attname); else if (nsPush(ctxt, NULL, URL) > 0) nbNs++; skip_default_ns: if (alloc != 0) xmlFree(attvalue); if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) break; if (!IS_BLANK_CH(RAW)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "attributes construct error\n"); break; } SKIP_BLANKS; continue; } if (aprefix == ctxt->str_xmlns) { const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len); xmlURIPtr uri; if (attname == ctxt->str_xml) { if (URL != ctxt->str_xml_ns) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "xml namespace prefix mapped to wrong URI\n", NULL, NULL, NULL); } /* * Do not keep a namespace definition node */ goto skip_ns; } if (URL == ctxt->str_xml_ns) { if (attname != ctxt->str_xml) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "xml namespace URI mapped to wrong prefix\n", NULL, NULL, NULL); } goto skip_ns; } if (attname == ctxt->str_xmlns) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "redefinition of the xmlns prefix is forbidden\n", NULL, NULL, NULL); goto skip_ns; } if ((len == 29) && (xmlStrEqual(URL, BAD_CAST "http://www.w3.org/2000/xmlns/"))) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "reuse of the xmlns namespace name is forbidden\n", NULL, NULL, NULL); goto skip_ns; } if ((URL == NULL) || (URL[0] == 0)) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "xmlns:%s: Empty XML namespace is not allowed\n", attname, NULL, NULL); goto skip_ns; } else { uri = xmlParseURI((const char *) URL); if (uri == NULL) { xmlNsErr(ctxt, XML_WAR_NS_URI, "xmlns:%s: '%s' is not a valid URI\n", attname, URL, NULL); } else { if ((ctxt->pedantic) && (uri->scheme == NULL)) { xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE, "xmlns:%s: URI %s is not absolute\n", attname, URL, NULL); } xmlFreeURI(uri); } } /* * check that it's not a defined namespace */ for (j = 1;j <= nbNs;j++) if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname) break; if (j <= nbNs) xmlErrAttributeDup(ctxt, aprefix, attname); else if (nsPush(ctxt, attname, URL) > 0) nbNs++; skip_ns: if (alloc != 0) xmlFree(attvalue); if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) break; if (!IS_BLANK_CH(RAW)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "attributes construct error\n"); break; } SKIP_BLANKS; if (ctxt->input->base != base) goto base_changed; continue; } /* * Add the pair to atts */ if ((atts == NULL) || (nbatts + 5 > maxatts)) { if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) { if (attvalue[len] == 0) xmlFree(attvalue); goto failed; } maxatts = ctxt->maxatts; atts = ctxt->atts; } ctxt->attallocs[nratts++] = alloc; atts[nbatts++] = attname; atts[nbatts++] = aprefix; atts[nbatts++] = NULL; /* the URI will be fetched later */ atts[nbatts++] = attvalue; attvalue += len; atts[nbatts++] = attvalue; /* * tag if some deallocation is needed */ if (alloc != 0) attval = 1; } else { if ((attvalue != NULL) && (attvalue[len] == 0)) xmlFree(attvalue); } failed: GROW if (ctxt->instate == XML_PARSER_EOF) break; if (ctxt->input->base != base) goto base_changed; if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) break; if (!IS_BLANK_CH(RAW)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "attributes construct error\n"); break; } SKIP_BLANKS; if ((cons == ctxt->input->consumed) && (q == CUR_PTR) && (attname == NULL) && (attvalue == NULL)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlParseStartTag: problem parsing attributes\n"); break; } GROW; if (ctxt->input->base != base) goto base_changed; } /* * The attributes defaulting */ if (ctxt->attsDefault != NULL) { xmlDefAttrsPtr defaults; defaults = xmlHashLookup2(ctxt->attsDefault, localname, prefix); if (defaults != NULL) { for (i = 0;i < defaults->nbAttrs;i++) { attname = defaults->values[5 * i]; aprefix = defaults->values[5 * i + 1]; /* * special work for namespaces defaulted defs */ if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) { /* * check that it's not a defined namespace */ for (j = 1;j <= nbNs;j++) if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL) break; if (j <= nbNs) continue; nsname = xmlGetNamespace(ctxt, NULL); if (nsname != defaults->values[5 * i + 2]) { if (nsPush(ctxt, NULL, defaults->values[5 * i + 2]) > 0) nbNs++; } } else if (aprefix == ctxt->str_xmlns) { /* * check that it's not a defined namespace */ for (j = 1;j <= nbNs;j++) if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname) break; if (j <= nbNs) continue; nsname = xmlGetNamespace(ctxt, attname); if (nsname != defaults->values[2]) { if (nsPush(ctxt, attname, defaults->values[5 * i + 2]) > 0) nbNs++; } } else { /* * check that it's not a defined attribute */ for (j = 0;j < nbatts;j+=5) { if ((attname == atts[j]) && (aprefix == atts[j+1])) break; } if (j < nbatts) continue; if ((atts == NULL) || (nbatts + 5 > maxatts)) { if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) { return(NULL); } maxatts = ctxt->maxatts; atts = ctxt->atts; } atts[nbatts++] = attname; atts[nbatts++] = aprefix; if (aprefix == NULL) atts[nbatts++] = NULL; else atts[nbatts++] = xmlGetNamespace(ctxt, aprefix); atts[nbatts++] = defaults->values[5 * i + 2]; atts[nbatts++] = defaults->values[5 * i + 3]; if ((ctxt->standalone == 1) && (defaults->values[5 * i + 4] != NULL)) { xmlValidityError(ctxt, XML_DTD_STANDALONE_DEFAULTED, "standalone: attribute %s on %s defaulted from external subset\n", attname, localname); } nbdef++; } } } } /* * The attributes checkings */ for (i = 0; i < nbatts;i += 5) { /* * The default namespace does not apply to attribute names. */ if (atts[i + 1] != NULL) { nsname = xmlGetNamespace(ctxt, atts[i + 1]); if (nsname == NULL) { xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE, "Namespace prefix %s for %s on %s is not defined\n", atts[i + 1], atts[i], localname); } atts[i + 2] = nsname; } else nsname = NULL; /* * [ WFC: Unique Att Spec ] * No attribute name may appear more than once in the same * start-tag or empty-element tag. * As extended by the Namespace in XML REC. */ for (j = 0; j < i;j += 5) { if (atts[i] == atts[j]) { if (atts[i+1] == atts[j+1]) { xmlErrAttributeDup(ctxt, atts[i+1], atts[i]); break; } if ((nsname != NULL) && (atts[j + 2] == nsname)) { xmlNsErr(ctxt, XML_NS_ERR_ATTRIBUTE_REDEFINED, "Namespaced Attribute %s in '%s' redefined\n", atts[i], nsname, NULL); break; } } } } nsname = xmlGetNamespace(ctxt, prefix); if ((prefix != NULL) && (nsname == NULL)) { xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE, "Namespace prefix %s on %s is not defined\n", prefix, localname, NULL); } *pref = prefix; *URI = nsname; /* * SAX: Start of Element ! */ if ((ctxt->sax != NULL) && (ctxt->sax->startElementNs != NULL) && (!ctxt->disableSAX)) { if (nbNs > 0) ctxt->sax->startElementNs(ctxt->userData, localname, prefix, nsname, nbNs, &ctxt->nsTab[ctxt->nsNr - 2 * nbNs], nbatts / 5, nbdef, atts); else ctxt->sax->startElementNs(ctxt->userData, localname, prefix, nsname, 0, NULL, nbatts / 5, nbdef, atts); } /* * Free up attribute allocated strings if needed */ if (attval != 0) { for (i = 3,j = 0; j < nratts;i += 5,j++) if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL)) xmlFree((xmlChar *) atts[i]); } return(localname); base_changed: /* * the attribute strings are valid iif the base didn't changed */ if (attval != 0) { for (i = 3,j = 0; j < nratts;i += 5,j++) if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL)) xmlFree((xmlChar *) atts[i]); } ctxt->input->cur = ctxt->input->base + cur; ctxt->input->line = oldline; ctxt->input->col = oldcol; if (ctxt->wellFormed == 1) { goto reparse; } return(NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'CVE-2015-7500 Fix memory access error due to incorrect entities boundaries For https://bugzilla.gnome.org/show_bug.cgi?id=756525 handle properly the case where we popped out of the current entity while processing a start tag Reported by Kostya Serebryany @ Google This slightly modifies the output of 754946 in regression tests'</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 user_update(struct key *key, struct key_preparsed_payload *prep) { struct user_key_payload *upayload, *zap; size_t datalen = prep->datalen; int ret; ret = -EINVAL; if (datalen <= 0 || datalen > 32767 || !prep->data) goto error; /* construct a replacement payload */ ret = -ENOMEM; upayload = kmalloc(sizeof(*upayload) + datalen, GFP_KERNEL); if (!upayload) goto error; upayload->datalen = datalen; memcpy(upayload->data, prep->data, datalen); /* check the quota and attach the new data */ zap = upayload; ret = key_payload_reserve(key, datalen); if (ret == 0) { /* attach the new data, displacing the old */ zap = key->payload.data[0]; rcu_assign_keypointer(key, upayload); key->expiry = 0; } if (zap) kfree_rcu(zap, rcu); error: return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264', 'CWE-269'], 'message': 'KEYS: Fix handling of stored error in a negatively instantiated user key If a user key gets negatively instantiated, an error code is cached in the payload area. A negatively instantiated key may be then be positively instantiated by updating it with valid data. However, the ->update key type method must be aware that the error code may be there. The following may be used to trigger the bug in the user key type: keyctl request2 user user "" @u keyctl add user user "a" @u which manifests itself as: BUG: unable to handle kernel paging request at 00000000ffffff8a IP: [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046 PGD 7cc30067 PUD 0 Oops: 0002 [#1] SMP Modules linked in: CPU: 3 PID: 2644 Comm: a.out Not tainted 4.3.0+ #49 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 task: ffff88003ddea700 ti: ffff88003dd88000 task.ti: ffff88003dd88000 RIP: 0010:[<ffffffff810a376f>] [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046 RSP: 0018:ffff88003dd8bdb0 EFLAGS: 00010246 RAX: 00000000ffffff82 RBX: 0000000000000000 RCX: 0000000000000001 RDX: ffffffff81e3fe40 RSI: 0000000000000000 RDI: 00000000ffffff82 RBP: ffff88003dd8bde0 R08: ffff88007d2d2da0 R09: 0000000000000000 R10: 0000000000000000 R11: ffff88003e8073c0 R12: 00000000ffffff82 R13: ffff88003dd8be68 R14: ffff88007d027600 R15: ffff88003ddea700 FS: 0000000000b92880(0063) GS:ffff88007fd00000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b CR2: 00000000ffffff8a CR3: 000000007cc5f000 CR4: 00000000000006e0 Stack: ffff88003dd8bdf0 ffffffff81160a8a 0000000000000000 00000000ffffff82 ffff88003dd8be68 ffff88007d027600 ffff88003dd8bdf0 ffffffff810a39e5 ffff88003dd8be20 ffffffff812a31ab ffff88007d027600 ffff88007d027620 Call Trace: [<ffffffff810a39e5>] kfree_call_rcu+0x15/0x20 kernel/rcu/tree.c:3136 [<ffffffff812a31ab>] user_update+0x8b/0xb0 security/keys/user_defined.c:129 [< inline >] __key_update security/keys/key.c:730 [<ffffffff8129e5c1>] key_create_or_update+0x291/0x440 security/keys/key.c:908 [< inline >] SYSC_add_key security/keys/keyctl.c:125 [<ffffffff8129fc21>] SyS_add_key+0x101/0x1e0 security/keys/keyctl.c:60 [<ffffffff8185f617>] entry_SYSCALL_64_fastpath+0x12/0x6a arch/x86/entry/entry_64.S:185 Note the error code (-ENOKEY) in EDX. A similar bug can be tripped by: keyctl request2 trusted user "" @u keyctl add trusted user "a" @u This should also affect encrypted keys - but that has to be correctly parameterised or it will fail with EINVAL before getting to the bit that will crashes. Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: David Howells <[email protected]> Acked-by: Mimi Zohar <[email protected]> Signed-off-by: James Morris <[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 trusted_update(struct key *key, struct key_preparsed_payload *prep) { struct trusted_key_payload *p = key->payload.data[0]; struct trusted_key_payload *new_p; struct trusted_key_options *new_o; size_t datalen = prep->datalen; char *datablob; int ret = 0; if (!p->migratable) return -EPERM; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; datablob = kmalloc(datalen + 1, GFP_KERNEL); if (!datablob) return -ENOMEM; new_o = trusted_options_alloc(); if (!new_o) { ret = -ENOMEM; goto out; } new_p = trusted_payload_alloc(key); if (!new_p) { ret = -ENOMEM; goto out; } memcpy(datablob, prep->data, datalen); datablob[datalen] = '\0'; ret = datablob_parse(datablob, new_p, new_o); if (ret != Opt_update) { ret = -EINVAL; kfree(new_p); goto out; } if (!new_o->keyhandle) { ret = -EINVAL; kfree(new_p); goto out; } /* copy old key values, and reseal with new pcrs */ new_p->migratable = p->migratable; new_p->key_len = p->key_len; memcpy(new_p->key, p->key, p->key_len); dump_payload(p); dump_payload(new_p); ret = key_seal(new_p, new_o); if (ret < 0) { pr_info("trusted_key: key_seal failed (%d)\n", ret); kfree(new_p); goto out; } if (new_o->pcrlock) { ret = pcrlock(new_o->pcrlock); if (ret < 0) { pr_info("trusted_key: pcrlock failed (%d)\n", ret); kfree(new_p); goto out; } } rcu_assign_keypointer(key, new_p); call_rcu(&p->rcu, trusted_rcu_free); out: kfree(datablob); kfree(new_o); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264', 'CWE-269'], 'message': 'KEYS: Fix handling of stored error in a negatively instantiated user key If a user key gets negatively instantiated, an error code is cached in the payload area. A negatively instantiated key may be then be positively instantiated by updating it with valid data. However, the ->update key type method must be aware that the error code may be there. The following may be used to trigger the bug in the user key type: keyctl request2 user user "" @u keyctl add user user "a" @u which manifests itself as: BUG: unable to handle kernel paging request at 00000000ffffff8a IP: [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046 PGD 7cc30067 PUD 0 Oops: 0002 [#1] SMP Modules linked in: CPU: 3 PID: 2644 Comm: a.out Not tainted 4.3.0+ #49 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 task: ffff88003ddea700 ti: ffff88003dd88000 task.ti: ffff88003dd88000 RIP: 0010:[<ffffffff810a376f>] [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046 RSP: 0018:ffff88003dd8bdb0 EFLAGS: 00010246 RAX: 00000000ffffff82 RBX: 0000000000000000 RCX: 0000000000000001 RDX: ffffffff81e3fe40 RSI: 0000000000000000 RDI: 00000000ffffff82 RBP: ffff88003dd8bde0 R08: ffff88007d2d2da0 R09: 0000000000000000 R10: 0000000000000000 R11: ffff88003e8073c0 R12: 00000000ffffff82 R13: ffff88003dd8be68 R14: ffff88007d027600 R15: ffff88003ddea700 FS: 0000000000b92880(0063) GS:ffff88007fd00000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b CR2: 00000000ffffff8a CR3: 000000007cc5f000 CR4: 00000000000006e0 Stack: ffff88003dd8bdf0 ffffffff81160a8a 0000000000000000 00000000ffffff82 ffff88003dd8be68 ffff88007d027600 ffff88003dd8bdf0 ffffffff810a39e5 ffff88003dd8be20 ffffffff812a31ab ffff88007d027600 ffff88007d027620 Call Trace: [<ffffffff810a39e5>] kfree_call_rcu+0x15/0x20 kernel/rcu/tree.c:3136 [<ffffffff812a31ab>] user_update+0x8b/0xb0 security/keys/user_defined.c:129 [< inline >] __key_update security/keys/key.c:730 [<ffffffff8129e5c1>] key_create_or_update+0x291/0x440 security/keys/key.c:908 [< inline >] SYSC_add_key security/keys/keyctl.c:125 [<ffffffff8129fc21>] SyS_add_key+0x101/0x1e0 security/keys/keyctl.c:60 [<ffffffff8185f617>] entry_SYSCALL_64_fastpath+0x12/0x6a arch/x86/entry/entry_64.S:185 Note the error code (-ENOKEY) in EDX. A similar bug can be tripped by: keyctl request2 trusted user "" @u keyctl add trusted user "a" @u This should also affect encrypted keys - but that has to be correctly parameterised or it will fail with EINVAL before getting to the bit that will crashes. Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: David Howells <[email protected]> Acked-by: Mimi Zohar <[email protected]> Signed-off-by: James Morris <[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: enum nss_status _nss_mymachines_getgrnam_r( const char *name, struct group *gr, char *buffer, size_t buflen, int *errnop) { _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_bus_message_unref_ sd_bus_message* reply = NULL; _cleanup_bus_flush_close_unref_ sd_bus *bus = NULL; const char *p, *e, *machine; uint32_t mapped; uid_t gid; size_t l; int r; assert(name); assert(gr); p = startswith(name, "vg-"); if (!p) goto not_found; e = strrchr(p, '-'); if (!e || e == p) goto not_found; r = parse_gid(e + 1, &gid); if (r < 0) goto not_found; machine = strndupa(p, e - p); if (!machine_name_is_valid(machine)) goto not_found; r = sd_bus_open_system(&bus); if (r < 0) goto fail; r = sd_bus_call_method(bus, "org.freedesktop.machine1", "/org/freedesktop/machine1", "org.freedesktop.machine1.Manager", "MapFromMachineGroup", &error, &reply, "su", machine, (uint32_t) gid); if (r < 0) { if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_GROUP_MAPPING)) goto not_found; goto fail; } r = sd_bus_message_read(reply, "u", &mapped); if (r < 0) goto fail; l = sizeof(char*) + strlen(name) + 1; if (buflen < l) { *errnop = ENOMEM; return NSS_STATUS_TRYAGAIN; } memzero(buffer, sizeof(char*)); strcpy(buffer + sizeof(char*), name); gr->gr_name = buffer + sizeof(char*); gr->gr_gid = gid; gr->gr_passwd = (char*) "*"; /* locked */ gr->gr_mem = (char**) buffer; *errnop = 0; return NSS_STATUS_SUCCESS; not_found: *errnop = 0; return NSS_STATUS_NOTFOUND; fail: *errnop = -r; return NSS_STATUS_UNAVAIL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415', 'CWE-119'], 'message': 'nss-mymachines: do not allow overlong machine names https://github.com/systemd/systemd/issues/2002'</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: aiptek_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *usbdev = interface_to_usbdev(intf); struct usb_endpoint_descriptor *endpoint; struct aiptek *aiptek; struct input_dev *inputdev; int i; int speeds[] = { 0, AIPTEK_PROGRAMMABLE_DELAY_50, AIPTEK_PROGRAMMABLE_DELAY_400, AIPTEK_PROGRAMMABLE_DELAY_25, AIPTEK_PROGRAMMABLE_DELAY_100, AIPTEK_PROGRAMMABLE_DELAY_200, AIPTEK_PROGRAMMABLE_DELAY_300 }; int err = -ENOMEM; /* programmableDelay is where the command-line specified * delay is kept. We make it the first element of speeds[], * so therefore, your override speed is tried first, then the * remainder. Note that the default value of 400ms will be tried * if you do not specify any command line parameter. */ speeds[0] = programmableDelay; aiptek = kzalloc(sizeof(struct aiptek), GFP_KERNEL); inputdev = input_allocate_device(); if (!aiptek || !inputdev) { dev_warn(&intf->dev, "cannot allocate memory or input device\n"); goto fail1; } aiptek->data = usb_alloc_coherent(usbdev, AIPTEK_PACKET_LENGTH, GFP_ATOMIC, &aiptek->data_dma); if (!aiptek->data) { dev_warn(&intf->dev, "cannot allocate usb buffer\n"); goto fail1; } aiptek->urb = usb_alloc_urb(0, GFP_KERNEL); if (!aiptek->urb) { dev_warn(&intf->dev, "cannot allocate urb\n"); goto fail2; } aiptek->inputdev = inputdev; aiptek->usbdev = usbdev; aiptek->intf = intf; aiptek->ifnum = intf->altsetting[0].desc.bInterfaceNumber; aiptek->inDelay = 0; aiptek->endDelay = 0; aiptek->previousJitterable = 0; aiptek->lastMacro = -1; /* Set up the curSettings struct. Said struct contains the current * programmable parameters. The newSetting struct contains changes * the user makes to the settings via the sysfs interface. Those * changes are not "committed" to curSettings until the user * writes to the sysfs/.../execute file. */ aiptek->curSetting.pointerMode = AIPTEK_POINTER_EITHER_MODE; aiptek->curSetting.coordinateMode = AIPTEK_COORDINATE_ABSOLUTE_MODE; aiptek->curSetting.toolMode = AIPTEK_TOOL_BUTTON_PEN_MODE; aiptek->curSetting.xTilt = AIPTEK_TILT_DISABLE; aiptek->curSetting.yTilt = AIPTEK_TILT_DISABLE; aiptek->curSetting.mouseButtonLeft = AIPTEK_MOUSE_LEFT_BUTTON; aiptek->curSetting.mouseButtonMiddle = AIPTEK_MOUSE_MIDDLE_BUTTON; aiptek->curSetting.mouseButtonRight = AIPTEK_MOUSE_RIGHT_BUTTON; aiptek->curSetting.stylusButtonUpper = AIPTEK_STYLUS_UPPER_BUTTON; aiptek->curSetting.stylusButtonLower = AIPTEK_STYLUS_LOWER_BUTTON; aiptek->curSetting.jitterDelay = jitterDelay; aiptek->curSetting.programmableDelay = programmableDelay; /* Both structs should have equivalent settings */ aiptek->newSetting = aiptek->curSetting; /* Determine the usb devices' physical path. * Asketh not why we always pretend we're using "../input0", * but I suspect this will have to be refactored one * day if a single USB device can be a keyboard & a mouse * & a tablet, and the inputX number actually will tell * us something... */ usb_make_path(usbdev, aiptek->features.usbPath, sizeof(aiptek->features.usbPath)); strlcat(aiptek->features.usbPath, "/input0", sizeof(aiptek->features.usbPath)); /* Set up client data, pointers to open and close routines * for the input device. */ inputdev->name = "Aiptek"; inputdev->phys = aiptek->features.usbPath; usb_to_input_id(usbdev, &inputdev->id); inputdev->dev.parent = &intf->dev; input_set_drvdata(inputdev, aiptek); inputdev->open = aiptek_open; inputdev->close = aiptek_close; /* Now program the capacities of the tablet, in terms of being * an input device. */ for (i = 0; i < ARRAY_SIZE(eventTypes); ++i) __set_bit(eventTypes[i], inputdev->evbit); for (i = 0; i < ARRAY_SIZE(absEvents); ++i) __set_bit(absEvents[i], inputdev->absbit); for (i = 0; i < ARRAY_SIZE(relEvents); ++i) __set_bit(relEvents[i], inputdev->relbit); __set_bit(MSC_SERIAL, inputdev->mscbit); /* Set up key and button codes */ for (i = 0; i < ARRAY_SIZE(buttonEvents); ++i) __set_bit(buttonEvents[i], inputdev->keybit); for (i = 0; i < ARRAY_SIZE(macroKeyEvents); ++i) __set_bit(macroKeyEvents[i], inputdev->keybit); /* * Program the input device coordinate capacities. We do not yet * know what maximum X, Y, and Z values are, so we're putting fake * values in. Later, we'll ask the tablet to put in the correct * values. */ input_set_abs_params(inputdev, ABS_X, 0, 2999, 0, 0); input_set_abs_params(inputdev, ABS_Y, 0, 2249, 0, 0); input_set_abs_params(inputdev, ABS_PRESSURE, 0, 511, 0, 0); input_set_abs_params(inputdev, ABS_TILT_X, AIPTEK_TILT_MIN, AIPTEK_TILT_MAX, 0, 0); input_set_abs_params(inputdev, ABS_TILT_Y, AIPTEK_TILT_MIN, AIPTEK_TILT_MAX, 0, 0); input_set_abs_params(inputdev, ABS_WHEEL, AIPTEK_WHEEL_MIN, AIPTEK_WHEEL_MAX - 1, 0, 0); endpoint = &intf->altsetting[0].endpoint[0].desc; /* Go set up our URB, which is called when the tablet receives * input. */ usb_fill_int_urb(aiptek->urb, aiptek->usbdev, usb_rcvintpipe(aiptek->usbdev, endpoint->bEndpointAddress), aiptek->data, 8, aiptek_irq, aiptek, endpoint->bInterval); aiptek->urb->transfer_dma = aiptek->data_dma; aiptek->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; /* Program the tablet. This sets the tablet up in the mode * specified in newSetting, and also queries the tablet's * physical capacities. * * Sanity check: if a tablet doesn't like the slow programmatic * delay, we often get sizes of 0x0. Let's use that as an indicator * to try faster delays, up to 25 ms. If that logic fails, well, you'll * have to explain to us how your tablet thinks it's 0x0, and yet that's * not an error :-) */ for (i = 0; i < ARRAY_SIZE(speeds); ++i) { aiptek->curSetting.programmableDelay = speeds[i]; (void)aiptek_program_tablet(aiptek); if (input_abs_get_max(aiptek->inputdev, ABS_X) > 0) { dev_info(&intf->dev, "Aiptek using %d ms programming speed\n", aiptek->curSetting.programmableDelay); break; } } /* Murphy says that some day someone will have a tablet that fails the above test. That's you, Frederic Rodrigo */ if (i == ARRAY_SIZE(speeds)) { dev_info(&intf->dev, "Aiptek tried all speeds, no sane response\n"); goto fail3; } /* Associate this driver's struct with the usb interface. */ usb_set_intfdata(intf, aiptek); /* Set up the sysfs files */ err = sysfs_create_group(&intf->dev.kobj, &aiptek_attribute_group); if (err) { dev_warn(&intf->dev, "cannot create sysfs group err: %d\n", err); goto fail3; } /* Register the tablet as an Input Device */ err = input_register_device(aiptek->inputdev); if (err) { dev_warn(&intf->dev, "input_register_device returned err: %d\n", err); goto fail4; } return 0; fail4: sysfs_remove_group(&intf->dev.kobj, &aiptek_attribute_group); fail3: usb_free_urb(aiptek->urb); fail2: usb_free_coherent(usbdev, AIPTEK_PACKET_LENGTH, aiptek->data, aiptek->data_dma); fail1: usb_set_intfdata(intf, NULL); input_free_device(inputdev); kfree(aiptek); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-401'], 'message': 'Input: aiptek - fix crash on detecting device without endpoints The aiptek driver crashes in aiptek_probe() when a specially crafted USB device without endpoints is detected. This fix adds a check that the device has proper configuration expected by the driver. Also an error return value is changed to more matching one in one of the error paths. Reported-by: Ralf Spenneberg <[email protected]> Signed-off-by: Vladis Dronov <[email protected]> Signed-off-by: Dmitry Torokhov <[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 btrfs_clone(struct inode *src, struct inode *inode, const u64 off, const u64 olen, const u64 olen_aligned, const u64 destoff, int no_time_update) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_path *path = NULL; struct extent_buffer *leaf; struct btrfs_trans_handle *trans; char *buf = NULL; struct btrfs_key key; u32 nritems; int slot; int ret; int no_quota; const u64 len = olen_aligned; u64 last_disko = 0; u64 last_dest_end = destoff; ret = -ENOMEM; buf = vmalloc(root->nodesize); if (!buf) return ret; path = btrfs_alloc_path(); if (!path) { vfree(buf); return ret; } path->reada = 2; /* clone data */ key.objectid = btrfs_ino(src); key.type = BTRFS_EXTENT_DATA_KEY; key.offset = off; while (1) { u64 next_key_min_offset = key.offset + 1; /* * note the key will change type as we walk through the * tree. */ path->leave_spinning = 1; ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path, 0, 0); if (ret < 0) goto out; /* * First search, if no extent item that starts at offset off was * found but the previous item is an extent item, it's possible * it might overlap our target range, therefore process it. */ if (key.offset == off && ret > 0 && path->slots[0] > 0) { btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1); if (key.type == BTRFS_EXTENT_DATA_KEY) path->slots[0]--; } nritems = btrfs_header_nritems(path->nodes[0]); process_slot: no_quota = 1; if (path->slots[0] >= nritems) { ret = btrfs_next_leaf(BTRFS_I(src)->root, path); if (ret < 0) goto out; if (ret > 0) break; nritems = btrfs_header_nritems(path->nodes[0]); } leaf = path->nodes[0]; slot = path->slots[0]; btrfs_item_key_to_cpu(leaf, &key, slot); if (key.type > BTRFS_EXTENT_DATA_KEY || key.objectid != btrfs_ino(src)) break; if (key.type == BTRFS_EXTENT_DATA_KEY) { struct btrfs_file_extent_item *extent; int type; u32 size; struct btrfs_key new_key; u64 disko = 0, diskl = 0; u64 datao = 0, datal = 0; u8 comp; u64 drop_start; extent = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item); comp = btrfs_file_extent_compression(leaf, extent); type = btrfs_file_extent_type(leaf, extent); if (type == BTRFS_FILE_EXTENT_REG || type == BTRFS_FILE_EXTENT_PREALLOC) { disko = btrfs_file_extent_disk_bytenr(leaf, extent); diskl = btrfs_file_extent_disk_num_bytes(leaf, extent); datao = btrfs_file_extent_offset(leaf, extent); datal = btrfs_file_extent_num_bytes(leaf, extent); } else if (type == BTRFS_FILE_EXTENT_INLINE) { /* take upper bound, may be compressed */ datal = btrfs_file_extent_ram_bytes(leaf, extent); } /* * The first search might have left us at an extent * item that ends before our target range's start, can * happen if we have holes and NO_HOLES feature enabled. */ if (key.offset + datal <= off) { path->slots[0]++; goto process_slot; } else if (key.offset >= off + len) { break; } next_key_min_offset = key.offset + datal; size = btrfs_item_size_nr(leaf, slot); read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf, slot), size); btrfs_release_path(path); path->leave_spinning = 0; memcpy(&new_key, &key, sizeof(new_key)); new_key.objectid = btrfs_ino(inode); if (off <= key.offset) new_key.offset = key.offset + destoff - off; else new_key.offset = destoff; /* * Deal with a hole that doesn't have an extent item * that represents it (NO_HOLES feature enabled). * This hole is either in the middle of the cloning * range or at the beginning (fully overlaps it or * partially overlaps it). */ if (new_key.offset != last_dest_end) drop_start = last_dest_end; else drop_start = new_key.offset; /* * 1 - adjusting old extent (we may have to split it) * 1 - add new extent * 1 - inode update */ trans = btrfs_start_transaction(root, 3); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out; } if (type == BTRFS_FILE_EXTENT_REG || type == BTRFS_FILE_EXTENT_PREALLOC) { /* * a | --- range to clone ---| b * | ------------- extent ------------- | */ /* subtract range b */ if (key.offset + datal > off + len) datal = off + len - key.offset; /* subtract range a */ if (off > key.offset) { datao += off - key.offset; datal -= off - key.offset; } ret = btrfs_drop_extents(trans, root, inode, drop_start, new_key.offset + datal, 1); if (ret) { if (ret != -EOPNOTSUPP) btrfs_abort_transaction(trans, root, ret); btrfs_end_transaction(trans, root); goto out; } ret = btrfs_insert_empty_item(trans, root, path, &new_key, size); if (ret) { btrfs_abort_transaction(trans, root, ret); btrfs_end_transaction(trans, root); goto out; } leaf = path->nodes[0]; slot = path->slots[0]; write_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf, slot), size); extent = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item); /* disko == 0 means it's a hole */ if (!disko) datao = 0; btrfs_set_file_extent_offset(leaf, extent, datao); btrfs_set_file_extent_num_bytes(leaf, extent, datal); /* * We need to look up the roots that point at * this bytenr and see if the new root does. If * it does not we need to make sure we update * quotas appropriately. */ if (disko && root != BTRFS_I(src)->root && disko != last_disko) { no_quota = check_ref(trans, root, disko); if (no_quota < 0) { btrfs_abort_transaction(trans, root, ret); btrfs_end_transaction(trans, root); ret = no_quota; goto out; } } if (disko) { inode_add_bytes(inode, datal); ret = btrfs_inc_extent_ref(trans, root, disko, diskl, 0, root->root_key.objectid, btrfs_ino(inode), new_key.offset - datao, no_quota); if (ret) { btrfs_abort_transaction(trans, root, ret); btrfs_end_transaction(trans, root); goto out; } } } else if (type == BTRFS_FILE_EXTENT_INLINE) { u64 skip = 0; u64 trim = 0; u64 aligned_end = 0; /* * Don't copy an inline extent into an offset * greater than zero. Having an inline extent * at such an offset results in chaos as btrfs * isn't prepared for such cases. Just skip * this case for the same reasons as commented * at btrfs_ioctl_clone(). */ if (last_dest_end > 0) { ret = -EOPNOTSUPP; btrfs_end_transaction(trans, root); goto out; } if (off > key.offset) { skip = off - key.offset; new_key.offset += skip; } if (key.offset + datal > off + len) trim = key.offset + datal - (off + len); if (comp && (skip || trim)) { ret = -EINVAL; btrfs_end_transaction(trans, root); goto out; } size -= skip + trim; datal -= skip + trim; aligned_end = ALIGN(new_key.offset + datal, root->sectorsize); ret = btrfs_drop_extents(trans, root, inode, drop_start, aligned_end, 1); if (ret) { if (ret != -EOPNOTSUPP) btrfs_abort_transaction(trans, root, ret); btrfs_end_transaction(trans, root); goto out; } ret = btrfs_insert_empty_item(trans, root, path, &new_key, size); if (ret) { btrfs_abort_transaction(trans, root, ret); btrfs_end_transaction(trans, root); goto out; } if (skip) { u32 start = btrfs_file_extent_calc_inline_size(0); memmove(buf+start, buf+start+skip, datal); } leaf = path->nodes[0]; slot = path->slots[0]; write_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf, slot), size); inode_add_bytes(inode, datal); } /* If we have an implicit hole (NO_HOLES feature). */ if (drop_start < new_key.offset) clone_update_extent_map(inode, trans, NULL, drop_start, new_key.offset - drop_start); clone_update_extent_map(inode, trans, path, 0, 0); btrfs_mark_buffer_dirty(leaf); btrfs_release_path(path); last_dest_end = ALIGN(new_key.offset + datal, root->sectorsize); ret = clone_finish_inode_update(trans, inode, last_dest_end, destoff, olen, no_time_update); if (ret) goto out; if (new_key.offset + datal >= destoff + len) break; } btrfs_release_path(path); key.offset = next_key_min_offset; } ret = 0; if (last_dest_end < destoff + len) { /* * We have an implicit hole (NO_HOLES feature is enabled) that * fully or partially overlaps our cloning range at its end. */ btrfs_release_path(path); /* * 1 - remove extent(s) * 1 - inode update */ trans = btrfs_start_transaction(root, 2); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out; } ret = btrfs_drop_extents(trans, root, inode, last_dest_end, destoff + len, 1); if (ret) { if (ret != -EOPNOTSUPP) btrfs_abort_transaction(trans, root, ret); btrfs_end_transaction(trans, root); goto out; } clone_update_extent_map(inode, trans, NULL, last_dest_end, destoff + len - last_dest_end); ret = clone_finish_inode_update(trans, inode, destoff + len, destoff, olen, no_time_update); } out: btrfs_free_path(path); vfree(buf); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Btrfs: fix file corruption and data loss after cloning inline extents Currently the clone ioctl allows to clone an inline extent from one file to another that already has other (non-inlined) extents. This is a problem because btrfs is not designed to deal with files having inline and regular extents, if a file has an inline extent then it must be the only extent in the file and must start at file offset 0. Having a file with an inline extent followed by regular extents results in EIO errors when doing reads or writes against the first 4K of the file. Also, the clone ioctl allows one to lose data if the source file consists of a single inline extent, with a size of N bytes, and the destination file consists of a single inline extent with a size of M bytes, where we have M > N. In this case the clone operation removes the inline extent from the destination file and then copies the inline extent from the source file into the destination file - we lose the M - N bytes from the destination file, a read operation will get the value 0x00 for any bytes in the the range [N, M] (the destination inode's i_size remained as M, that's why we can read past N bytes). So fix this by not allowing such destructive operations to happen and return errno EOPNOTSUPP to user space. Currently the fstest btrfs/035 tests the data loss case but it totally ignores this - i.e. expects the operation to succeed and does not check the we got data loss. The following test case for fstests exercises all these cases that result in file corruption and data loss: seq=`basename $0` seqres=$RESULT_DIR/$seq echo "QA output created by $seq" tmp=/tmp/$$ status=1 # failure is the default! trap "_cleanup; exit \$status" 0 1 2 3 15 _cleanup() { rm -f $tmp.* } # get standard environment, filters and checks . ./common/rc . ./common/filter # real QA test starts here _need_to_be_root _supported_fs btrfs _supported_os Linux _require_scratch _require_cloner _require_btrfs_fs_feature "no_holes" _require_btrfs_mkfs_feature "no-holes" rm -f $seqres.full test_cloning_inline_extents() { local mkfs_opts=$1 local mount_opts=$2 _scratch_mkfs $mkfs_opts >>$seqres.full 2>&1 _scratch_mount $mount_opts # File bar, the source for all the following clone operations, consists # of a single inline extent (50 bytes). $XFS_IO_PROG -f -c "pwrite -S 0xbb 0 50" $SCRATCH_MNT/bar \ | _filter_xfs_io # Test cloning into a file with an extent (non-inlined) where the # destination offset overlaps that extent. It should not be possible to # clone the inline extent from file bar into this file. $XFS_IO_PROG -f -c "pwrite -S 0xaa 0K 16K" $SCRATCH_MNT/foo \ | _filter_xfs_io $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/bar $SCRATCH_MNT/foo # Doing IO against any range in the first 4K of the file should work. # Due to a past clone ioctl bug which allowed cloning the inline extent, # these operations resulted in EIO errors. echo "File foo data after clone operation:" # All bytes should have the value 0xaa (clone operation failed and did # not modify our file). od -t x1 $SCRATCH_MNT/foo $XFS_IO_PROG -c "pwrite -S 0xcc 0 100" $SCRATCH_MNT/foo | _filter_xfs_io # Test cloning the inline extent against a file which has a hole in its # first 4K followed by a non-inlined extent. It should not be possible # as well to clone the inline extent from file bar into this file. $XFS_IO_PROG -f -c "pwrite -S 0xdd 4K 12K" $SCRATCH_MNT/foo2 \ | _filter_xfs_io $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/bar $SCRATCH_MNT/foo2 # Doing IO against any range in the first 4K of the file should work. # Due to a past clone ioctl bug which allowed cloning the inline extent, # these operations resulted in EIO errors. echo "File foo2 data after clone operation:" # All bytes should have the value 0x00 (clone operation failed and did # not modify our file). od -t x1 $SCRATCH_MNT/foo2 $XFS_IO_PROG -c "pwrite -S 0xee 0 90" $SCRATCH_MNT/foo2 | _filter_xfs_io # Test cloning the inline extent against a file which has a size of zero # but has a prealloc extent. It should not be possible as well to clone # the inline extent from file bar into this file. $XFS_IO_PROG -f -c "falloc -k 0 1M" $SCRATCH_MNT/foo3 | _filter_xfs_io $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/bar $SCRATCH_MNT/foo3 # Doing IO against any range in the first 4K of the file should work. # Due to a past clone ioctl bug which allowed cloning the inline extent, # these operations resulted in EIO errors. echo "First 50 bytes of foo3 after clone operation:" # Should not be able to read any bytes, file has 0 bytes i_size (the # clone operation failed and did not modify our file). od -t x1 $SCRATCH_MNT/foo3 $XFS_IO_PROG -c "pwrite -S 0xff 0 90" $SCRATCH_MNT/foo3 | _filter_xfs_io # Test cloning the inline extent against a file which consists of a # single inline extent that has a size not greater than the size of # bar's inline extent (40 < 50). # It should be possible to do the extent cloning from bar to this file. $XFS_IO_PROG -f -c "pwrite -S 0x01 0 40" $SCRATCH_MNT/foo4 \ | _filter_xfs_io $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/bar $SCRATCH_MNT/foo4 # Doing IO against any range in the first 4K of the file should work. echo "File foo4 data after clone operation:" # Must match file bar's content. od -t x1 $SCRATCH_MNT/foo4 $XFS_IO_PROG -c "pwrite -S 0x02 0 90" $SCRATCH_MNT/foo4 | _filter_xfs_io # Test cloning the inline extent against a file which consists of a # single inline extent that has a size greater than the size of bar's # inline extent (60 > 50). # It should not be possible to clone the inline extent from file bar # into this file. $XFS_IO_PROG -f -c "pwrite -S 0x03 0 60" $SCRATCH_MNT/foo5 \ | _filter_xfs_io $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/bar $SCRATCH_MNT/foo5 # Reading the file should not fail. echo "File foo5 data after clone operation:" # Must have a size of 60 bytes, with all bytes having a value of 0x03 # (the clone operation failed and did not modify our file). od -t x1 $SCRATCH_MNT/foo5 # Test cloning the inline extent against a file which has no extents but # has a size greater than bar's inline extent (16K > 50). # It should not be possible to clone the inline extent from file bar # into this file. $XFS_IO_PROG -f -c "truncate 16K" $SCRATCH_MNT/foo6 | _filter_xfs_io $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/bar $SCRATCH_MNT/foo6 # Reading the file should not fail. echo "File foo6 data after clone operation:" # Must have a size of 16K, with all bytes having a value of 0x00 (the # clone operation failed and did not modify our file). od -t x1 $SCRATCH_MNT/foo6 # Test cloning the inline extent against a file which has no extents but # has a size not greater than bar's inline extent (30 < 50). # It should be possible to clone the inline extent from file bar into # this file. $XFS_IO_PROG -f -c "truncate 30" $SCRATCH_MNT/foo7 | _filter_xfs_io $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/bar $SCRATCH_MNT/foo7 # Reading the file should not fail. echo "File foo7 data after clone operation:" # Must have a size of 50 bytes, with all bytes having a value of 0xbb. od -t x1 $SCRATCH_MNT/foo7 # Test cloning the inline extent against a file which has a size not # greater than the size of bar's inline extent (20 < 50) but has # a prealloc extent that goes beyond the file's size. It should not be # possible to clone the inline extent from bar into this file. $XFS_IO_PROG -f -c "falloc -k 0 1M" \ -c "pwrite -S 0x88 0 20" \ $SCRATCH_MNT/foo8 | _filter_xfs_io $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/bar $SCRATCH_MNT/foo8 echo "File foo8 data after clone operation:" # Must have a size of 20 bytes, with all bytes having a value of 0x88 # (the clone operation did not modify our file). od -t x1 $SCRATCH_MNT/foo8 _scratch_unmount } echo -e "\nTesting without compression and without the no-holes feature...\n" test_cloning_inline_extents echo -e "\nTesting with compression and without the no-holes feature...\n" test_cloning_inline_extents "" "-o compress" echo -e "\nTesting without compression and with the no-holes feature...\n" test_cloning_inline_extents "-O no-holes" "" echo -e "\nTesting with compression and with the no-holes feature...\n" test_cloning_inline_extents "-O no-holes" "-o compress" status=0 exit Cc: [email protected] Signed-off-by: Filipe Manana <[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: grub_password_get (char buf[], unsigned buf_size) { unsigned cur_len = 0; int key; while (1) { key = grub_getkey (); if (key == '\n' || key == '\r') break; if (key == '\e') { cur_len = 0; break; } if (key == '\b') { cur_len--; continue; } if (!grub_isprint (key)) continue; if (cur_len + 2 < buf_size) buf[cur_len++] = key; } grub_memset (buf + cur_len, 0, buf_size - cur_len); grub_xputs ("\n"); grub_refresh (); return (key != '\e'); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Fix security issue when reading username and password This patch fixes two integer underflows at: * grub-core/lib/crypto.c * grub-core/normal/auth.c CVE-2015-8370 Signed-off-by: Hector Marco-Gisbert <[email protected]> Signed-off-by: Ismael Ripoll-Ripoll <[email protected]> Also-By: Andrey Borzenkov <[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 LibRaw::unpack(void) { CHECK_ORDER_HIGH(LIBRAW_PROGRESS_LOAD_RAW); CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); try { if(!libraw_internal_data.internal_data.input) return LIBRAW_INPUT_CLOSED; RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW,0,2); if (O.shot_select >= P1.raw_count) return LIBRAW_REQUEST_FOR_NONEXISTENT_IMAGE; if(!load_raw) return LIBRAW_UNSPECIFIED_ERROR; // already allocated ? if(imgdata.image) { free(imgdata.image); imgdata.image = 0; } if(imgdata.rawdata.raw_alloc) { free(imgdata.rawdata.raw_alloc); imgdata.rawdata.raw_alloc = 0; } if (libraw_internal_data.unpacker_data.meta_length) { libraw_internal_data.internal_data.meta_data = (char *) malloc (libraw_internal_data.unpacker_data.meta_length); merror (libraw_internal_data.internal_data.meta_data, "LibRaw::unpack()"); } libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); int save_iwidth = S.iwidth, save_iheight = S.iheight, save_shrink = IO.shrink; int rwidth = S.raw_width, rheight = S.raw_height; if( !IO.fuji_width) { // adjust non-Fuji allocation if(rwidth < S.width + S.left_margin) rwidth = S.width + S.left_margin; if(rheight < S.height + S.top_margin) rheight = S.height + S.top_margin; } imgdata.rawdata.raw_image = 0; imgdata.rawdata.color4_image = 0; imgdata.rawdata.color3_image = 0; #ifdef USE_RAWSPEED int rawspeed_enabled = 1; if(imgdata.idata.dng_version && libraw_internal_data.unpacker_data.tiff_samples == 2) rawspeed_enabled = 0; // Disable rawspeed for double-sized Oly files if(!strncasecmp(imgdata.idata.make,"Olympus",7) && ( (!strncasecmp(imgdata.idata.model,"E-M5MarkII",10) && imgdata.sizes.raw_width == 9280) || !strncasecmp(imgdata.idata.model,"SH-2",4) || !strncasecmp(imgdata.idata.model,"TG-4",4)) ) rawspeed_enabled = 0; if(!strncasecmp(imgdata.idata.make,"Canon",5) && !strncasecmp(imgdata.idata.model,"EOS 5DS",7) && (load_raw == &LibRaw::canon_sraw_load_raw)) rawspeed_enabled = 0; // RawSpeed Supported, if(O.use_rawspeed && rawspeed_enabled && !(is_sraw() && O.sraw_ycc) && (decoder_info.decoder_flags & LIBRAW_DECODER_TRYRAWSPEED) && _rawspeed_camerameta) { INT64 spos = ID.input->tell(); void *_rawspeed_buffer = 0; try { // printf("Using rawspeed\n"); ID.input->seek(0,SEEK_SET); INT64 _rawspeed_buffer_sz = ID.input->size()+32; _rawspeed_buffer = malloc(_rawspeed_buffer_sz); if(!_rawspeed_buffer) throw LIBRAW_EXCEPTION_ALLOC; ID.input->read(_rawspeed_buffer,_rawspeed_buffer_sz,1); FileMap map((uchar8*)_rawspeed_buffer,_rawspeed_buffer_sz); RawParser t(&map); RawDecoder *d = 0; CameraMetaDataLR *meta = static_cast<CameraMetaDataLR*>(_rawspeed_camerameta); d = t.getDecoder(); if(!d) throw "Unable to find decoder"; try { d->checkSupport(meta); } catch (const RawDecoderException& e) { imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_UNSUPPORTED; throw e; } d->interpolateBadPixels = FALSE; d->applyStage1DngOpcodes = FALSE; _rawspeed_decoder = static_cast<void*>(d); d->decodeRaw(); d->decodeMetaData(meta); RawImage r = d->mRaw; if( r->errors.size()>0) { delete d; _rawspeed_decoder = 0; throw 1; } if (r->isCFA) { imgdata.rawdata.raw_image = (ushort*) r->getDataUncropped(0,0); } else if(r->getCpp()==4) { imgdata.rawdata.color4_image = (ushort(*)[4]) r->getDataUncropped(0,0); if(r->whitePoint > 0 && r->whitePoint < 65536) C.maximum = r->whitePoint; } else if(r->getCpp() == 3) { imgdata.rawdata.color3_image = (ushort(*)[3]) r->getDataUncropped(0,0); if(r->whitePoint > 0 && r->whitePoint < 65536) C.maximum = r->whitePoint; } else { delete d; _rawspeed_decoder = 0; } if(_rawspeed_decoder) { // set sizes iPoint2D rsdim = r->getUncroppedDim(); S.raw_pitch = r->pitch; S.raw_width = rsdim.x; S.raw_height = rsdim.y; //C.maximum = r->whitePoint; fix_after_rawspeed(r->blackLevel); } free(_rawspeed_buffer); _rawspeed_buffer = 0; imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROCESSED; } catch (const RawDecoderException& RDE) { imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROBLEM; if (_rawspeed_buffer) { free(_rawspeed_buffer); _rawspeed_buffer = 0; } const char *p = RDE.what(); if (!strncmp(RDE.what(), "Decoder canceled", strlen("Decoder canceled"))) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; } catch (...) { // We may get here due to cancellation flag imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROBLEM; if(_rawspeed_buffer) { free(_rawspeed_buffer); _rawspeed_buffer = 0; } } ID.input->seek(spos,SEEK_SET); } #endif if(!imgdata.rawdata.raw_image && !imgdata.rawdata.color4_image && !imgdata.rawdata.color3_image) //RawSpeed failed! { // Not allocated on RawSpeed call, try call LibRaw if(decoder_info.decoder_flags & LIBRAW_DECODER_OWNALLOC) { // x3f foveon decoder // Do nothing! Decoder will allocate data internally } else if(imgdata.idata.filters || P1.colors == 1) // Bayer image or single color -> decode to raw_image { imgdata.rawdata.raw_alloc = malloc(rwidth*(rheight+8)*sizeof(imgdata.rawdata.raw_image[0])); imgdata.rawdata.raw_image = (ushort*) imgdata.rawdata.raw_alloc; if(!S.raw_pitch) S.raw_pitch = S.raw_width*2; // Bayer case, not set before } else // NO LEGACY FLAG if (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { // sRAW and old Foveon decoders only, so extra buffer size is just 1/4 S.iwidth = S.width; S.iheight= S.height; IO.shrink = 0; S.raw_pitch = S.width*8; // allocate image as temporary buffer, size imgdata.rawdata.raw_alloc = 0; imgdata.image = (ushort (*)[4]) calloc(S.iwidth*S.iheight,sizeof(*imgdata.image)); } ID.input->seek(libraw_internal_data.unpacker_data.data_offset, SEEK_SET); unsigned m_save = C.maximum; if(load_raw == &LibRaw::unpacked_load_raw && !strcasecmp(imgdata.idata.make,"Nikon")) C.maximum=65535; (this->*load_raw)(); if(load_raw == &LibRaw::unpacked_load_raw && !strcasecmp(imgdata.idata.make,"Nikon")) C.maximum = m_save; if(decoder_info.decoder_flags & LIBRAW_DECODER_OWNALLOC) { // x3f foveon decoder only: do nothing } else if (!(imgdata.idata.filters || P1.colors == 1)) { // successfully decoded legacy image, attach image to raw_alloc imgdata.rawdata.raw_alloc = imgdata.image; imgdata.image = 0; // Restore saved values. Note: Foveon have masked frame // Other 4-color legacy data: no borders S.raw_width = S.width; S.left_margin = 0; S.raw_height = S.height; S.top_margin = 0; } } if(imgdata.rawdata.raw_image) crop_masked_pixels(); // calculate black levels // recover saved if( !(imgdata.idata.filters || P1.colors == 1) && !imgdata.rawdata.color4_image) { imgdata.image = 0; imgdata.rawdata.color4_image = (ushort (*)[4]) imgdata.rawdata.raw_alloc; } // recover image sizes S.iwidth = save_iwidth; S.iheight = save_iheight; IO.shrink = save_shrink; // adjust black to possible maximum unsigned int i = C.cblack[3]; unsigned int c; for(c=0;c<3;c++) if (i > C.cblack[c]) i = C.cblack[c]; for (c=0;c<4;c++) C.cblack[c] -= i; C.black += i; // Save color,sizes and internal data into raw_image fields memmove(&imgdata.rawdata.color,&imgdata.color,sizeof(imgdata.color)); memmove(&imgdata.rawdata.sizes,&imgdata.sizes,sizeof(imgdata.sizes)); memmove(&imgdata.rawdata.iparams,&imgdata.idata,sizeof(imgdata.idata)); memmove(&imgdata.rawdata.ioparams,&libraw_internal_data.internal_output_params,sizeof(libraw_internal_data.internal_output_params)); SET_PROC_FLAG(LIBRAW_PROGRESS_LOAD_RAW); RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW,1,2); return 0; } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } catch (std::exception ee) { EXCEPTION_HANDLER(LIBRAW_EXCEPTION_IO_CORRUPT); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-129'], 'message': 'fixed two more problems found by fuzzer'</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 ldap_encode_response(struct asn1_data *data, struct ldap_Result *result) { asn1_write_enumerated(data, result->resultcode); asn1_write_OctetString(data, result->dn, (result->dn) ? strlen(result->dn) : 0); asn1_write_OctetString(data, result->errormessage, (result->errormessage) ? strlen(result->errormessage) : 0); if (result->referral) { asn1_push_tag(data, ASN1_CONTEXT(3)); asn1_write_OctetString(data, result->referral, strlen(result->referral)); asn1_pop_tag(data); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: s4: libcli: ldap message - Ensure all asn1_XX returns are checked. BUG: https://bugzilla.samba.org/show_bug.cgi?id=9187 Signed-off-by: Jeremy Allison <[email protected]> Reviewed-by: Ronnie Sahlberg <[email protected]> Autobuild-User(master): Jeremy Allison <[email protected]> Autobuild-Date(master): Fri Sep 26 03:15:00 CEST 2014 on sn-devel-104 (cherry picked from commit 69a7e3cfdc8dbba9c8dcfdfae82d2894c7247e15)'</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: _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, const struct ldap_control_handler *control_handlers, struct ldap_message *msg) { uint8_t tag; asn1_start_tag(data, ASN1_SEQUENCE(0)); asn1_read_Integer(data, &msg->messageid); if (!asn1_peek_uint8(data, &tag)) return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); switch(tag) { case ASN1_APPLICATION(LDAP_TAG_BindRequest): { struct ldap_BindRequest *r = &msg->r.BindRequest; msg->type = LDAP_TAG_BindRequest; asn1_start_tag(data, tag); asn1_read_Integer(data, &r->version); asn1_read_OctetString_talloc(msg, data, &r->dn); if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(0))) { int pwlen; r->creds.password = ""; r->mechanism = LDAP_AUTH_MECH_SIMPLE; asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(0)); pwlen = asn1_tag_remaining(data); if (pwlen == -1) { return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } if (pwlen != 0) { char *pw = talloc_array(msg, char, pwlen+1); if (!pw) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } asn1_read(data, pw, pwlen); pw[pwlen] = '\0'; r->creds.password = pw; } asn1_end_tag(data); } else if (asn1_peek_tag(data, ASN1_CONTEXT(3))){ asn1_start_tag(data, ASN1_CONTEXT(3)); r->mechanism = LDAP_AUTH_MECH_SASL; asn1_read_OctetString_talloc(msg, data, &r->creds.SASL.mechanism); if (asn1_peek_tag(data, ASN1_OCTET_STRING)) { /* optional */ DATA_BLOB tmp_blob = data_blob(NULL, 0); asn1_read_OctetString(data, msg, &tmp_blob); r->creds.SASL.secblob = talloc(msg, DATA_BLOB); if (!r->creds.SASL.secblob) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } *r->creds.SASL.secblob = data_blob_talloc(r->creds.SASL.secblob, tmp_blob.data, tmp_blob.length); data_blob_free(&tmp_blob); } else { r->creds.SASL.secblob = NULL; } asn1_end_tag(data); } else { /* Neither Simple nor SASL bind */ return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_BindResponse): { struct ldap_BindResponse *r = &msg->r.BindResponse; msg->type = LDAP_TAG_BindResponse; asn1_start_tag(data, tag); ldap_decode_response(msg, data, &r->response); if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(7))) { DATA_BLOB tmp_blob = data_blob(NULL, 0); asn1_read_ContextSimple(data, 7, &tmp_blob); r->SASL.secblob = talloc(msg, DATA_BLOB); if (!r->SASL.secblob) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } *r->SASL.secblob = data_blob_talloc(r->SASL.secblob, tmp_blob.data, tmp_blob.length); data_blob_free(&tmp_blob); } else { r->SASL.secblob = NULL; } asn1_end_tag(data); break; } case ASN1_APPLICATION_SIMPLE(LDAP_TAG_UnbindRequest): { msg->type = LDAP_TAG_UnbindRequest; asn1_start_tag(data, tag); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_SearchRequest): { struct ldap_SearchRequest *r = &msg->r.SearchRequest; int sizelimit, timelimit; const char **attrs = NULL; msg->type = LDAP_TAG_SearchRequest; asn1_start_tag(data, tag); asn1_read_OctetString_talloc(msg, data, &r->basedn); asn1_read_enumerated(data, (int *)(void *)&(r->scope)); asn1_read_enumerated(data, (int *)(void *)&(r->deref)); asn1_read_Integer(data, &sizelimit); r->sizelimit = sizelimit; asn1_read_Integer(data, &timelimit); r->timelimit = timelimit; asn1_read_BOOLEAN(data, &r->attributesonly); r->tree = ldap_decode_filter_tree(msg, data); if (r->tree == NULL) { return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } asn1_start_tag(data, ASN1_SEQUENCE(0)); r->num_attributes = 0; r->attributes = NULL; while (asn1_tag_remaining(data) > 0) { const char *attr; if (!asn1_read_OctetString_talloc(msg, data, &attr)) return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); if (!add_string_to_array(msg, attr, &attrs, &r->num_attributes)) return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } r->attributes = attrs; asn1_end_tag(data); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_SearchResultEntry): { struct ldap_SearchResEntry *r = &msg->r.SearchResultEntry; msg->type = LDAP_TAG_SearchResultEntry; r->attributes = NULL; r->num_attributes = 0; asn1_start_tag(data, tag); asn1_read_OctetString_talloc(msg, data, &r->dn); ldap_decode_attribs(msg, data, &r->attributes, &r->num_attributes); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_SearchResultDone): { struct ldap_Result *r = &msg->r.SearchResultDone; msg->type = LDAP_TAG_SearchResultDone; asn1_start_tag(data, tag); ldap_decode_response(msg, data, r); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_SearchResultReference): { struct ldap_SearchResRef *r = &msg->r.SearchResultReference; msg->type = LDAP_TAG_SearchResultReference; asn1_start_tag(data, tag); asn1_read_OctetString_talloc(msg, data, &r->referral); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_ModifyRequest): { struct ldap_ModifyRequest *r = &msg->r.ModifyRequest; msg->type = LDAP_TAG_ModifyRequest; asn1_start_tag(data, ASN1_APPLICATION(LDAP_TAG_ModifyRequest)); asn1_read_OctetString_talloc(msg, data, &r->dn); asn1_start_tag(data, ASN1_SEQUENCE(0)); r->num_mods = 0; r->mods = NULL; while (asn1_tag_remaining(data) > 0) { struct ldap_mod mod; int v; ZERO_STRUCT(mod); asn1_start_tag(data, ASN1_SEQUENCE(0)); asn1_read_enumerated(data, &v); mod.type = v; ldap_decode_attrib(msg, data, &mod.attrib); asn1_end_tag(data); if (!add_mod_to_array_talloc(msg, &mod, &r->mods, &r->num_mods)) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } } asn1_end_tag(data); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_ModifyResponse): { struct ldap_Result *r = &msg->r.ModifyResponse; msg->type = LDAP_TAG_ModifyResponse; asn1_start_tag(data, tag); ldap_decode_response(msg, data, r); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_AddRequest): { struct ldap_AddRequest *r = &msg->r.AddRequest; msg->type = LDAP_TAG_AddRequest; asn1_start_tag(data, tag); asn1_read_OctetString_talloc(msg, data, &r->dn); r->attributes = NULL; r->num_attributes = 0; ldap_decode_attribs(msg, data, &r->attributes, &r->num_attributes); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_AddResponse): { struct ldap_Result *r = &msg->r.AddResponse; msg->type = LDAP_TAG_AddResponse; asn1_start_tag(data, tag); ldap_decode_response(msg, data, r); asn1_end_tag(data); break; } case ASN1_APPLICATION_SIMPLE(LDAP_TAG_DelRequest): { struct ldap_DelRequest *r = &msg->r.DelRequest; int len; char *dn; msg->type = LDAP_TAG_DelRequest; asn1_start_tag(data, ASN1_APPLICATION_SIMPLE(LDAP_TAG_DelRequest)); len = asn1_tag_remaining(data); if (len == -1) { return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } dn = talloc_array(msg, char, len+1); if (dn == NULL) break; asn1_read(data, dn, len); dn[len] = '\0'; r->dn = dn; asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_DelResponse): { struct ldap_Result *r = &msg->r.DelResponse; msg->type = LDAP_TAG_DelResponse; asn1_start_tag(data, tag); ldap_decode_response(msg, data, r); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_ModifyDNRequest): { struct ldap_ModifyDNRequest *r = &msg->r.ModifyDNRequest; msg->type = LDAP_TAG_ModifyDNRequest; asn1_start_tag(data, ASN1_APPLICATION(LDAP_TAG_ModifyDNRequest)); asn1_read_OctetString_talloc(msg, data, &r->dn); asn1_read_OctetString_talloc(msg, data, &r->newrdn); asn1_read_BOOLEAN(data, &r->deleteolddn); r->newsuperior = NULL; if (asn1_tag_remaining(data) > 0) { int len; char *newsup; asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(0)); len = asn1_tag_remaining(data); if (len == -1) { return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } newsup = talloc_array(msg, char, len+1); if (newsup == NULL) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } asn1_read(data, newsup, len); newsup[len] = '\0'; r->newsuperior = newsup; asn1_end_tag(data); } asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_ModifyDNResponse): { struct ldap_Result *r = &msg->r.ModifyDNResponse; msg->type = LDAP_TAG_ModifyDNResponse; asn1_start_tag(data, tag); ldap_decode_response(msg, data, r); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_CompareRequest): { struct ldap_CompareRequest *r = &msg->r.CompareRequest; msg->type = LDAP_TAG_CompareRequest; asn1_start_tag(data, ASN1_APPLICATION(LDAP_TAG_CompareRequest)); asn1_read_OctetString_talloc(msg, data, &r->dn); asn1_start_tag(data, ASN1_SEQUENCE(0)); asn1_read_OctetString_talloc(msg, data, &r->attribute); asn1_read_OctetString(data, msg, &r->value); if (r->value.data) { talloc_steal(msg, r->value.data); } asn1_end_tag(data); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_CompareResponse): { struct ldap_Result *r = &msg->r.CompareResponse; msg->type = LDAP_TAG_CompareResponse; asn1_start_tag(data, tag); ldap_decode_response(msg, data, r); asn1_end_tag(data); break; } case ASN1_APPLICATION_SIMPLE(LDAP_TAG_AbandonRequest): { struct ldap_AbandonRequest *r = &msg->r.AbandonRequest; msg->type = LDAP_TAG_AbandonRequest; asn1_start_tag(data, tag); asn1_read_implicit_Integer(data, &r->messageid); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_ExtendedRequest): { struct ldap_ExtendedRequest *r = &msg->r.ExtendedRequest; DATA_BLOB tmp_blob = data_blob(NULL, 0); msg->type = LDAP_TAG_ExtendedRequest; asn1_start_tag(data,tag); if (!asn1_read_ContextSimple(data, 0, &tmp_blob)) { return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } r->oid = blob2string_talloc(msg, tmp_blob); data_blob_free(&tmp_blob); if (!r->oid) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(1))) { asn1_read_ContextSimple(data, 1, &tmp_blob); r->value = talloc(msg, DATA_BLOB); if (!r->value) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } *r->value = data_blob_talloc(r->value, tmp_blob.data, tmp_blob.length); data_blob_free(&tmp_blob); } else { r->value = NULL; } asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_ExtendedResponse): { struct ldap_ExtendedResponse *r = &msg->r.ExtendedResponse; DATA_BLOB tmp_blob = data_blob(NULL, 0); msg->type = LDAP_TAG_ExtendedResponse; asn1_start_tag(data, tag); ldap_decode_response(msg, data, &r->response); if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(10))) { asn1_read_ContextSimple(data, 1, &tmp_blob); r->oid = blob2string_talloc(msg, tmp_blob); data_blob_free(&tmp_blob); if (!r->oid) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } } else { r->oid = NULL; } if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(11))) { asn1_read_ContextSimple(data, 1, &tmp_blob); r->value = talloc(msg, DATA_BLOB); if (!r->value) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } *r->value = data_blob_talloc(r->value, tmp_blob.data, tmp_blob.length); data_blob_free(&tmp_blob); } else { r->value = NULL; } asn1_end_tag(data); break; } default: return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } msg->controls = NULL; msg->controls_decoded = NULL; if (asn1_peek_tag(data, ASN1_CONTEXT(0))) { int i = 0; struct ldb_control **ctrl = NULL; bool *decoded = NULL; asn1_start_tag(data, ASN1_CONTEXT(0)); while (asn1_peek_tag(data, ASN1_SEQUENCE(0))) { DATA_BLOB value; /* asn1_start_tag(data, ASN1_SEQUENCE(0)); */ ctrl = talloc_realloc(msg, ctrl, struct ldb_control *, i+2); if (!ctrl) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } decoded = talloc_realloc(msg, decoded, bool, i+1); if (!decoded) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } ctrl[i] = talloc(ctrl, struct ldb_control); if (!ctrl[i]) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } if (!ldap_decode_control_wrapper(ctrl[i], data, ctrl[i], &value)) { return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } if (!ldap_decode_control_value(ctrl[i], value, control_handlers, ctrl[i])) { if (ctrl[i]->critical) { ctrl[i]->data = NULL; decoded[i] = false; i++; } else { talloc_free(ctrl[i]); ctrl[i] = NULL; } } else { decoded[i] = true; i++; } } if (ctrl != NULL) { ctrl[i] = NULL; } msg->controls = ctrl; msg->controls_decoded = decoded; asn1_end_tag(data); } asn1_end_tag(data); if ((data->has_error) || (data->nesting != NULL)) { return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } return NT_STATUS_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: s4: libcli: ldap message - Ensure all asn1_XX returns are checked. BUG: https://bugzilla.samba.org/show_bug.cgi?id=9187 Signed-off-by: Jeremy Allison <[email protected]> Reviewed-by: Ronnie Sahlberg <[email protected]> Autobuild-User(master): Jeremy Allison <[email protected]> Autobuild-Date(master): Fri Sep 26 03:15:00 CEST 2014 on sn-devel-104 (cherry picked from commit 69a7e3cfdc8dbba9c8dcfdfae82d2894c7247e15)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool decode_openldap_dereference(void *mem_ctx, DATA_BLOB in, void *_out) { void **out = (void **)_out; struct asn1_data *data = asn1_init(mem_ctx); struct dsdb_openldap_dereference_result_control *control; struct dsdb_openldap_dereference_result **r = NULL; int i = 0; if (!data) return false; control = talloc(mem_ctx, struct dsdb_openldap_dereference_result_control); if (!control) return false; if (!asn1_load(data, in)) { return false; } control = talloc(mem_ctx, struct dsdb_openldap_dereference_result_control); if (!control) { return false; } if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) { return false; } while (asn1_tag_remaining(data) > 0) { r = talloc_realloc(control, r, struct dsdb_openldap_dereference_result *, i + 2); if (!r) { return false; } r[i] = talloc_zero(r, struct dsdb_openldap_dereference_result); if (!r[i]) { return false; } if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) { return false; } asn1_read_OctetString_talloc(r[i], data, &r[i]->source_attribute); asn1_read_OctetString_talloc(r[i], data, &r[i]->dereferenced_dn); if (asn1_peek_tag(data, ASN1_CONTEXT(0))) { if (!asn1_start_tag(data, ASN1_CONTEXT(0))) { return false; } ldap_decode_attribs_bare(r, data, &r[i]->attributes, &r[i]->num_attributes); if (!asn1_end_tag(data)) { return false; } } if (!asn1_end_tag(data)) { return false; } i++; r[i] = NULL; } if (!asn1_end_tag(data)) { return false; } control->attributes = r; *out = control; return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: s4: libcli: ldap message - Ensure all asn1_XX returns are checked. BUG: https://bugzilla.samba.org/show_bug.cgi?id=9187 Signed-off-by: Jeremy Allison <[email protected]> Reviewed-by: Ronnie Sahlberg <[email protected]> Autobuild-User(master): Jeremy Allison <[email protected]> Autobuild-Date(master): Fri Sep 26 03:15:00 CEST 2014 on sn-devel-104 (cherry picked from commit 69a7e3cfdc8dbba9c8dcfdfae82d2894c7247e15)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool ldap_push_filter(struct asn1_data *data, struct ldb_parse_tree *tree) { int i; switch (tree->operation) { case LDB_OP_AND: case LDB_OP_OR: asn1_push_tag(data, ASN1_CONTEXT(tree->operation==LDB_OP_AND?0:1)); for (i=0; i<tree->u.list.num_elements; i++) { if (!ldap_push_filter(data, tree->u.list.elements[i])) { return false; } } asn1_pop_tag(data); break; case LDB_OP_NOT: asn1_push_tag(data, ASN1_CONTEXT(2)); if (!ldap_push_filter(data, tree->u.isnot.child)) { return false; } asn1_pop_tag(data); break; case LDB_OP_EQUALITY: /* equality test */ asn1_push_tag(data, ASN1_CONTEXT(3)); asn1_write_OctetString(data, tree->u.equality.attr, strlen(tree->u.equality.attr)); asn1_write_OctetString(data, tree->u.equality.value.data, tree->u.equality.value.length); asn1_pop_tag(data); break; case LDB_OP_SUBSTRING: /* SubstringFilter ::= SEQUENCE { type AttributeDescription, -- at least one must be present substrings SEQUENCE OF CHOICE { initial [0] LDAPString, any [1] LDAPString, final [2] LDAPString } } */ asn1_push_tag(data, ASN1_CONTEXT(4)); asn1_write_OctetString(data, tree->u.substring.attr, strlen(tree->u.substring.attr)); asn1_push_tag(data, ASN1_SEQUENCE(0)); if (tree->u.substring.chunks && tree->u.substring.chunks[0]) { i = 0; if (!tree->u.substring.start_with_wildcard) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0)); asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i]); asn1_pop_tag(data); i++; } while (tree->u.substring.chunks[i]) { int ctx; if (( ! tree->u.substring.chunks[i + 1]) && (tree->u.substring.end_with_wildcard == 0)) { ctx = 2; } else { ctx = 1; } asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(ctx)); asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i]); asn1_pop_tag(data); i++; } } asn1_pop_tag(data); asn1_pop_tag(data); break; case LDB_OP_GREATER: /* greaterOrEqual test */ asn1_push_tag(data, ASN1_CONTEXT(5)); asn1_write_OctetString(data, tree->u.comparison.attr, strlen(tree->u.comparison.attr)); asn1_write_OctetString(data, tree->u.comparison.value.data, tree->u.comparison.value.length); asn1_pop_tag(data); break; case LDB_OP_LESS: /* lessOrEqual test */ asn1_push_tag(data, ASN1_CONTEXT(6)); asn1_write_OctetString(data, tree->u.comparison.attr, strlen(tree->u.comparison.attr)); asn1_write_OctetString(data, tree->u.comparison.value.data, tree->u.comparison.value.length); asn1_pop_tag(data); break; case LDB_OP_PRESENT: /* present test */ asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(7)); asn1_write_LDAPString(data, tree->u.present.attr); asn1_pop_tag(data); return !data->has_error; case LDB_OP_APPROX: /* approx test */ asn1_push_tag(data, ASN1_CONTEXT(8)); asn1_write_OctetString(data, tree->u.comparison.attr, strlen(tree->u.comparison.attr)); asn1_write_OctetString(data, tree->u.comparison.value.data, tree->u.comparison.value.length); asn1_pop_tag(data); break; case LDB_OP_EXTENDED: /* MatchingRuleAssertion ::= SEQUENCE { matchingRule [1] MatchingRuleID OPTIONAL, type [2] AttributeDescription OPTIONAL, matchValue [3] AssertionValue, dnAttributes [4] BOOLEAN DEFAULT FALSE } */ asn1_push_tag(data, ASN1_CONTEXT(9)); if (tree->u.extended.rule_id) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1)); asn1_write_LDAPString(data, tree->u.extended.rule_id); asn1_pop_tag(data); } if (tree->u.extended.attr) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(2)); asn1_write_LDAPString(data, tree->u.extended.attr); asn1_pop_tag(data); } asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(3)); asn1_write_DATA_BLOB_LDAPString(data, &tree->u.extended.value); asn1_pop_tag(data); asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(4)); asn1_write_uint8(data, tree->u.extended.dnAttributes); asn1_pop_tag(data); asn1_pop_tag(data); break; default: return false; } return !data->has_error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: s4: libcli: ldap message - Ensure all asn1_XX returns are checked. BUG: https://bugzilla.samba.org/show_bug.cgi?id=9187 Signed-off-by: Jeremy Allison <[email protected]> Reviewed-by: Ronnie Sahlberg <[email protected]> Autobuild-User(master): Jeremy Allison <[email protected]> Autobuild-Date(master): Fri Sep 26 03:15:00 CEST 2014 on sn-devel-104 (cherry picked from commit 69a7e3cfdc8dbba9c8dcfdfae82d2894c7247e15)'</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 ldap_decode_response(TALLOC_CTX *mem_ctx, struct asn1_data *data, struct ldap_Result *result) { asn1_read_enumerated(data, &result->resultcode); asn1_read_OctetString_talloc(mem_ctx, data, &result->dn); asn1_read_OctetString_talloc(mem_ctx, data, &result->errormessage); if (asn1_peek_tag(data, ASN1_CONTEXT(3))) { asn1_start_tag(data, ASN1_CONTEXT(3)); asn1_read_OctetString_talloc(mem_ctx, data, &result->referral); asn1_end_tag(data); } else { result->referral = NULL; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: s4: libcli: ldap message - Ensure all asn1_XX returns are checked. BUG: https://bugzilla.samba.org/show_bug.cgi?id=9187 Signed-off-by: Jeremy Allison <[email protected]> Reviewed-by: Ronnie Sahlberg <[email protected]> Autobuild-User(master): Jeremy Allison <[email protected]> Autobuild-Date(master): Fri Sep 26 03:15:00 CEST 2014 on sn-devel-104 (cherry picked from commit 69a7e3cfdc8dbba9c8dcfdfae82d2894c7247e15)'</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 asn1_write_OctetString(struct asn1_data *data, const void *p, size_t length) { asn1_push_tag(data, ASN1_OCTET_STRING); asn1_write(data, p, length); asn1_pop_tag(data); return !data->has_error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: lib: util: Check *every* asn1 return call and early return. BUG: https://bugzilla.samba.org/show_bug.cgi?id=9187 Signed-off-by: Jeremy Allison <[email protected]> Reviewed-by: Volker Lendecke <[email protected]> Autobuild-User(master): Jeremy Allison <[email protected]> Autobuild-Date(master): Fri Sep 19 01:29:00 CEST 2014 on sn-devel-104 (cherry picked from commit b9d3fd4cc551df78a7b066ee8ce43bbaa3ff994a)'</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 asn1_write_LDAPString(struct asn1_data *data, const char *s) { asn1_write(data, s, strlen(s)); return !data->has_error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: lib: util: Check *every* asn1 return call and early return. BUG: https://bugzilla.samba.org/show_bug.cgi?id=9187 Signed-off-by: Jeremy Allison <[email protected]> Reviewed-by: Volker Lendecke <[email protected]> Autobuild-User(master): Jeremy Allison <[email protected]> Autobuild-Date(master): Fri Sep 19 01:29:00 CEST 2014 on sn-devel-104 (cherry picked from commit b9d3fd4cc551df78a7b066ee8ce43bbaa3ff994a)'</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 asn1_check_BOOLEAN(struct asn1_data *data, bool v) { uint8_t b = 0; asn1_read_uint8(data, &b); if (b != ASN1_BOOLEAN) { data->has_error = true; return false; } asn1_read_uint8(data, &b); if (b != v) { data->has_error = true; return false; } return !data->has_error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: lib: util: Check *every* asn1 return call and early return. BUG: https://bugzilla.samba.org/show_bug.cgi?id=9187 Signed-off-by: Jeremy Allison <[email protected]> Reviewed-by: Volker Lendecke <[email protected]> Autobuild-User(master): Jeremy Allison <[email protected]> Autobuild-Date(master): Fri Sep 19 01:29:00 CEST 2014 on sn-devel-104 (cherry picked from commit b9d3fd4cc551df78a7b066ee8ce43bbaa3ff994a)'</s>