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: int LibRaw::unpack(void) { CHECK_ORDER_HIGH(LIBRAW_PROGRESS_LOAD_RAW); CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); try { 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; if (O.use_camera_matrix && C.cmatrix[0][0] > 0.25) { memcpy (C.rgb_cam, C.cmatrix, sizeof (C.cmatrix)); IO.raw_color = 0; } // already allocated ? if(imgdata.image) { free(imgdata.image); imgdata.image = 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()"); } ID.input->seek(libraw_internal_data.unpacker_data.data_offset, SEEK_SET); int save_document_mode = O.document_mode; O.document_mode = 0; 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; } if(decoder_info.decoder_flags & LIBRAW_DECODER_FLATFIELD) { imgdata.rawdata.raw_alloc = malloc(rwidth*rheight*sizeof(imgdata.rawdata.raw_image[0])); imgdata.rawdata.raw_image = (ushort*) imgdata.rawdata.raw_alloc; } else if (decoder_info.decoder_flags & LIBRAW_DECODER_4COMPONENT) { S.iwidth = S.width; S.iheight= S.height; IO.shrink = 0; imgdata.rawdata.raw_alloc = calloc(rwidth*rheight,sizeof(*imgdata.rawdata.color_image)); imgdata.rawdata.color_image = (ushort(*)[4]) imgdata.rawdata.raw_alloc; } else if (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { // sRAW and Foveon only, so extra buffer size is just 1/4 // Legacy converters does not supports half mode! S.iwidth = S.width; S.iheight= S.height; IO.shrink = 0; // allocate image as temporary buffer, size imgdata.rawdata.raw_alloc = calloc(S.iwidth*S.iheight,sizeof(*imgdata.image)); imgdata.image = (ushort (*)[4]) imgdata.rawdata.raw_alloc; } (this->*load_raw)(); // recover saved if( decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { imgdata.image = 0; imgdata.rawdata.color_image = (ushort (*)[4]) imgdata.rawdata.raw_alloc; } // calculate channel maximum { for(int c=0;c<4;c++) C.channel_maximum[c] = 0; if(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { for(int rc = 0; rc < S.iwidth*S.iheight; rc++) { if(C.channel_maximum[0]<imgdata.rawdata.color_image[rc][0]) C.channel_maximum[0]=imgdata.rawdata.color_image[rc][0]; if(C.channel_maximum[1]<imgdata.rawdata.color_image[rc][1]) C.channel_maximum[1]=imgdata.rawdata.color_image[rc][1]; if(C.channel_maximum[2]<imgdata.rawdata.color_image[rc][2]) C.channel_maximum[2]=imgdata.rawdata.color_image[rc][2]; if(C.channel_maximum[3]<imgdata.rawdata.color_image[rc][3]) C.channel_maximum[3]=imgdata.rawdata.color_image[rc][3]; } } else if(decoder_info.decoder_flags & LIBRAW_DECODER_4COMPONENT) { for(int row = S.top_margin; row < S.height+S.top_margin; row++) for(int col = S.left_margin; col < S.width+S.left_margin; col++) { int rc = row*S.raw_width+col; if(C.channel_maximum[0]<imgdata.rawdata.color_image[rc][0]) C.channel_maximum[0]=imgdata.rawdata.color_image[rc][0]; if(C.channel_maximum[1]<imgdata.rawdata.color_image[rc][1]) C.channel_maximum[1]=imgdata.rawdata.color_image[rc][1]; if(C.channel_maximum[2]<imgdata.rawdata.color_image[rc][2]) C.channel_maximum[2]=imgdata.rawdata.color_image[rc][2]; if(C.channel_maximum[3]<imgdata.rawdata.color_image[rc][3]) C.channel_maximum[3]=imgdata.rawdata.color_image[rc][4]; } } else if (decoder_info.decoder_flags & LIBRAW_DECODER_FLATFIELD) { for(int row = 0; row < S.height; row++) { int colors[4]; for (int xx=0;xx<4;xx++) colors[xx] = COLOR(row,xx); for(int col = 0; col < S.width; col++) { int cc = colors[col&3]; if(C.channel_maximum[cc] < imgdata.rawdata.raw_image[(row+S.top_margin)*S.raw_width +(col+S.left_margin)]) C.channel_maximum[cc] = imgdata.rawdata.raw_image[(row+S.top_margin)*S.raw_width +(col+S.left_margin)]; } } } } // recover image sizes S.iwidth = save_iwidth; S.iheight = save_iheight; IO.shrink = save_shrink; // phase-one black if(imgdata.rawdata.ph1_black) C.ph1_black = imgdata.rawdata.ph1_black; O.document_mode = save_document_mode; // 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-399'], 'message': 'fixed error handling for broken full-color images'</s>
<s>[INST] Given the following code containing errors, provide 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 b43_request_firmware(struct work_struct *work) { struct b43_wl *wl = container_of(work, struct b43_wl, firmware_load); struct b43_wldev *dev = wl->current_dev; struct b43_request_fw_context *ctx; unsigned int i; int err; const char *errmsg; ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) return; ctx->dev = dev; ctx->req_type = B43_FWTYPE_PROPRIETARY; err = b43_try_request_fw(ctx); if (!err) goto start_ieee80211; /* Successfully loaded it. */ /* Was fw version known? */ if (ctx->fatal_failure) goto out; /* proprietary fw not found, try open source */ ctx->req_type = B43_FWTYPE_OPENSOURCE; err = b43_try_request_fw(ctx); if (!err) goto start_ieee80211; /* Successfully loaded it. */ if(ctx->fatal_failure) goto out; /* Could not find a usable firmware. Print the errors. */ for (i = 0; i < B43_NR_FWTYPES; i++) { errmsg = ctx->errors[i]; if (strlen(errmsg)) b43err(dev->wl, errmsg); } b43_print_fw_helptext(dev->wl, 1); goto out; start_ieee80211: wl->hw->queues = B43_QOS_QUEUE_NUM; if (!modparam_qos || dev->fw.opensource) wl->hw->queues = 1; err = ieee80211_register_hw(wl->hw); if (err) goto err_one_core_detach; wl->hw_registred = true; b43_leds_register(wl->current_dev); goto out; err_one_core_detach: b43_one_core_detach(dev->dev); out: kfree(ctx); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'b43: stop format string leaking into error msgs The module parameter "fwpostfix" is userspace controllable, unfiltered, and is used to define the firmware filename. b43_do_request_fw() populates ctx->errors[] on error, containing the firmware filename. b43err() parses its arguments as a format string. For systems with b43 hardware, this could lead to a uid-0 to ring-0 escalation. CVE-2013-2852 Signed-off-by: Kees Cook <[email protected]> Cc: [email protected] Signed-off-by: John W. Linville <[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: zend_op_array *compile_string(zval *source_string, char *filename TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval; zval tmp; int compiler_result; zend_bool original_in_compilation = CG(in_compilation); if (source_string->value.str.len==0) { efree(op_array); return NULL; } CG(in_compilation) = 1; tmp = *source_string; zval_copy_ctor(&tmp); convert_to_string(&tmp); source_string = &tmp; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(source_string, filename TSRMLS_CC)==FAILURE) { efree(op_array); retval = NULL; } else { zend_bool orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(op_array, ZEND_EVAL_CODE, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; CG(active_op_array) = op_array; zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); BEGIN(ST_IN_SCRIPTING); compiler_result = zendparse(TSRMLS_C); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } if (compiler_result==1) { CG(active_op_array) = original_active_op_array; CG(unclean_shutdown)=1; destroy_op_array(op_array TSRMLS_CC); efree(op_array); retval = NULL; } else { zend_do_return(NULL, 0 TSRMLS_CC); CG(active_op_array) = original_active_op_array; pass_two(op_array TSRMLS_CC); zend_release_labels(0 TSRMLS_CC); retval = op_array; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(&tmp); CG(in_compilation) = original_in_compilation; return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'fix bug #64660 - yyparse can return 2, not only 1'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gpg_ctx_add_recipient (struct _GpgCtx *gpg, const gchar *keyid) { if (gpg->mode != GPG_CTX_MODE_ENCRYPT && gpg->mode != GPG_CTX_MODE_EXPORT) return; if (!gpg->recipients) gpg->recipients = g_ptr_array_new (); g_ptr_array_add (gpg->recipients, g_strdup (keyid)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CamelGpgContext: Enclose email addresses in brackets. The recipient list for encrypting can be specified by either key ID or email address. Enclose email addresses in brackets to ensure an exact match, as per the gpg man page: HOW TO SPECIFY A USER ID ... By exact match on an email address. This is indicated by enclosing the email address in the usual way with left and right angles. <[email protected]> Without the brackets gpg uses a substring match, which risks selecting the wrong recipient.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: private int mget(struct magic_set *ms, const unsigned char *s, struct magic *m, size_t nbytes, size_t o, unsigned int cont_level, int mode, int text, int flip, int recursion_level, int *printed_something, int *need_separator, int *returnval) { uint32_t soffset, offset = ms->offset; uint32_t count = m->str_range; int rv, oneed_separator; char *sbuf, *rbuf; union VALUETYPE *p = &ms->ms_value; struct mlist ml; if (recursion_level >= 20) { file_error(ms, 0, "recursion nesting exceeded"); return -1; } if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o), (uint32_t)nbytes, count) == -1) return -1; if ((ms->flags & MAGIC_DEBUG) != 0) { fprintf(stderr, "mget(type=%d, flag=%x, offset=%u, o=%zu, " "nbytes=%zu, count=%u)\n", m->type, m->flag, offset, o, nbytes, count); mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE)); } if (m->flag & INDIR) { int off = m->in_offset; if (m->in_op & FILE_OPINDIRECT) { const union VALUETYPE *q = CAST(const union VALUETYPE *, ((const void *)(s + offset + off))); switch (cvt_flip(m->in_type, flip)) { case FILE_BYTE: off = q->b; break; case FILE_SHORT: off = q->h; break; case FILE_BESHORT: off = (short)((q->hs[0]<<8)|(q->hs[1])); break; case FILE_LESHORT: off = (short)((q->hs[1]<<8)|(q->hs[0])); break; case FILE_LONG: off = q->l; break; case FILE_BELONG: case FILE_BEID3: off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)| (q->hl[2]<<8)|(q->hl[3])); break; case FILE_LEID3: case FILE_LELONG: off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)| (q->hl[1]<<8)|(q->hl[0])); break; case FILE_MELONG: off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)| (q->hl[3]<<8)|(q->hl[2])); break; } if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect offs=%u\n", off); } switch (cvt_flip(m->in_type, flip)) { case FILE_BYTE: if (nbytes < (offset + 1)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->b & off; break; case FILE_OPOR: offset = p->b | off; break; case FILE_OPXOR: offset = p->b ^ off; break; case FILE_OPADD: offset = p->b + off; break; case FILE_OPMINUS: offset = p->b - off; break; case FILE_OPMULTIPLY: offset = p->b * off; break; case FILE_OPDIVIDE: offset = p->b / off; break; case FILE_OPMODULO: offset = p->b % off; break; } } else offset = p->b; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_BESHORT: if (nbytes < (offset + 2)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (short)((p->hs[0]<<8)| (p->hs[1])) & off; break; case FILE_OPOR: offset = (short)((p->hs[0]<<8)| (p->hs[1])) | off; break; case FILE_OPXOR: offset = (short)((p->hs[0]<<8)| (p->hs[1])) ^ off; break; case FILE_OPADD: offset = (short)((p->hs[0]<<8)| (p->hs[1])) + off; break; case FILE_OPMINUS: offset = (short)((p->hs[0]<<8)| (p->hs[1])) - off; break; case FILE_OPMULTIPLY: offset = (short)((p->hs[0]<<8)| (p->hs[1])) * off; break; case FILE_OPDIVIDE: offset = (short)((p->hs[0]<<8)| (p->hs[1])) / off; break; case FILE_OPMODULO: offset = (short)((p->hs[0]<<8)| (p->hs[1])) % off; break; } } else offset = (short)((p->hs[0]<<8)| (p->hs[1])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LESHORT: if (nbytes < (offset + 2)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (short)((p->hs[1]<<8)| (p->hs[0])) & off; break; case FILE_OPOR: offset = (short)((p->hs[1]<<8)| (p->hs[0])) | off; break; case FILE_OPXOR: offset = (short)((p->hs[1]<<8)| (p->hs[0])) ^ off; break; case FILE_OPADD: offset = (short)((p->hs[1]<<8)| (p->hs[0])) + off; break; case FILE_OPMINUS: offset = (short)((p->hs[1]<<8)| (p->hs[0])) - off; break; case FILE_OPMULTIPLY: offset = (short)((p->hs[1]<<8)| (p->hs[0])) * off; break; case FILE_OPDIVIDE: offset = (short)((p->hs[1]<<8)| (p->hs[0])) / off; break; case FILE_OPMODULO: offset = (short)((p->hs[1]<<8)| (p->hs[0])) % off; break; } } else offset = (short)((p->hs[1]<<8)| (p->hs[0])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_SHORT: if (nbytes < (offset + 2)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->h & off; break; case FILE_OPOR: offset = p->h | off; break; case FILE_OPXOR: offset = p->h ^ off; break; case FILE_OPADD: offset = p->h + off; break; case FILE_OPMINUS: offset = p->h - off; break; case FILE_OPMULTIPLY: offset = p->h * off; break; case FILE_OPDIVIDE: offset = p->h / off; break; case FILE_OPMODULO: offset = p->h % off; break; } } else offset = p->h; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_BELONG: case FILE_BEID3: if (nbytes < (offset + 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) & off; break; case FILE_OPOR: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) | off; break; case FILE_OPXOR: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) ^ off; break; case FILE_OPADD: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) + off; break; case FILE_OPMINUS: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) - off; break; case FILE_OPMULTIPLY: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) * off; break; case FILE_OPDIVIDE: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) / off; break; case FILE_OPMODULO: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) % off; break; } } else offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LELONG: case FILE_LEID3: if (nbytes < (offset + 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) & off; break; case FILE_OPOR: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) | off; break; case FILE_OPXOR: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) ^ off; break; case FILE_OPADD: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) + off; break; case FILE_OPMINUS: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) - off; break; case FILE_OPMULTIPLY: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) * off; break; case FILE_OPDIVIDE: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) / off; break; case FILE_OPMODULO: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) % off; break; } } else offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_MELONG: if (nbytes < (offset + 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) & off; break; case FILE_OPOR: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) | off; break; case FILE_OPXOR: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) ^ off; break; case FILE_OPADD: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) + off; break; case FILE_OPMINUS: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) - off; break; case FILE_OPMULTIPLY: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) * off; break; case FILE_OPDIVIDE: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) / off; break; case FILE_OPMODULO: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) % off; break; } } else offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LONG: if (nbytes < (offset + 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->l & off; break; case FILE_OPOR: offset = p->l | off; break; case FILE_OPXOR: offset = p->l ^ off; break; case FILE_OPADD: offset = p->l + off; break; case FILE_OPMINUS: offset = p->l - off; break; case FILE_OPMULTIPLY: offset = p->l * off; break; case FILE_OPDIVIDE: offset = p->l / off; break; case FILE_OPMODULO: offset = p->l % off; break; } } else offset = p->l; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; } switch (cvt_flip(m->in_type, flip)) { case FILE_LEID3: case FILE_BEID3: offset = ((((offset >> 0) & 0x7f) << 0) | (((offset >> 8) & 0x7f) << 7) | (((offset >> 16) & 0x7f) << 14) | (((offset >> 24) & 0x7f) << 21)) + 10; break; default: break; } if (m->flag & INDIROFFADD) { offset += ms->c.li[cont_level-1].off; if (offset == 0) { if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect *zero* offset\n"); return 0; } if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect +offs=%u\n", offset); } if (mcopy(ms, p, m->type, 0, s, offset, nbytes, count) == -1) return -1; ms->offset = offset; if ((ms->flags & MAGIC_DEBUG) != 0) { mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE)); } } /* Verify we have enough data to match magic type */ switch (m->type) { case FILE_BYTE: if (nbytes < (offset + 1)) /* should alway be true */ return 0; break; case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: if (nbytes < (offset + 2)) return 0; break; case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: if (nbytes < (offset + 4)) return 0; break; case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: if (nbytes < (offset + 8)) return 0; break; case FILE_STRING: case FILE_PSTRING: case FILE_SEARCH: if (nbytes < (offset + m->vallen)) return 0; break; case FILE_REGEX: if (nbytes < offset) return 0; break; case FILE_INDIRECT: if (nbytes < offset) return 0; sbuf = ms->o.buf; soffset = ms->offset; ms->o.buf = NULL; ms->offset = 0; rv = file_softmagic(ms, s + offset, nbytes - offset, BINTEST, text); if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect @offs=%u[%d]\n", offset, rv); rbuf = ms->o.buf; ms->o.buf = sbuf; ms->offset = soffset; if (rv == 1) { if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 && file_printf(ms, m->desc, offset) == -1) return -1; if (file_printf(ms, "%s", rbuf) == -1) return -1; free(rbuf); } return rv; case FILE_USE: if (nbytes < offset) return 0; sbuf = m->value.s; if (*sbuf == '^') { sbuf++; flip = !flip; } if (file_magicfind(ms, sbuf, &ml) == -1) { file_error(ms, 0, "cannot find entry `%s'", sbuf); return -1; } oneed_separator = *need_separator; if (m->flag & NOSPACE) *need_separator = 0; rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o, mode, text, flip, recursion_level, printed_something, need_separator, returnval); if (rv != 1) *need_separator = oneed_separator; return rv; case FILE_NAME: if (file_printf(ms, "%s", m->desc) == -1) return -1; return 1; case FILE_DEFAULT: /* nothing to check */ default: break; } if (!mconvert(ms, m, flip)) return 0; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #64830 mimetype detection segfaults on mp3 file'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ZrtpPacketHello::ZrtpPacketHello(uint8_t *data) { DEBUGOUT((fprintf(stdout, "Creating Hello packet from data\n"))); zrtpHeader = (zrtpPacketHeader_t *)&((HelloPacket_t *)data)->hdr; // the standard header helloHeader = (Hello_t *)&((HelloPacket_t *)data)->hello; uint32_t t = *((uint32_t*)&helloHeader->flags); uint32_t temp = zrtpNtohl(t); nHash = (temp & (0xf << 16)) >> 16; nCipher = (temp & (0xf << 12)) >> 12; nAuth = (temp & (0xf << 8)) >> 8; nPubkey = (temp & (0xf << 4)) >> 4; nSas = temp & 0xf; // +2 : the MAC at the end of the packet computedLength = nHash + nCipher + nAuth + nPubkey + nSas + sizeof(HelloPacket_t)/ZRTP_WORD_SIZE + 2; oHash = sizeof(Hello_t); oCipher = oHash + (nHash * ZRTP_WORD_SIZE); oAuth = oCipher + (nCipher * ZRTP_WORD_SIZE); oPubkey = oAuth + (nAuth * ZRTP_WORD_SIZE); oSas = oPubkey + (nPubkey * ZRTP_WORD_SIZE); oHmac = oSas + (nSas * ZRTP_WORD_SIZE); // offset to HMAC } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix vulnerabilities found and reported by Mark Dowd - limit length of memcpy - limit number of offered algorithms in Hello packet - length check in PING packet - fix a small coding 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: AlgorithmEnum* ZRtp::findBestSASType(ZrtpPacketHello *hello) { int i; int ii; int numAlgosOffered; AlgorithmEnum* algosOffered[ZrtpConfigure::maxNoOfAlgos+1]; int numAlgosConf; AlgorithmEnum* algosConf[ZrtpConfigure::maxNoOfAlgos+1]; int num = hello->getNumSas(); if (num == 0) { return &zrtpSasTypes.getByName(mandatorySasType); } // Buildlist of configured SAS algorithm names numAlgosConf = configureAlgos.getNumConfiguredAlgos(SasType); for (i = 0; i < numAlgosConf; i++) { algosConf[i] = &configureAlgos.getAlgoAt(SasType, i); } // Build list of offered known algos in Hello, for (numAlgosOffered = 0, i = 0; i < num; i++) { algosOffered[numAlgosOffered] = &zrtpSasTypes.getByName((const char*)hello->getSasType(i++)); if (!algosOffered[numAlgosOffered]->isValid()) continue; numAlgosOffered++; } // Lookup offered algos in configured algos. Prefer algorithms that appear first in Hello packet (offered). for (i = 0; i < numAlgosOffered; i++) { for (ii = 0; ii < numAlgosConf; ii++) { if (*(int32_t*)(algosOffered[i]->getName()) == *(int32_t*)(algosConf[ii]->getName())) { return algosConf[ii]; } } } // If we don't have a match - use the mandatory algorithm return &zrtpSasTypes.getByName(mandatorySasType); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix vulnerabilities found and reported by Mark Dowd - limit length of memcpy - limit number of offered algorithms in Hello packet - length check in PING packet - fix a small coding 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: ZrtpPacketPingAck* ZRtp::preparePingAck(ZrtpPacketPing* ppkt) { // Because we do not support ZRTP proxy mode use the truncated ZID. // If this code shall be used in ZRTP proxy implementation the computation // of the endpoint hash must be enhanced (see chaps 5.15ff and 5.16) zrtpPingAck.setLocalEpHash(ownZid); zrtpPingAck.setRemoteEpHash(ppkt->getEpHash()); zrtpPingAck.setSSRC(peerSSRC); return &zrtpPingAck; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix vulnerabilities found and reported by Mark Dowd - limit length of memcpy - limit number of offered algorithms in Hello packet - length check in PING packet - fix a small coding 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: new_msg_lsa_change_notify (u_char msgtype, u_int32_t seqnum, struct in_addr ifaddr, struct in_addr area_id, u_char is_self_originated, struct lsa_header *data) { u_char buf[OSPF_API_MAX_MSG_SIZE]; struct msg_lsa_change_notify *nmsg; int len; assert (data); nmsg = (struct msg_lsa_change_notify *) buf; len = ntohs (data->length) + sizeof (struct msg_lsa_change_notify) - sizeof (struct lsa_header); nmsg->ifaddr = ifaddr; nmsg->area_id = area_id; nmsg->is_self_originated = is_self_originated; memset (&nmsg->pad, 0, sizeof (nmsg->pad)); memcpy (&nmsg->data, data, ntohs (data->length)); return msg_new (msgtype, nmsg, seqnum, len); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'ospfd: CVE-2013-2236, stack overrun in apiserver the OSPF API-server (exporting the LSDB and allowing announcement of Opaque-LSAs) writes past the end of fixed on-stack buffers. This leads to an exploitable stack overflow. For this condition to occur, the following two conditions must be true: - Quagga is configured with --enable-opaque-lsa - ospfd is started with the "-a" command line option If either of these does not hold, the relevant code is not executed and the issue does not get triggered. Since the issue occurs on receiving large LSAs (larger than 1488 bytes), it is possible for this to happen during normal operation of a network. In particular, if there is an OSPF router with a large number of interfaces, the Router-LSA of that router may exceed 1488 bytes and trigger this, leading to an ospfd crash. For an attacker to exploit this, s/he must be able to inject valid LSAs into the OSPF domain. Any best-practice protection measure (using crypto authentication, restricting OSPF to internal interfaces, packet filtering protocol 89, etc.) will prevent exploitation. On top of that, remote (not on an OSPF-speaking network segment) attackers will have difficulties bringing up the adjacency needed to inject a LSA. This patch only performs minimal changes to remove the possibility of a stack overrun. The OSPF API in general is quite ugly and needs a rewrite. Reported-by: Ricky Charlet <[email protected]> Cc: Florian Weimer <[email protected]> Signed-off-by: David Lamparter <[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: new_msg_register_event (u_int32_t seqnum, struct lsa_filter_type *filter) { u_char buf[OSPF_API_MAX_MSG_SIZE]; struct msg_register_event *emsg; int len; emsg = (struct msg_register_event *) buf; len = sizeof (struct msg_register_event) + filter->num_areas * sizeof (struct in_addr); emsg->filter.typemask = htons (filter->typemask); emsg->filter.origin = filter->origin; emsg->filter.num_areas = filter->num_areas; return msg_new (MSG_REGISTER_EVENT, emsg, seqnum, len); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'ospfd: CVE-2013-2236, stack overrun in apiserver the OSPF API-server (exporting the LSDB and allowing announcement of Opaque-LSAs) writes past the end of fixed on-stack buffers. This leads to an exploitable stack overflow. For this condition to occur, the following two conditions must be true: - Quagga is configured with --enable-opaque-lsa - ospfd is started with the "-a" command line option If either of these does not hold, the relevant code is not executed and the issue does not get triggered. Since the issue occurs on receiving large LSAs (larger than 1488 bytes), it is possible for this to happen during normal operation of a network. In particular, if there is an OSPF router with a large number of interfaces, the Router-LSA of that router may exceed 1488 bytes and trigger this, leading to an ospfd crash. For an attacker to exploit this, s/he must be able to inject valid LSAs into the OSPF domain. Any best-practice protection measure (using crypto authentication, restricting OSPF to internal interfaces, packet filtering protocol 89, etc.) will prevent exploitation. On top of that, remote (not on an OSPF-speaking network segment) attackers will have difficulties bringing up the adjacency needed to inject a LSA. This patch only performs minimal changes to remove the possibility of a stack overrun. The OSPF API in general is quite ugly and needs a rewrite. Reported-by: Ricky Charlet <[email protected]> Cc: Florian Weimer <[email protected]> Signed-off-by: David Lamparter <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Status AuthorizationManager::acquirePrivilegesFromPrivilegeDocument( const std::string& dbname, const PrincipalName& principal, const BSONObj& privilegeDocument) { if (!_authenticatedPrincipals.lookup(principal)) { return Status(ErrorCodes::UserNotFound, mongoutils::str::stream() << "No authenticated principle found with name: " << principal.getUser() << " from database " << principal.getDB(), 0); } if (principal.getUser() == internalSecurity.user) { // Grant full access to internal user ActionSet allActions; allActions.addAllActions(); return acquirePrivilege(Privilege(PrivilegeSet::WILDCARD_RESOURCE, allActions), principal); } return buildPrivilegeSet(dbname, principal, privilegeDocument, &_acquiredPrivileges); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'SERVER-9983 Do not needlessly lock when looking up privileges for the __system@local user. Uncorrected, this can cause replica set heartbeats to stall behind operations that hold the read lock for a long time.'</s>
<s>[INST] Given the following code containing errors, provide 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 AuthorizationSession::addAuthorizedPrincipal(Principal* principal) { // Log out any already-logged-in user on the same database as "principal". logoutDatabase(principal->getName().getDB().toString()); // See SERVER-8144. _authenticatedPrincipals.add(principal); if (!principal->isImplicitPrivilegeAcquisitionEnabled()) return; _acquirePrivilegesForPrincipalFromDatabase(ADMIN_DBNAME, principal->getName()); principal->markDatabaseAsProbed(ADMIN_DBNAME); const std::string dbname = principal->getName().getDB().toString(); _acquirePrivilegesForPrincipalFromDatabase(dbname, principal->getName()); principal->markDatabaseAsProbed(dbname); _externalState->onAddAuthorizedPrincipal(principal); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'SERVER-9983 Do not needlessly lock when looking up privileges for the __system@local user. Uncorrected, this can cause replica set heartbeats to stall behind operations that hold the read lock for a long time.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _fr_window_ask_overwrite_dialog (OverwriteData *odata) { if ((odata->edata->overwrite == FR_OVERWRITE_ASK) && (odata->current_file != NULL)) { const char *base_name; GFile *destination; base_name = _g_path_get_relative_basename ((char *) odata->current_file->data, odata->edata->base_dir, odata->edata->junk_paths); destination = g_file_get_child (odata->edata->destination, base_name); g_file_query_info_async (destination, G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_STANDARD_NAME "," G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, G_PRIORITY_DEFAULT, odata->window->priv->cancellable, query_info_ready_for_overwrite_dialog_cb, odata); g_object_unref (destination); return; } if (odata->edata->file_list != NULL) { /* speed optimization: passing NULL when extracting all the * files is faster if the command supports the * propCanExtractAll property. */ if (odata->extract_all) { _g_string_list_free (odata->edata->file_list); odata->edata->file_list = NULL; } odata->edata->overwrite = FR_OVERWRITE_YES; _fr_window_archive_extract_from_edata (odata->window, odata->edata); } else { GtkWidget *d; d = _gtk_message_dialog_new (GTK_WINDOW (odata->window), 0, GTK_STOCK_DIALOG_WARNING, _("Extraction not performed"), NULL, GTK_STOCK_OK, GTK_RESPONSE_OK, NULL); gtk_dialog_set_default_response (GTK_DIALOG (d), GTK_RESPONSE_OK); fr_window_show_error_dialog (odata->window, d, GTK_WINDOW (odata->window), _("Extraction not performed")); fr_window_stop_batch (odata->window); } g_free (odata); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'libarchive: sanitize filenames before extracting'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: writeDataError(instanceData *pData, cJSON **pReplyRoot, uchar *reqmsg) { char *rendered = NULL; cJSON *errRoot; cJSON *req; cJSON *replyRoot = *pReplyRoot; size_t toWrite; ssize_t wrRet; char errStr[1024]; DEFiRet; if(pData->errorFile == NULL) { DBGPRINTF("omelasticsearch: no local error logger defined - " "ignoring ES error information\n"); FINALIZE; } if(pData->fdErrFile == -1) { pData->fdErrFile = open((char*)pData->errorFile, O_WRONLY|O_CREAT|O_APPEND|O_LARGEFILE|O_CLOEXEC, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP); if(pData->fdErrFile == -1) { rs_strerror_r(errno, errStr, sizeof(errStr)); DBGPRINTF("omelasticsearch: error opening error file: %s\n", errStr); ABORT_FINALIZE(RS_RET_ERR); } } if((req=cJSON_CreateObject()) == NULL) ABORT_FINALIZE(RS_RET_ERR); cJSON_AddItemToObject(req, "url", cJSON_CreateString((char*)pData->restURL)); cJSON_AddItemToObject(req, "postdata", cJSON_CreateString((char*)reqmsg)); if((errRoot=cJSON_CreateObject()) == NULL) ABORT_FINALIZE(RS_RET_ERR); cJSON_AddItemToObject(errRoot, "request", req); cJSON_AddItemToObject(errRoot, "reply", replyRoot); rendered = cJSON_Print(errRoot); /* we do not do real error-handling on the err file, as this finally complicates * things way to much. */ DBGPRINTF("omelasticsearch: error record: '%s'\n", rendered); toWrite = strlen(rendered); wrRet = write(pData->fdErrFile, rendered, toWrite); if(wrRet != (ssize_t) toWrite) { DBGPRINTF("omelasticsearch: error %d writing error file, write returns %lld\n", errno, (long long) wrRet); } free(rendered); cJSON_Delete(errRoot); *pReplyRoot = NULL; /* tell caller not to delete once again! */ finalize_it: if(rendered != NULL) free(rendered); RETiRet; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'bugfix: double-free in omelasticsearch closes: http://bugzilla.adiscon.com/show_bug.cgi?id=461 Thanks to Marius Ionescu for providing a detailled bug report'</s>
<s>[INST] Given the following code containing errors, provide 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 credssp_skip_ts_credentials(rdpCredssp* credssp) { int length; int ts_password_creds_length; int ts_credentials_length = 0; length = ber_skip_integer(0); length += ber_skip_contextual_tag(length); ts_credentials_length += length; ts_password_creds_length = credssp_skip_ts_password_creds(credssp); length = ber_skip_octet_string(ts_password_creds_length); length += ber_skip_contextual_tag(length); ts_credentials_length += length; length = ber_skip_sequence(ts_credentials_length); return length; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 _ber_skip_length(int length) { if (length > 0x80) return 3; else return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 credssp_skip_ts_request(int length) { length += ber_skip_integer(2); length += ber_skip_contextual_tag(3); length += der_skip_sequence_tag(length); return length; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 ber_write_sequence_tag(wStream* s, int length) { Stream_Write_UINT8(s, (BER_CLASS_UNIV | BER_CONSTRUCT) | (BER_TAG_MASK & BER_TAG_SEQUENCE)); return ber_write_length(s, length) + 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 credssp_encode_ts_credentials(rdpCredssp* credssp) { wStream* s; int length; length = credssp_skip_ts_credentials(credssp); sspi_SecBufferAlloc(&credssp->ts_credentials, length); s = Stream_New(credssp->ts_credentials.pvBuffer, length); credssp_write_ts_credentials(credssp, s); Stream_Free(s, FALSE); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 credssp_ntlm_client_init(rdpCredssp* credssp) { char* spn; int length; freerdp* instance; rdpSettings* settings; settings = credssp->settings; instance = (freerdp*) settings->instance; if ((settings->Password == NULL) || (settings->Username == NULL)) { if (instance->Authenticate) { BOOL proceed = instance->Authenticate(instance, &settings->Username, &settings->Password, &settings->Domain); if (!proceed) return 0; } } sspi_SetAuthIdentity(&(credssp->identity), settings->Username, settings->Domain, settings->Password); #ifdef WITH_DEBUG_NLA _tprintf(_T("User: %s Domain: %s Password: %s\n"), (char*) credssp->identity.User, (char*) credssp->identity.Domain, (char*) credssp->identity.Password); #endif sspi_SecBufferAlloc(&credssp->PublicKey, credssp->transport->TlsIn->PublicKeyLength); CopyMemory(credssp->PublicKey.pvBuffer, credssp->transport->TlsIn->PublicKey, credssp->transport->TlsIn->PublicKeyLength); length = sizeof(TERMSRV_SPN_PREFIX) + strlen(settings->ServerHostname); spn = (SEC_CHAR*) malloc(length + 1); sprintf(spn, "%s%s", TERMSRV_SPN_PREFIX, settings->ServerHostname); #ifdef UNICODE credssp->ServicePrincipalName = (LPTSTR) malloc(length * 2 + 2); MultiByteToWideChar(CP_UTF8, 0, spn, length, (LPWSTR) credssp->ServicePrincipalName, length); free(spn); #else credssp->ServicePrincipalName = spn; #endif return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 ber_read_application_tag(wStream* s, BYTE tag, int* length) { BYTE byte; if (tag > 30) { if(Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); if (byte != ((BER_CLASS_APPL | BER_CONSTRUCT) | BER_TAG_MASK)) return FALSE; if(Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); if (byte != tag) return FALSE; return ber_read_length(s, length); } else { if(Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); if (byte != ((BER_CLASS_APPL | BER_CONSTRUCT) | (BER_TAG_MASK & tag))) return FALSE; return ber_read_length(s, length); } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 credssp_server_authenticate(rdpCredssp* credssp) { UINT32 cbMaxToken; ULONG fContextReq; ULONG pfContextAttr; SECURITY_STATUS status; CredHandle credentials; TimeStamp expiration; PSecPkgInfo pPackageInfo; SecBuffer input_buffer; SecBuffer output_buffer; SecBufferDesc input_buffer_desc; SecBufferDesc output_buffer_desc; BOOL have_context; BOOL have_input_buffer; BOOL have_pub_key_auth; sspi_GlobalInit(); if (credssp_ntlm_server_init(credssp) == 0) return 0; #ifdef WITH_NATIVE_SSPI if (!credssp->SspiModule) credssp->SspiModule = _tcsdup(_T("secur32.dll")); #endif if (credssp->SspiModule) { HMODULE hSSPI; INIT_SECURITY_INTERFACE pInitSecurityInterface; hSSPI = LoadLibrary(credssp->SspiModule); if (!hSSPI) { _tprintf(_T("Failed to load SSPI module: %s\n"), credssp->SspiModule); return 0; } #ifdef UNICODE pInitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress(hSSPI, "InitSecurityInterfaceW"); #else pInitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress(hSSPI, "InitSecurityInterfaceA"); #endif credssp->table = (*pInitSecurityInterface)(); } #ifndef WITH_NATIVE_SSPI else { credssp->table = InitSecurityInterface(); } #endif status = credssp->table->QuerySecurityPackageInfo(NLA_PKG_NAME, &pPackageInfo); if (status != SEC_E_OK) { fprintf(stderr, "QuerySecurityPackageInfo status: 0x%08X\n", status); return 0; } cbMaxToken = pPackageInfo->cbMaxToken; status = credssp->table->AcquireCredentialsHandle(NULL, NLA_PKG_NAME, SECPKG_CRED_INBOUND, NULL, NULL, NULL, NULL, &credentials, &expiration); if (status != SEC_E_OK) { fprintf(stderr, "AcquireCredentialsHandle status: 0x%08X\n", status); return 0; } have_context = FALSE; have_input_buffer = FALSE; have_pub_key_auth = FALSE; ZeroMemory(&input_buffer, sizeof(SecBuffer)); ZeroMemory(&output_buffer, sizeof(SecBuffer)); ZeroMemory(&input_buffer_desc, sizeof(SecBufferDesc)); ZeroMemory(&output_buffer_desc, sizeof(SecBufferDesc)); ZeroMemory(&credssp->ContextSizes, sizeof(SecPkgContext_Sizes)); /* * from tspkg.dll: 0x00000112 * ASC_REQ_MUTUAL_AUTH * ASC_REQ_CONFIDENTIALITY * ASC_REQ_ALLOCATE_MEMORY */ fContextReq = 0; fContextReq |= ASC_REQ_MUTUAL_AUTH; fContextReq |= ASC_REQ_CONFIDENTIALITY; fContextReq |= ASC_REQ_CONNECTION; fContextReq |= ASC_REQ_USE_SESSION_KEY; fContextReq |= ASC_REQ_REPLAY_DETECT; fContextReq |= ASC_REQ_SEQUENCE_DETECT; fContextReq |= ASC_REQ_EXTENDED_ERROR; while (TRUE) { input_buffer_desc.ulVersion = SECBUFFER_VERSION; input_buffer_desc.cBuffers = 1; input_buffer_desc.pBuffers = &input_buffer; input_buffer.BufferType = SECBUFFER_TOKEN; /* receive authentication token */ input_buffer_desc.ulVersion = SECBUFFER_VERSION; input_buffer_desc.cBuffers = 1; input_buffer_desc.pBuffers = &input_buffer; input_buffer.BufferType = SECBUFFER_TOKEN; if (credssp_recv(credssp) < 0) return -1; #ifdef WITH_DEBUG_CREDSSP fprintf(stderr, "Receiving Authentication Token\n"); credssp_buffer_print(credssp); #endif input_buffer.pvBuffer = credssp->negoToken.pvBuffer; input_buffer.cbBuffer = credssp->negoToken.cbBuffer; if (credssp->negoToken.cbBuffer < 1) { fprintf(stderr, "CredSSP: invalid negoToken!\n"); return -1; } output_buffer_desc.ulVersion = SECBUFFER_VERSION; output_buffer_desc.cBuffers = 1; output_buffer_desc.pBuffers = &output_buffer; output_buffer.BufferType = SECBUFFER_TOKEN; output_buffer.cbBuffer = cbMaxToken; output_buffer.pvBuffer = malloc(output_buffer.cbBuffer); status = credssp->table->AcceptSecurityContext(&credentials, have_context? &credssp->context: NULL, &input_buffer_desc, fContextReq, SECURITY_NATIVE_DREP, &credssp->context, &output_buffer_desc, &pfContextAttr, &expiration); credssp->negoToken.pvBuffer = output_buffer.pvBuffer; credssp->negoToken.cbBuffer = output_buffer.cbBuffer; if ((status == SEC_I_COMPLETE_AND_CONTINUE) || (status == SEC_I_COMPLETE_NEEDED)) { if (credssp->table->CompleteAuthToken != NULL) credssp->table->CompleteAuthToken(&credssp->context, &output_buffer_desc); if (status == SEC_I_COMPLETE_NEEDED) status = SEC_E_OK; else if (status == SEC_I_COMPLETE_AND_CONTINUE) status = SEC_I_CONTINUE_NEEDED; } if (status == SEC_E_OK) { have_pub_key_auth = TRUE; if (credssp->table->QueryContextAttributes(&credssp->context, SECPKG_ATTR_SIZES, &credssp->ContextSizes) != SEC_E_OK) { fprintf(stderr, "QueryContextAttributes SECPKG_ATTR_SIZES failure\n"); return 0; } if (credssp_decrypt_public_key_echo(credssp) != SEC_E_OK) { fprintf(stderr, "Error: could not verify client's public key echo\n"); return -1; } sspi_SecBufferFree(&credssp->negoToken); credssp->negoToken.pvBuffer = NULL; credssp->negoToken.cbBuffer = 0; credssp_encrypt_public_key_echo(credssp); } if ((status != SEC_E_OK) && (status != SEC_I_CONTINUE_NEEDED)) { fprintf(stderr, "AcceptSecurityContext status: 0x%08X\n", status); return -1; } /* send authentication token */ #ifdef WITH_DEBUG_CREDSSP fprintf(stderr, "Sending Authentication Token\n"); credssp_buffer_print(credssp); #endif credssp_send(credssp); credssp_buffer_free(credssp); if (status != SEC_I_CONTINUE_NEEDED) break; have_context = TRUE; } /* Receive encrypted credentials */ if (credssp_recv(credssp) < 0) return -1; if (credssp_decrypt_ts_credentials(credssp) != SEC_E_OK) { fprintf(stderr, "Could not decrypt TSCredentials status: 0x%08X\n", status); return 0; } if (status != SEC_E_OK) { fprintf(stderr, "AcceptSecurityContext status: 0x%08X\n", status); return 0; } status = credssp->table->ImpersonateSecurityContext(&credssp->context); if (status != SEC_E_OK) { fprintf(stderr, "ImpersonateSecurityContext status: 0x%08X\n", status); return 0; } else { status = credssp->table->RevertSecurityContext(&credssp->context); if (status != SEC_E_OK) { fprintf(stderr, "RevertSecurityContext status: 0x%08X\n", status); return 0; } } credssp->table->FreeContextBuffer(pPackageInfo); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 ber_write_contextual_tag(wStream* s, BYTE tag, int length, BOOL pc) { Stream_Write_UINT8(s, (BER_CLASS_CTXT | BER_PC(pc)) | (BER_TAG_MASK & tag)); return ber_write_length(s, length) + 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 ber_skip_sequence(int length) { return 1 + _ber_skip_length(length) + length; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 ber_write_length(wStream* s, int length) { if (length > 0x7F) { Stream_Write_UINT8(s, 0x82); Stream_Write_UINT16_BE(s, length); return 3; } else { Stream_Write_UINT8(s, length); return 1; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 credssp_skip_pub_key_auth(int length) { length = ber_skip_octet_string(length); length += ber_skip_contextual_tag(length); return length; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 ber_read_enumerated(wStream* s, BYTE* enumerated, BYTE count) { int length; if(!ber_read_universal_tag(s, BER_TAG_ENUMERATED, FALSE) || !ber_read_length(s, &length)) return FALSE; if (length != 1 || Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, *enumerated); /* check that enumerated value falls within expected range */ if (*enumerated + 1 > count) return FALSE; return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 ber_read_universal_tag(wStream* s, BYTE tag, BOOL pc) { BYTE byte; if(Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); if (byte != (BER_CLASS_UNIV | BER_PC(pc) | (BER_TAG_MASK & tag))) return FALSE; return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 credssp_write_ts_credentials(rdpCredssp* credssp, wStream* s) { int length; int ts_password_creds_length; length = credssp_skip_ts_credentials(credssp); ts_password_creds_length = credssp_skip_ts_password_creds(credssp); /* TSCredentials (SEQUENCE) */ length = ber_get_content_length(length); length -= ber_write_sequence_tag(s, length); /* [0] credType (INTEGER) */ length -= ber_write_contextual_tag(s, 0, 3, TRUE); length -= ber_write_integer(s, 1); /* [1] credentials (OCTET STRING) */ length -= 1; length -= ber_write_contextual_tag(s, 1, length, TRUE); length -= ber_write_octet_string_tag(s, ts_password_creds_length); credssp_write_ts_password_creds(credssp, s); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 ber_read_contextual_tag(wStream* s, BYTE tag, int* length, BOOL pc) { BYTE byte; if(Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); if (byte != ((BER_CLASS_CTXT | BER_PC(pc)) | (BER_TAG_MASK & tag))) { Stream_Rewind(s, 1); return FALSE; } return ber_read_length(s, length); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 ber_write_universal_tag(wStream* s, BYTE tag, BOOL pc) { Stream_Write_UINT8(s, (BER_CLASS_UNIV | BER_PC(pc)) | (BER_TAG_MASK & tag)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide 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 ber_write_integer(wStream* s, UINT32 value) { ber_write_universal_tag(s, BER_TAG_INTEGER, FALSE); if (value < 0x80) { ber_write_length(s, 1); Stream_Write_UINT8(s, value); return 3; } else if (value < 0x8000) { ber_write_length(s, 2); Stream_Write_UINT16_BE(s, value); return 4; } else if (value < 0x800000) { ber_write_length(s, 3); Stream_Write_UINT8(s, (value >> 16)); Stream_Write_UINT16_BE(s, (value & 0xFFFF)); return 5; } else if (value < 0x80000000) { ber_write_length(s, 4); Stream_Write_UINT32_BE(s, value); return 6; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Finished merging missing changes from pull request #1257 (https://github.com/FreeRDP/FreeRDP/pull/1257 - commit 0dc22d5). Correctly report the length of ts_password_creds.'</s>
<s>[INST] Given the following code containing errors, provide 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 credssp_sizeof_ts_password_creds(rdpCredssp* credssp) { int length; int ts_password_creds_length = 0; length = ber_sizeof_octet_string(credssp->identity.DomainLength * 2); length += ber_sizeof_contextual_tag(length); ts_password_creds_length += length; length = ber_sizeof_octet_string(credssp->identity.UserLength * 2); length += ber_sizeof_contextual_tag(length); ts_password_creds_length += length; length = ber_sizeof_octet_string(credssp->identity.PasswordLength * 2); length += ber_sizeof_contextual_tag(length); ts_password_creds_length += length; length = ber_sizeof_sequence(ts_password_creds_length); return length; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Finished merging missing changes from pull request #1257 (https://github.com/FreeRDP/FreeRDP/pull/1257 - commit 0dc22d5). Correctly report the length of ts_password_creds.'</s>
<s>[INST] Given the following code containing errors, provide 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 security_decrypt(BYTE* data, int length, rdpRdp* rdp) { if (rdp->decrypt_use_count >= 4096) { security_key_update(rdp->decrypt_key, rdp->decrypt_update_key, rdp->rc4_key_len); crypto_rc4_free(rdp->rc4_decrypt_key); rdp->rc4_decrypt_key = crypto_rc4_init(rdp->decrypt_key, rdp->rc4_key_len); rdp->decrypt_use_count = 0; } crypto_rc4(rdp->rc4_decrypt_key, length, data, data); rdp->decrypt_use_count += 1; rdp->decrypt_checksum_use_count++; return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'security: add a NULL pointer check to fix a server crash.'</s>
<s>[INST] Given the following code containing errors, provide 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 peer_recv_callback(rdpTransport* transport, wStream* s, void* extra) { freerdp_peer* client = (freerdp_peer*) extra; rdpRdp* rdp = client->context->rdp; switch (rdp->state) { case CONNECTION_STATE_INITIAL: if (!rdp_server_accept_nego(rdp, s)) return -1; if (rdp->nego->selected_protocol & PROTOCOL_NLA) { sspi_CopyAuthIdentity(&client->identity, &(rdp->nego->transport->credssp->identity)); IFCALLRET(client->Logon, client->authenticated, client, &client->identity, TRUE); credssp_free(rdp->nego->transport->credssp); } else { IFCALLRET(client->Logon, client->authenticated, client, &client->identity, FALSE); } break; case CONNECTION_STATE_NEGO: if (!rdp_server_accept_mcs_connect_initial(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_CONNECT: if (!rdp_server_accept_mcs_erect_domain_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_ERECT_DOMAIN: if (!rdp_server_accept_mcs_attach_user_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_ATTACH_USER: if (!rdp_server_accept_mcs_channel_join_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_CHANNEL_JOIN: if (rdp->settings->DisableEncryption) { if (!rdp_server_accept_client_keys(rdp, s)) return -1; break; } rdp->state = CONNECTION_STATE_ESTABLISH_KEYS; /* FALLTHROUGH */ case CONNECTION_STATE_ESTABLISH_KEYS: if (!rdp_server_accept_client_info(rdp, s)) return -1; IFCALL(client->Capabilities, client); if (!rdp_send_demand_active(rdp)) return -1; break; case CONNECTION_STATE_LICENSE: if (!rdp_server_accept_confirm_active(rdp, s)) { /** * During reactivation sequence the client might sent some input or channel data * before receiving the Deactivate All PDU. We need to process them as usual. */ Stream_SetPosition(s, 0); return peer_recv_pdu(client, s); } break; case CONNECTION_STATE_ACTIVE: if (peer_recv_pdu(client, s) < 0) return -1; break; default: fprintf(stderr, "Invalid state %d\n", rdp->state); return -1; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished.'</s>
<s>[INST] Given the following code containing errors, provide 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 transport_connect_nla(rdpTransport* transport) { freerdp* instance; rdpSettings* settings; if (transport->layer == TRANSPORT_LAYER_TSG) return TRUE; if (!transport_connect_tls(transport)) return FALSE; /* Network Level Authentication */ if (transport->settings->Authentication != TRUE) return TRUE; settings = transport->settings; instance = (freerdp*) settings->instance; if (transport->credssp == NULL) transport->credssp = credssp_new(instance, transport, settings); if (credssp_authenticate(transport->credssp) < 0) { if (!connectErrorCode) connectErrorCode = AUTHENTICATIONERROR; fprintf(stderr, "Authentication failure, check credentials.\n" "If credentials are valid, the NTLMSSP implementation may be to blame.\n"); credssp_free(transport->credssp); return FALSE; } credssp_free(transport->credssp); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished.'</s>
<s>[INST] Given the following code containing errors, provide 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* sspi_SecureHandleGetUpperPointer(SecHandle* handle) { void* pointer; if (!handle) return NULL; pointer = (void*) ~((size_t) handle->dwUpper); return pointer; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished.'</s>
<s>[INST] Given the following code containing errors, provide 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 transport_accept_nla(rdpTransport* transport) { freerdp* instance; rdpSettings* settings; if (transport->TlsIn == NULL) transport->TlsIn = tls_new(transport->settings); if (transport->TlsOut == NULL) transport->TlsOut = transport->TlsIn; transport->layer = TRANSPORT_LAYER_TLS; transport->TlsIn->sockfd = transport->TcpIn->sockfd; if (tls_accept(transport->TlsIn, transport->settings->CertificateFile, transport->settings->PrivateKeyFile) != TRUE) return FALSE; /* Network Level Authentication */ if (transport->settings->Authentication != TRUE) return TRUE; settings = transport->settings; instance = (freerdp*) settings->instance; if (transport->credssp == NULL) transport->credssp = credssp_new(instance, transport, settings); if (credssp_authenticate(transport->credssp) < 0) { fprintf(stderr, "client authentication failure\n"); credssp_free(transport->credssp); return FALSE; } /* don't free credssp module yet, we need to copy the credentials from it first */ return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlParseElement(xmlParserCtxtPtr ctxt) { const xmlChar *name; const xmlChar *prefix = NULL; const xmlChar *URI = NULL; xmlParserNodeInfo node_info; int line, tlen = 0; xmlNodePtr ret; int nsNr = ctxt->nsNr; if (((unsigned int) ctxt->nameNr > xmlParserMaxDepth) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INTERNAL_ERROR, "Excessive depth in document: %d use XML_PARSE_HUGE option\n", xmlParserMaxDepth); ctxt->instate = XML_PARSER_EOF; return; } /* Capture start position */ if (ctxt->record_info) { node_info.begin_pos = ctxt->input->consumed + (CUR_PTR - ctxt->input->base); node_info.begin_line = ctxt->input->line; } if (ctxt->spaceNr == 0) spacePush(ctxt, -1); else if (*ctxt->space == -2) spacePush(ctxt, -1); else spacePush(ctxt, *ctxt->space); line = ctxt->input->line; #ifdef LIBXML_SAX1_ENABLED if (ctxt->sax2) #endif /* LIBXML_SAX1_ENABLED */ name = xmlParseStartTag2(ctxt, &prefix, &URI, &tlen); #ifdef LIBXML_SAX1_ENABLED else name = xmlParseStartTag(ctxt); #endif /* LIBXML_SAX1_ENABLED */ if (ctxt->instate == XML_PARSER_EOF) return; if (name == NULL) { spacePop(ctxt); return; } namePush(ctxt, name); ret = ctxt->node; #ifdef LIBXML_VALID_ENABLED /* * [ VC: Root Element Type ] * The Name in the document type declaration must match the element * type of the root element. */ if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc && ctxt->node && (ctxt->node == ctxt->myDoc->children)) ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc); #endif /* LIBXML_VALID_ENABLED */ /* * Check for an Empty Element. */ if ((RAW == '/') && (NXT(1) == '>')) { SKIP(2); if (ctxt->sax2) { if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElementNs(ctxt->userData, name, prefix, URI); #ifdef LIBXML_SAX1_ENABLED } else { if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElement(ctxt->userData, name); #endif /* LIBXML_SAX1_ENABLED */ } namePop(ctxt); spacePop(ctxt); if (nsNr != ctxt->nsNr) nsPop(ctxt, ctxt->nsNr - nsNr); if ( ret != NULL && ctxt->record_info ) { node_info.end_pos = ctxt->input->consumed + (CUR_PTR - ctxt->input->base); node_info.end_line = ctxt->input->line; node_info.node = ret; xmlParserAddNodeInfo(ctxt, &node_info); } return; } if (RAW == '>') { NEXT1; } else { xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_GT_REQUIRED, "Couldn't find end of Start Tag %s line %d\n", name, line, NULL); /* * end of parsing of this node. */ nodePop(ctxt); namePop(ctxt); spacePop(ctxt); if (nsNr != ctxt->nsNr) nsPop(ctxt, ctxt->nsNr - nsNr); /* * Capture end position and add node */ if ( ret != NULL && ctxt->record_info ) { node_info.end_pos = ctxt->input->consumed + (CUR_PTR - ctxt->input->base); node_info.end_line = ctxt->input->line; node_info.node = ret; xmlParserAddNodeInfo(ctxt, &node_info); } return; } /* * Parse the content of the element: */ xmlParseContent(ctxt); if (!IS_BYTE_CHAR(RAW)) { xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED, "Premature end of data in tag %s line %d\n", name, line, NULL); /* * end of parsing of this node. */ nodePop(ctxt); namePop(ctxt); spacePop(ctxt); if (nsNr != ctxt->nsNr) nsPop(ctxt, ctxt->nsNr - nsNr); return; } /* * parse the end of tag: '</' should be here. */ if (ctxt->sax2) { xmlParseEndTag2(ctxt, prefix, URI, line, ctxt->nsNr - nsNr, tlen); namePop(ctxt); } #ifdef LIBXML_SAX1_ENABLED else xmlParseEndTag1(ctxt, line); #endif /* LIBXML_SAX1_ENABLED */ /* * Capture end position and add node */ if ( ret != NULL && ctxt->record_info ) { node_info.end_pos = ctxt->input->consumed + (CUR_PTR - ctxt->input->base); node_info.end_line = ctxt->input->line; node_info.node = ret; xmlParserAddNodeInfo(ctxt, &node_info); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Improve handling of xmlStopParser() Add a specific parser error Try to stop parsing as quickly as possible'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlParsePEReference(xmlParserCtxtPtr ctxt) { const xmlChar *name; xmlEntityPtr entity = NULL; xmlParserInputPtr input; if (RAW != '%') return; NEXT; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParsePEReference: no name\n"); return; } if (RAW != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); return; } NEXT; /* * Increate the number of entity references parsed */ ctxt->nbentities++; /* * Request the entity from SAX */ if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) entity = ctxt->sax->getParameterEntity(ctxt->userData, name); if (entity == NULL) { /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", ... * ... The declaration of a parameter entity must precede * any reference to it... */ if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name); } else { /* * [ VC: Entity Declared ] * In a document with an external subset or external * parameter entities with "standalone='no'", ... * ... The declaration of a parameter entity must * precede any reference to it... */ xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); ctxt->valid = 0; } } else { /* * Internal checking in case the entity quest barfed */ if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) { xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "Internal: %%%s; is not a parameter entity\n", name, NULL); } else if (ctxt->input->free != deallocblankswrapper) { input = xmlNewBlanksWrapperInputStream(ctxt, entity); if (xmlPushInput(ctxt, input) < 0) return; } else { /* * TODO !!! * handle the extra spaces added before and after * c.f. http://www.w3.org/TR/REC-xml#as-PE */ input = xmlNewEntityInputStream(ctxt, entity); if (xmlPushInput(ctxt, input) < 0) return; if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { xmlParseTextDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing * right here */ ctxt->instate = XML_PARSER_EOF; return; } } } } ctxt->hasPErefs = 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Improve handling of xmlStopParser() Add a specific parser error Try to stop parsing as quickly as possible'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlParseEntityRef(xmlParserCtxtPtr ctxt) { const xmlChar *name; xmlEntityPtr ent = NULL; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); if (RAW != '&') return(NULL); NEXT; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseEntityRef: no name\n"); return(NULL); } if (RAW != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); return(NULL); } NEXT; /* * Predefined entities override any extra definition */ if ((ctxt->options & XML_PARSE_OLDSAX) == 0) { ent = xmlGetPredefinedEntity(name); if (ent != NULL) return(ent); } /* * Increase the number of entity references parsed */ ctxt->nbentities++; /* * Ask first SAX for entity resolution, otherwise try the * entities which may have stored in the parser context. */ if (ctxt->sax != NULL) { if (ctxt->sax->getEntity != NULL) ent = ctxt->sax->getEntity(ctxt->userData, name); if ((ctxt->wellFormed == 1 ) && (ent == NULL) && (ctxt->options & XML_PARSE_OLDSAX)) ent = xmlGetPredefinedEntity(name); if ((ctxt->wellFormed == 1 ) && (ent == NULL) && (ctxt->userData==ctxt)) { ent = xmlSAX2GetEntity(ctxt, name); } } /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", the * Name given in the entity reference must match that in an * entity declaration, except that well-formed documents * need not declare any of the following entities: amp, lt, * gt, apos, quot. * The declaration of a parameter entity must precede any * reference to it. * Similarly, the declaration of a general entity must * precede any reference to it which appears in a default * value in an attribute-list declaration. Note that if * entities are declared in the external subset or in * external parameter entities, a non-validating processor * is not obligated to read and process their declarations; * for such documents, the rule that an entity must be * declared is a well-formedness constraint only if * standalone='yes'. */ if (ent == NULL) { if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "Entity '%s' not defined\n", name); } else { xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY, "Entity '%s' not defined\n", name); if ((ctxt->inSubset == 0) && (ctxt->sax != NULL) && (ctxt->sax->reference != NULL)) { ctxt->sax->reference(ctxt->userData, name); } } ctxt->valid = 0; } /* * [ WFC: Parsed Entity ] * An entity reference must not contain the name of an * unparsed entity */ else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY, "Entity reference to unparsed entity %s\n", name); } /* * [ WFC: No External Entity References ] * Attribute values cannot contain direct or indirect * entity references to external entities. */ else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) && (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) { xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL, "Attribute references external entity '%s'\n", name); } /* * [ WFC: No < in Attribute Values ] * The replacement text of any entity referred to directly or * indirectly in an attribute value (other than "&lt;") must * not contain a <. */ else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) && (ent != NULL) && (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY)) { if ((ent->checked & 1) || ((ent->checked == 0) && (ent->content != NULL) &&(xmlStrchr(ent->content, '<')))) { xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, "'<' in entity '%s' is not allowed in attributes values\n", name); } } /* * Internal check, no parameter entities here ... */ else { switch (ent->etype) { case XML_INTERNAL_PARAMETER_ENTITY: case XML_EXTERNAL_PARAMETER_ENTITY: xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER, "Attempt to reference the parameter entity '%s'\n", name); break; default: break; } } /* * [ WFC: No Recursion ] * A parsed entity must not contain a recursive reference * to itself, either directly or indirectly. * Done somewhere else */ return(ent); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Improve handling of xmlStopParser() Add a specific parser error Try to stop parsing as quickly as possible'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlParseChunk(xmlParserCtxtPtr ctxt, const char *chunk, int size, int terminate) { int end_in_lf = 0; int remain = 0; size_t old_avail = 0; size_t avail = 0; if (ctxt == NULL) return(XML_ERR_INTERNAL_ERROR); if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) return(ctxt->errNo); if (ctxt->instate == XML_PARSER_EOF) return(-1); if (ctxt->instate == XML_PARSER_START) xmlDetectSAX2(ctxt); if ((size > 0) && (chunk != NULL) && (!terminate) && (chunk[size - 1] == '\r')) { end_in_lf = 1; size--; } xmldecl_done: if ((size > 0) && (chunk != NULL) && (ctxt->input != NULL) && (ctxt->input->buf != NULL) && (ctxt->instate != XML_PARSER_EOF)) { size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer, ctxt->input); size_t cur = ctxt->input->cur - ctxt->input->base; int res; old_avail = xmlBufUse(ctxt->input->buf->buffer); /* * Specific handling if we autodetected an encoding, we should not * push more than the first line ... which depend on the encoding * And only push the rest once the final encoding was detected */ if ((ctxt->instate == XML_PARSER_START) && (ctxt->input != NULL) && (ctxt->input->buf != NULL) && (ctxt->input->buf->encoder != NULL)) { unsigned int len = 45; if ((xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UTF-16")) || (xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UTF16"))) len = 90; else if ((xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UCS-4")) || (xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UCS4"))) len = 180; if (ctxt->input->buf->rawconsumed < len) len -= ctxt->input->buf->rawconsumed; /* * Change size for reading the initial declaration only * if size is greater than len. Otherwise, memmove in xmlBufferAdd * will blindly copy extra bytes from memory. */ if ((unsigned int) size > len) { remain = size - len; size = len; } else { remain = 0; } } res = xmlParserInputBufferPush(ctxt->input->buf, size, chunk); if (res < 0) { ctxt->errNo = XML_PARSER_EOF; ctxt->disableSAX = 1; return (XML_PARSER_EOF); } xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input, base, cur); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: pushed %d\n", size); #endif } else if (ctxt->instate != XML_PARSER_EOF) { if ((ctxt->input != NULL) && ctxt->input->buf != NULL) { xmlParserInputBufferPtr in = ctxt->input->buf; if ((in->encoder != NULL) && (in->buffer != NULL) && (in->raw != NULL)) { int nbchars; size_t base = xmlBufGetInputBase(in->buffer, ctxt->input); size_t current = ctxt->input->cur - ctxt->input->base; nbchars = xmlCharEncInput(in, terminate); if (nbchars < 0) { /* TODO 2.6.0 */ xmlGenericError(xmlGenericErrorContext, "xmlParseChunk: encoder error\n"); return(XML_ERR_INVALID_ENCODING); } xmlBufSetInputBaseCur(in->buffer, ctxt->input, base, current); } } } if (remain != 0) { xmlParseTryOrFinish(ctxt, 0); } else { if ((ctxt->input != NULL) && (ctxt->input->buf != NULL)) avail = xmlBufUse(ctxt->input->buf->buffer); /* * Depending on the current state it may not be such * a good idea to try parsing if there is nothing in the chunk * which would be worth doing a parser state transition and we * need to wait for more data */ if ((terminate) || (avail > XML_MAX_TEXT_LENGTH) || (old_avail == 0) || (avail == 0) || (xmlParseCheckTransition(ctxt, (const char *)&ctxt->input->base[old_avail], avail - old_avail))) xmlParseTryOrFinish(ctxt, terminate); } if ((ctxt->input != NULL) && (((ctxt->input->end - ctxt->input->cur) > XML_MAX_LOOKUP_LIMIT) || ((ctxt->input->cur - ctxt->input->base) > XML_MAX_LOOKUP_LIMIT)) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "Huge input lookup"); ctxt->instate = XML_PARSER_EOF; } if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) return(ctxt->errNo); if (remain != 0) { chunk += size; size = remain; remain = 0; goto xmldecl_done; } if ((end_in_lf == 1) && (ctxt->input != NULL) && (ctxt->input->buf != NULL)) { size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer, ctxt->input); size_t current = ctxt->input->cur - ctxt->input->base; xmlParserInputBufferPush(ctxt->input->buf, 1, "\r"); xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input, base, current); } if (terminate) { /* * Check for termination */ int cur_avail = 0; if (ctxt->input != NULL) { if (ctxt->input->buf == NULL) cur_avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else cur_avail = xmlBufUse(ctxt->input->buf->buffer) - (ctxt->input->cur - ctxt->input->base); } if ((ctxt->instate != XML_PARSER_EOF) && (ctxt->instate != XML_PARSER_EPILOG)) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } if ((ctxt->instate == XML_PARSER_EPILOG) && (cur_avail > 0)) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } if (ctxt->instate != XML_PARSER_EOF) { if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); } ctxt->instate = XML_PARSER_EOF; } if (ctxt->wellFormed == 0) return((xmlParserErrors) ctxt->errNo); else return(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Improve handling of xmlStopParser() Add a specific parser error Try to stop parsing as quickly as possible'</s>
<s>[INST] Given the following code containing errors, provide 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->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); /* * 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); } /* * 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); 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': 'Improve handling of xmlStopParser() Add a specific parser error Try to stop parsing as quickly as possible'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlParseDocTypeDecl(xmlParserCtxtPtr ctxt) { const xmlChar *name = NULL; xmlChar *ExternalID = NULL; xmlChar *URI = NULL; /* * We know that '<!DOCTYPE' has been detected. */ SKIP(9); SKIP_BLANKS; /* * Parse the DOCTYPE name. */ name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseDocTypeDecl : no DOCTYPE name !\n"); } ctxt->intSubName = name; SKIP_BLANKS; /* * Check for SystemID and ExternalID */ URI = xmlParseExternalID(ctxt, &ExternalID, 1); if ((URI != NULL) || (ExternalID != NULL)) { ctxt->hasExternalSubset = 1; } ctxt->extSubURI = URI; ctxt->extSubSystem = ExternalID; SKIP_BLANKS; /* * Create and update the internal subset. */ if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) && (!ctxt->disableSAX)) ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI); /* * Is there any internal subset declarations ? * they are handled separately in xmlParseInternalSubset() */ if (RAW == '[') return; /* * We should be at the end of the DOCTYPE declaration. */ if (RAW != '>') { xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL); } NEXT; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Improve handling of xmlStopParser() Add a specific parser error Try to stop parsing as quickly as possible'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlStopParser(xmlParserCtxtPtr ctxt) { if (ctxt == NULL) return; ctxt->instate = XML_PARSER_EOF; ctxt->disableSAX = 1; if (ctxt->input != NULL) { ctxt->input->cur = BAD_CAST""; ctxt->input->base = ctxt->input->cur; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Improve handling of xmlStopParser() Add a specific parser error Try to stop parsing as quickly as possible'</s>
<s>[INST] Given the following code containing errors, provide 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 _xml_characterDataHandler(void *userData, const XML_Char *s, int len) { xml_parser *parser = (xml_parser *)userData; if (parser) { zval *retval, *args[2]; if (parser->characterDataHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_xmlchar_zval(s, len, parser->target_encoding); if ((retval = xml_call_handler(parser, parser->characterDataHandler, parser->characterDataPtr, 2, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { int i; int doprint = 0; char *decoded_value; int decoded_len; decoded_value = xml_utf8_decode(s,len,&decoded_len,parser->target_encoding); for (i = 0; i < decoded_len; i++) { switch (decoded_value[i]) { case ' ': case '\t': case '\n': continue; default: doprint = 1; break; } if (doprint) { break; } } if (doprint || (! parser->skipwhite)) { if (parser->lastwasopen) { zval **myval; /* check if the current tag already has a value - if yes append to that! */ if (zend_hash_find(Z_ARRVAL_PP(parser->ctag),"value",sizeof("value"),(void **) &myval) == SUCCESS) { int newlen = Z_STRLEN_PP(myval) + decoded_len; Z_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1); strncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1); Z_STRLEN_PP(myval) += decoded_len; efree(decoded_value); } else { add_assoc_string(*(parser->ctag),"value",decoded_value,0); } } else { zval *tag; zval **curtag, **mytype, **myval; HashPosition hpos=NULL; zend_hash_internal_pointer_end_ex(Z_ARRVAL_P(parser->data), &hpos); if (hpos && (zend_hash_get_current_data_ex(Z_ARRVAL_P(parser->data), (void **) &curtag, &hpos) == SUCCESS)) { if (zend_hash_find(Z_ARRVAL_PP(curtag),"type",sizeof("type"),(void **) &mytype) == SUCCESS) { if (!strcmp(Z_STRVAL_PP(mytype), "cdata")) { if (zend_hash_find(Z_ARRVAL_PP(curtag),"value",sizeof("value"),(void **) &myval) == SUCCESS) { int newlen = Z_STRLEN_PP(myval) + decoded_len; Z_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1); strncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1); Z_STRLEN_PP(myval) += decoded_len; efree(decoded_value); return; } } } } MAKE_STD_ZVAL(tag); array_init(tag); _xml_add_to_info(parser,parser->ltags[parser->level-1] + parser->toffset); add_assoc_string(tag,"tag",parser->ltags[parser->level-1] + parser->toffset,1); add_assoc_string(tag,"value",decoded_value,0); add_assoc_string(tag,"type","cdata",1); add_assoc_long(tag,"level",parser->level); zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),NULL); } } else { efree(decoded_value); } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'truncate results at depth of 255 to prevent corruption'</s>
<s>[INST] Given the following code containing errors, provide 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 _xml_startElementHandler(void *userData, const XML_Char *name, const XML_Char **attributes) { xml_parser *parser = (xml_parser *)userData; const char **attrs = (const char **) attributes; char *tag_name; char *att, *val; int val_len; zval *retval, *args[3]; if (parser) { parser->level++; tag_name = _xml_decode_tag(parser, name); if (parser->startElementHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_string_zval(((char *) tag_name) + parser->toffset); MAKE_STD_ZVAL(args[2]); array_init(args[2]); while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(args[2], att, val, val_len, 0); attributes += 2; efree(att); } if ((retval = xml_call_handler(parser, parser->startElementHandler, parser->startElementPtr, 3, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { zval *tag, *atr; int atcnt = 0; MAKE_STD_ZVAL(tag); MAKE_STD_ZVAL(atr); array_init(tag); array_init(atr); _xml_add_to_info(parser,((char *) tag_name) + parser->toffset); add_assoc_string(tag,"tag",((char *) tag_name) + parser->toffset,1); /* cast to avoid gcc-warning */ add_assoc_string(tag,"type","open",1); add_assoc_long(tag,"level",parser->level); parser->ltags[parser->level-1] = estrdup(tag_name); parser->lastwasopen = 1; attributes = (const XML_Char **) attrs; while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(atr,att,val,val_len,0); atcnt++; attributes += 2; efree(att); } if (atcnt) { zend_hash_add(Z_ARRVAL_P(tag),"attributes",sizeof("attributes"),&atr,sizeof(zval*),NULL); } else { zval_ptr_dtor(&atr); } zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),(void *) &parser->ctag); } efree(tag_name); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'truncate results at depth of 255 to prevent corruption'</s>
<s>[INST] Given the following code containing errors, provide 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 fib6_add_rt2node(struct fib6_node *fn, struct rt6_info *rt, struct nl_info *info) { struct rt6_info *iter = NULL; struct rt6_info **ins; int replace = (info->nlh && (info->nlh->nlmsg_flags & NLM_F_REPLACE)); int add = (!info->nlh || (info->nlh->nlmsg_flags & NLM_F_CREATE)); int found = 0; ins = &fn->leaf; for (iter = fn->leaf; iter; iter = iter->dst.rt6_next) { /* * Search for duplicates */ if (iter->rt6i_metric == rt->rt6i_metric) { /* * Same priority level */ if (info->nlh && (info->nlh->nlmsg_flags & NLM_F_EXCL)) return -EEXIST; if (replace) { found++; break; } if (iter->dst.dev == rt->dst.dev && iter->rt6i_idev == rt->rt6i_idev && ipv6_addr_equal(&iter->rt6i_gateway, &rt->rt6i_gateway)) { if (rt->rt6i_nsiblings) rt->rt6i_nsiblings = 0; if (!(iter->rt6i_flags & RTF_EXPIRES)) return -EEXIST; if (!(rt->rt6i_flags & RTF_EXPIRES)) rt6_clean_expires(iter); else rt6_set_expires(iter, rt->dst.expires); return -EEXIST; } /* If we have the same destination and the same metric, * but not the same gateway, then the route we try to * add is sibling to this route, increment our counter * of siblings, and later we will add our route to the * list. * Only static routes (which don't have flag * RTF_EXPIRES) are used for ECMPv6. * * To avoid long list, we only had siblings if the * route have a gateway. */ if (rt->rt6i_flags & RTF_GATEWAY && !(rt->rt6i_flags & RTF_EXPIRES) && !(iter->rt6i_flags & RTF_EXPIRES)) rt->rt6i_nsiblings++; } if (iter->rt6i_metric > rt->rt6i_metric) break; ins = &iter->dst.rt6_next; } /* Reset round-robin state, if necessary */ if (ins == &fn->leaf) fn->rr_ptr = NULL; /* Link this route to others same route. */ if (rt->rt6i_nsiblings) { unsigned int rt6i_nsiblings; struct rt6_info *sibling, *temp_sibling; /* Find the first route that have the same metric */ sibling = fn->leaf; while (sibling) { if (sibling->rt6i_metric == rt->rt6i_metric) { list_add_tail(&rt->rt6i_siblings, &sibling->rt6i_siblings); break; } sibling = sibling->dst.rt6_next; } /* For each sibling in the list, increment the counter of * siblings. BUG() if counters does not match, list of siblings * is broken! */ rt6i_nsiblings = 0; list_for_each_entry_safe(sibling, temp_sibling, &rt->rt6i_siblings, rt6i_siblings) { sibling->rt6i_nsiblings++; BUG_ON(sibling->rt6i_nsiblings != rt->rt6i_nsiblings); rt6i_nsiblings++; } BUG_ON(rt6i_nsiblings != rt->rt6i_nsiblings); } /* * insert node */ if (!replace) { if (!add) pr_warn("NLM_F_CREATE should be set when creating new route\n"); add: rt->dst.rt6_next = iter; *ins = rt; rt->rt6i_node = fn; atomic_inc(&rt->rt6i_ref); inet6_rt_notify(RTM_NEWROUTE, rt, info); info->nl_net->ipv6.rt6_stats->fib_rt_entries++; if (!(fn->fn_flags & RTN_RTINFO)) { info->nl_net->ipv6.rt6_stats->fib_route_nodes++; fn->fn_flags |= RTN_RTINFO; } } else { if (!found) { if (add) goto add; pr_warn("NLM_F_REPLACE set, but no existing node found!\n"); return -ENOENT; } *ins = rt; rt->rt6i_node = fn; rt->dst.rt6_next = iter->dst.rt6_next; atomic_inc(&rt->rt6i_ref); inet6_rt_notify(RTM_NEWROUTE, rt, info); rt6_release(iter); if (!(fn->fn_flags & RTN_RTINFO)) { info->nl_net->ipv6.rt6_stats->fib_route_nodes++; fn->fn_flags |= RTN_RTINFO; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'ipv6: only static routes qualify for equal cost multipathing Static routes in this case are non-expiring routes which did not get configured by autoconf or by icmpv6 redirects. To make sure we actually get an ecmp route while searching for the first one in this fib6_node's leafs, also make sure it matches the ecmp route assumptions. v2: a) Removed RTF_EXPIRE check in dst.from chain. The check of RTF_ADDRCONF already ensures that this route, even if added again without RTF_EXPIRES (in case of a RA announcement with infinite timeout), does not cause the rt6i_nsiblings logic to go wrong if a later RA updates the expiration time later. v3: a) Allow RTF_EXPIRES routes to enter the ecmp route set. We have to do so, because an pmtu event could update the RTF_EXPIRES flag and we would not count this route, if another route joins this set. We now filter only for RTF_GATEWAY|RTF_ADDRCONF|RTF_DYNAMIC, which are flags that don't get changed after rt6_info construction. Cc: Nicolas Dichtel <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: auth_shadow ( /* PARAMETERS */ const char *login, /* I: plaintext authenticator */ const char *password, /* I: plaintext password */ const char *service __attribute__((unused)), const char *realm __attribute__((unused)) /* END PARAMETERS */ ) { /************************************************************************ * * * This is gross. Everyone wants to do this differently, thus we have * * to #ifdef the whole mess for each system type. * * * ***********************************************************************/ # ifdef HAVE_GETSPNAM /*************** * getspnam_r() * ***************/ /* VARIABLES */ long today; /* the current time */ char *cpw; /* pointer to crypt() result */ struct passwd *pw; /* return from getpwnam_r() */ struct spwd *sp; /* return from getspnam_r() */ int errnum; # ifdef _REENTRANT struct passwd pwbuf; char pwdata[PWBUFSZ]; /* pwbuf indirect data goes in here */ struct spwd spbuf; char spdata[PWBUFSZ]; /* spbuf indirect data goes in here */ # endif /* _REENTRANT */ /* END VARIABLES */ # define RETURN(x) return strdup(x) /* * "Magic" password field entries for SunOS/SysV * * "*LK*" is defined at in the shadow(4) man page, but of course any string * inserted in front of the password will prevent the strings from matching * * *NP* is documented in getspnam(3) and indicates the caller had * insufficient permission to read the shadow password database * (generally this is a NIS error). */ # define SHADOW_PW_LOCKED "*LK*" /* account locked (not used by us) */ # define SHADOW_PW_EPERM "*NP*" /* insufficient database perms */ # ifdef _REENTRANT # ifdef GETXXNAM_R_5ARG (void) getpwnam_r(login, &pwbuf, pwdata, sizeof(pwdata), &pw); # else pw = getpwnam_r(login, &pwbuf, pwdata, sizeof(pwdata)); # endif /* GETXXNAM_R_5ARG */ # else pw = getpwnam(login); # endif /* _REENTRANT */ errnum = errno; endpwent(); if (pw == NULL) { if (errnum != 0) { char *errstr; if (flags & VERBOSE) { syslog(LOG_DEBUG, "DEBUG: auth_shadow: getpwnam(%s) failure: %m", login); } if (asprintf(&errstr, "NO Username lookup failure: %s", strerror(errno)) == -1) { /* XXX the hidden strdup() will likely fail and return NULL here.... */ RETURN("NO Username lookup failure: unknown error (ENOMEM formatting strerror())"); } return errstr; } else { if (flags & VERBOSE) { syslog(LOG_DEBUG, "DEBUG: auth_shadow: getpwnam(%s): invalid username", login); } RETURN("NO Invalid username"); } } today = (long)time(NULL)/(24L*60*60); # ifdef _REENTRANT # ifdef GETXXNAM_R_5ARG (void) getspnam_r(login, &spbuf, spdata, sizeof(spdata), &sp); # else sp = getspnam_r(login, &spbuf, spdata, sizeof(spdata)); # endif /* GETXXNAM_R_5ARG */ # else sp = getspnam(login); # endif /* _REENTRANT */ errnum = errno; endspent(); if (sp == NULL) { if (errnum != 0) { char *errstr; if (flags & VERBOSE) { syslog(LOG_DEBUG, "DEBUG: auth_shadow: getspnam(%s) failure: %m", login); } if (asprintf(&errstr, "NO Username shadow lookup failure: %s", strerror(errno)) == -1) { /* XXX the hidden strdup() will likely fail and return NULL here.... */ RETURN("NO Username shadow lookup failure: unknown error (ENOMEM formatting strerror())"); } return errstr; } else { if (flags & VERBOSE) { syslog(LOG_DEBUG, "DEBUG: auth_shadow: getspnam(%s): invalid shadow username", login); } RETURN("NO Invalid shadow username"); } } if (!strcmp(sp->sp_pwdp, SHADOW_PW_EPERM)) { if (flags & VERBOSE) { syslog(LOG_DEBUG, "DEBUG: auth_shadow: sp->sp_pwdp == SHADOW_PW_EPERM"); } RETURN("NO Insufficient permission to access NIS authentication database (saslauthd)"); } cpw = strdup((const char *)crypt(password, sp->sp_pwdp)); if (strcmp(sp->sp_pwdp, cpw)) { if (flags & VERBOSE) { /* * This _should_ reveal the SHADOW_PW_LOCKED prefix to an * administrator trying to debug the situation, though maybe we * should do the check here and be less obtuse about it.... */ syslog(LOG_DEBUG, "DEBUG: auth_shadow: pw mismatch: '%s' != '%s'", sp->sp_pwdp, cpw); } free(cpw); RETURN("NO Incorrect password"); } free(cpw); /* * The following fields will be set to -1 if: * * 1) They are not specified in the shadow database, or * 2) The database is being served up by NIS. */ if ((sp->sp_expire != -1) && (today > sp->sp_expire)) { if (flags & VERBOSE) { syslog(LOG_DEBUG, "DEBUG: auth_shadow: account expired: %dl > %dl", today, sp->sp_expire); } RETURN("NO Account expired"); } /* Remaining tests are relative to the last change date for the password */ if (sp->sp_lstchg != -1) { if ((sp->sp_max != -1) && ((sp->sp_lstchg + sp->sp_max) < today)) { if (flags & VERBOSE) { syslog(LOG_DEBUG, "DEBUG: auth_shadow: password expired: %ld + %ld < %ld", sp->sp_lstchg, sp->sp_max, today); } RETURN("NO Password expired"); } } if (flags & VERBOSE) { syslog(LOG_DEBUG, "DEBUG: auth_shadow: OK: %s", login); } RETURN("OK"); # elif defined(HAVE_GETUSERPW) /************* * AIX 4.1.4 * ************/ /* VARIABLES */ struct userpw *upw; /* return from getuserpw() */ /* END VARIABLES */ # define RETURN(x) { endpwdb(); return strdup(x); } if (setpwdb(S_READ) == -1) { syslog(LOG_ERR, "setpwdb: %m"); RETURN("NO setpwdb() internal failure (saslauthd)"); } upw = getuserpw(login); if (upw == 0) { if (flags & VERBOSE) { syslog(LOG_DEBUG, "auth_shadow: getuserpw(%s) failed: %m", login); } RETURN("NO Invalid username"); } if (strcmp(upw->upw_passwd, crypt(password, upw->upw_passwd)) != 0) { if (flags & VERBOSE) { syslog(LOG_DEBUG, "auth_shadow: pw mismatch: %s != %s", password, upw->upw_passwd); } RETURN("NO Incorrect password"); } RETURN("OK"); # else /* HAVE_GETUSERPW */ # error "unknown shadow authentication type" # endif /* ! HAVE_GETUSERPW */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Handle NULL returns from glibc 2.17+ crypt() Starting with glibc 2.17 (eglibc 2.17), crypt() fails with EINVAL (w/ NULL return) if the salt violates specifications. Additionally, on FIPS-140 enabled Linux systems, DES/MD5-encrypted passwords passed to crypt() fail with EPERM (w/ NULL return). When using glibc's crypt(), check return value to avoid a possible NULL pointer dereference. Patch by [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: char *pwcheck(userid, password) char *userid; char *password; { struct spwd *pwd; pwd = getspnam(userid); if (!pwd) { return "Userid not found"; } if (strcmp(pwd->sp_pwdp, crypt(password, pwd->sp_pwdp)) != 0) { return "Incorrect password"; } else { return "OK"; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Handle NULL returns from glibc 2.17+ crypt() Starting with glibc 2.17 (eglibc 2.17), crypt() fails with EINVAL (w/ NULL return) if the salt violates specifications. Additionally, on FIPS-140 enabled Linux systems, DES/MD5-encrypted passwords passed to crypt() fail with EPERM (w/ NULL return). When using glibc's crypt(), check return value to avoid a possible NULL pointer dereference. Patch by [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 vhost_net_ubuf_put_and_wait(struct vhost_net_ubuf_ref *ubufs) { kref_put(&ubufs->kref, vhost_net_zerocopy_done_signal); wait_event(ubufs->wait, !atomic_read(&ubufs->kref.refcount)); kfree(ubufs); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'vhost-net: fix use-after-free in vhost_net_flush vhost_net_ubuf_put_and_wait has a confusing name: it will actually also free it's argument. Thus since commit 1280c27f8e29acf4af2da914e80ec27c3dbd5c01 "vhost-net: flush outstanding DMAs on memory change" vhost_net_flush tries to use the argument after passing it to vhost_net_ubuf_put_and_wait, this results in use after free. To fix, don't free the argument in vhost_net_ubuf_put_and_wait, add an new API for callers that want to free ubufs. Acked-by: Asias He <[email protected]> Acked-by: Jason Wang <[email protected]> Signed-off-by: Michael S. Tsirkin <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int __br_mdb_del(struct net_bridge *br, struct br_mdb_entry *entry) { struct net_bridge_mdb_htable *mdb; struct net_bridge_mdb_entry *mp; struct net_bridge_port_group *p; struct net_bridge_port_group __rcu **pp; struct br_ip ip; int err = -EINVAL; if (!netif_running(br->dev) || br->multicast_disabled) return -EINVAL; if (timer_pending(&br->multicast_querier_timer)) return -EBUSY; ip.proto = entry->addr.proto; if (ip.proto == htons(ETH_P_IP)) ip.u.ip4 = entry->addr.u.ip4; #if IS_ENABLED(CONFIG_IPV6) else ip.u.ip6 = entry->addr.u.ip6; #endif spin_lock_bh(&br->multicast_lock); mdb = mlock_dereference(br->mdb, br); mp = br_mdb_ip_get(mdb, &ip); if (!mp) goto unlock; for (pp = &mp->ports; (p = mlock_dereference(*pp, br)) != NULL; pp = &p->next) { if (!p->port || p->port->dev->ifindex != entry->ifindex) continue; if (p->port->state == BR_STATE_DISABLED) goto unlock; rcu_assign_pointer(*pp, p->next); hlist_del_init(&p->mglist); del_timer(&p->timer); call_rcu_bh(&p->rcu, br_multicast_free_pg); err = 0; if (!mp->ports && !mp->mglist && netif_running(br->dev)) mod_timer(&mp->timer, jiffies); break; } unlock: spin_unlock_bh(&br->multicast_lock); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'bridge: fix some kernel warning in multicast timer Several people reported the warning: "kernel BUG at kernel/timer.c:729!" and the stack trace is: #7 [ffff880214d25c10] mod_timer+501 at ffffffff8106d905 #8 [ffff880214d25c50] br_multicast_del_pg.isra.20+261 at ffffffffa0731d25 [bridge] #9 [ffff880214d25c80] br_multicast_disable_port+88 at ffffffffa0732948 [bridge] #10 [ffff880214d25cb0] br_stp_disable_port+154 at ffffffffa072bcca [bridge] #11 [ffff880214d25ce8] br_device_event+520 at ffffffffa072a4e8 [bridge] #12 [ffff880214d25d18] notifier_call_chain+76 at ffffffff8164aafc #13 [ffff880214d25d50] raw_notifier_call_chain+22 at ffffffff810858f6 #14 [ffff880214d25d60] call_netdevice_notifiers+45 at ffffffff81536aad #15 [ffff880214d25d80] dev_close_many+183 at ffffffff81536d17 #16 [ffff880214d25dc0] rollback_registered_many+168 at ffffffff81537f68 #17 [ffff880214d25de8] rollback_registered+49 at ffffffff81538101 #18 [ffff880214d25e10] unregister_netdevice_queue+72 at ffffffff815390d8 #19 [ffff880214d25e30] __tun_detach+272 at ffffffffa074c2f0 [tun] #20 [ffff880214d25e88] tun_chr_close+45 at ffffffffa074c4bd [tun] #21 [ffff880214d25ea8] __fput+225 at ffffffff8119b1f1 #22 [ffff880214d25ef0] ____fput+14 at ffffffff8119b3fe #23 [ffff880214d25f00] task_work_run+159 at ffffffff8107cf7f #24 [ffff880214d25f30] do_notify_resume+97 at ffffffff810139e1 #25 [ffff880214d25f50] int_signal+18 at ffffffff8164f292 this is due to I forgot to check if mp->timer is armed in br_multicast_del_pg(). This bug is introduced by commit 9f00b2e7cf241fa389733d41b6 (bridge: only expire the mdb entry when query is received). Same for __br_mdb_del(). Tested-by: poma <[email protected]> Reported-by: LiYonghua <[email protected]> Reported-by: Robert Hancock <[email protected]> Cc: Herbert Xu <[email protected]> Cc: Stephen Hemminger <[email protected]> Cc: "David S. Miller" <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cmsSEQ* CMSEXPORT cmsAllocProfileSequenceDescription(cmsContext ContextID, cmsUInt32Number n) { cmsSEQ* Seq; cmsUInt32Number i; if (n == 0) return NULL; // In a absolutely arbitrary way, I hereby decide to allow a maxim of 255 profiles linked // in a devicelink. It makes not sense anyway and may be used for exploits, so let's close the door! if (n > 255) return NULL; Seq = (cmsSEQ*) _cmsMallocZero(ContextID, sizeof(cmsSEQ)); if (Seq == NULL) return NULL; Seq -> ContextID = ContextID; Seq -> seq = (cmsPSEQDESC*) _cmsCalloc(ContextID, n, sizeof(cmsPSEQDESC)); Seq -> n = n; for (i=0; i < n; i++) { Seq -> seq[i].Manufacturer = NULL; Seq -> seq[i].Model = NULL; Seq -> seq[i].Description = NULL; } return Seq; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'Non happy-path fixes'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Curves16Data* CurvesAlloc(cmsContext ContextID, int nCurves, int nElements, cmsToneCurve** G) { int i, j; Curves16Data* c16; c16 = _cmsMallocZero(ContextID, sizeof(Curves16Data)); if (c16 == NULL) return NULL; c16 ->nCurves = nCurves; c16 ->nElements = nElements; c16 ->Curves = _cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*)); if (c16 ->Curves == NULL) return NULL; for (i=0; i < nCurves; i++) { c16->Curves[i] = _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number)); if (nElements == 256) { for (j=0; j < nElements; j++) { c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j)); } } else { for (j=0; j < nElements; j++) { c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j); } } } return c16; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'Non happy-path fixes'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST_METHOD(5) { // The destructor doesnn't remove the server instance directory if it // wasn't created with the ownership flag or if it's been detached. string path, path2; { ServerInstanceDir dir(parentDir + "/passenger-test.1234", false); ServerInstanceDir dir2(parentDir + "/passenger-test.5678", false); dir2.detach(); path = dir.getPath(); path2 = dir2.getPath(); } ensure_equals(getFileType(path), FT_DIRECTORY); ensure_equals(getFileType(path2), FT_DIRECTORY); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'If the server instance directory already exists, it is now removed first in order get correct directory permissions. If the directory still exists after removal, Phusion Passenger aborts to avoid writing to a directory with unexpected permissions. Fixes issue #910.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: FileDescriptor connectToHelperAgent() { TRACE_POINT(); FileDescriptor conn; try { conn = connectToUnixServer(agentsStarter.getRequestSocketFilename()); writeExact(conn, agentsStarter.getRequestSocketPassword()); } catch (const SystemException &e) { if (e.code() == EPIPE || e.code() == ECONNREFUSED || e.code() == ENOENT) { UPDATE_TRACE_POINT(); bool connected = false; // Maybe the helper agent crashed. First wait 50 ms. usleep(50000); // Then try to reconnect to the helper agent for the // next 5 seconds. time_t deadline = time(NULL) + 5; while (!connected && time(NULL) < deadline) { try { conn = connectToUnixServer(agentsStarter.getRequestSocketFilename()); writeExact(conn, agentsStarter.getRequestSocketPassword()); connected = true; } catch (const SystemException &e) { if (e.code() == EPIPE || e.code() == ECONNREFUSED || e.code() == ENOENT) { // Looks like the helper agent hasn't been // restarted yet. Wait between 20 and 100 ms. usleep(20000 + rand() % 80000); // Don't care about thread-safety of rand() } else { throw; } } } if (!connected) { UPDATE_TRACE_POINT(); throw IOException("Cannot connect to the helper agent"); } } else { throw; } } return conn; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'Fixed a problem with graceful web server restarts. This problem was introduced in 4.0.6 during the attempt to fix issue #910.'</s>
<s>[INST] Given the following code containing errors, provide 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 initialize(const string &path, bool owner) { TRACE_POINT(); this->path = path; this->owner = owner; /* Create the server instance directory. We only need to write to this * directory for these reasons: * 1. Initial population of structure files (structure_version.txt, instance.pid). * 2. Creating/removing a generation directory. * 3. Removing the entire server instance directory (after all * generations are removed). * * 1 and 2 are done by the helper server during initialization and before lowering * privilege. 3 is done during helper server shutdown by a cleanup process that's * running as the same user the helper server was running as before privilege * lowering. * Therefore, we make the directory only writable by the user the helper server * was running as before privilege is lowered. Everybody else has read and execute * rights though, because we want admin tools to be able to list the available * generations no matter what user they're running as. */ if (owner) { switch (getFileType(path)) { case FT_NONEXISTANT: createDirectory(path); break; case FT_DIRECTORY: removeDirTree(path); createDirectory(path); break; default: throw RuntimeException("'" + path + "' already exists, and is not a directory"); } } else if (getFileType(path) != FT_DIRECTORY) { throw RuntimeException("Server instance directory '" + path + "' does not exist"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'Fixed a problem with graceful web server restarts. This problem was introduced in 4.0.6 during the attempt to fix issue #910.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PS_READ_FUNC(mm) { PS_MM_DATA; ps_sd *sd; int ret = FAILURE; mm_lock(data->mm, MM_LOCK_RD); sd = ps_sd_lookup(data, key, 0); if (sd) { *vallen = sd->datalen; *val = emalloc(sd->datalen + 1); memcpy(*val, sd->data, sd->datalen); (*val)[sd->datalen] = '\0'; ret = SUCCESS; } mm_unlock(data->mm); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Strict session'</s>
<s>[INST] Given the following code containing errors, provide 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_FUNCTION(session_id) { char *name = NULL; int name_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &name, &name_len) == FAILURE) { return; } if (PS(id)) { RETVAL_STRING(PS(id), 1); } else { RETVAL_EMPTY_STRING(); } if (name) { if (PS(id)) { efree(PS(id)); } PS(id) = estrndup(name, name_len); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Strict session'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHPAPI void php_session_start(TSRMLS_D) /* {{{ */ { zval **ppid; zval **data; char *p, *value; int nrand; int lensess; if (PS(use_only_cookies)) { PS(apply_trans_sid) = 0; } else { PS(apply_trans_sid) = PS(use_trans_sid); } switch (PS(session_status)) { case php_session_active: php_error(E_NOTICE, "A session had already been started - ignoring session_start()"); return; break; case php_session_disabled: value = zend_ini_string("session.save_handler", sizeof("session.save_handler"), 0); if (!PS(mod) && value) { PS(mod) = _php_find_ps_module(value TSRMLS_CC); if (!PS(mod)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot find save handler '%s' - session startup failed", value); return; } } value = zend_ini_string("session.serialize_handler", sizeof("session.serialize_handler"), 0); if (!PS(serializer) && value) { PS(serializer) = _php_find_ps_serializer(value TSRMLS_CC); if (!PS(serializer)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot find serialization handler '%s' - session startup failed", value); return; } } PS(session_status) = php_session_none; /* fallthrough */ default: case php_session_none: PS(define_sid) = 1; PS(send_cookie) = 1; } lensess = strlen(PS(session_name)); /* Cookies are preferred, because initially * cookie and get variables will be available. */ if (!PS(id)) { if (PS(use_cookies) && zend_hash_find(&EG(symbol_table), "_COOKIE", sizeof("_COOKIE"), (void **) &data) == SUCCESS && Z_TYPE_PP(data) == IS_ARRAY && zend_hash_find(Z_ARRVAL_PP(data), PS(session_name), lensess + 1, (void **) &ppid) == SUCCESS ) { PPID2SID; PS(apply_trans_sid) = 0; PS(send_cookie) = 0; PS(define_sid) = 0; } if (!PS(use_only_cookies) && !PS(id) && zend_hash_find(&EG(symbol_table), "_GET", sizeof("_GET"), (void **) &data) == SUCCESS && Z_TYPE_PP(data) == IS_ARRAY && zend_hash_find(Z_ARRVAL_PP(data), PS(session_name), lensess + 1, (void **) &ppid) == SUCCESS ) { PPID2SID; PS(send_cookie) = 0; } if (!PS(use_only_cookies) && !PS(id) && zend_hash_find(&EG(symbol_table), "_POST", sizeof("_POST"), (void **) &data) == SUCCESS && Z_TYPE_PP(data) == IS_ARRAY && zend_hash_find(Z_ARRVAL_PP(data), PS(session_name), lensess + 1, (void **) &ppid) == SUCCESS ) { PPID2SID; PS(send_cookie) = 0; } } /* Check the REQUEST_URI symbol for a string of the form * '<session-name>=<session-id>' to allow URLs of the form * http://yoursite/<session-name>=<session-id>/script.php */ if (!PS(use_only_cookies) && !PS(id) && PG(http_globals)[TRACK_VARS_SERVER] && zend_hash_find(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), "REQUEST_URI", sizeof("REQUEST_URI"), (void **) &data) == SUCCESS && Z_TYPE_PP(data) == IS_STRING && (p = strstr(Z_STRVAL_PP(data), PS(session_name))) && p[lensess] == '=' ) { char *q; p += lensess + 1; if ((q = strpbrk(p, "/?\\"))) { PS(id) = estrndup(p, q - p); PS(send_cookie) = 0; } } /* Check whether the current request was referred to by * an external site which invalidates the previously found id. */ if (PS(id) && PS(extern_referer_chk)[0] != '\0' && PG(http_globals)[TRACK_VARS_SERVER] && zend_hash_find(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), "HTTP_REFERER", sizeof("HTTP_REFERER"), (void **) &data) == SUCCESS && Z_TYPE_PP(data) == IS_STRING && Z_STRLEN_PP(data) != 0 && strstr(Z_STRVAL_PP(data), PS(extern_referer_chk)) == NULL ) { efree(PS(id)); PS(id) = NULL; PS(send_cookie) = 1; if (PS(use_trans_sid) && !PS(use_only_cookies)) { PS(apply_trans_sid) = 1; } } php_session_initialize(TSRMLS_C); if (!PS(use_cookies) && PS(send_cookie)) { if (PS(use_trans_sid) && !PS(use_only_cookies)) { PS(apply_trans_sid) = 1; } PS(send_cookie) = 0; } php_session_reset_id(TSRMLS_C); PS(session_status) = php_session_active; php_session_cache_limiter(TSRMLS_C); if ((PS(mod_data) || PS(mod_user_implemented)) && PS(gc_probability) > 0) { int nrdels = -1; nrand = (int) ((float) PS(gc_divisor) * php_combined_lcg(TSRMLS_C)); if (nrand < PS(gc_probability)) { PS(mod)->s_gc(&PS(mod_data), PS(gc_maxlifetime), &nrdels TSRMLS_CC); #ifdef SESSION_DEBUG if (nrdels != -1) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "purged %d expired session objects", nrdels); } #endif } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Strict session'</s>
<s>[INST] Given the following code containing errors, provide 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 php_session_reset_id(TSRMLS_D) /* {{{ */ { int module_number = PS(module_number); if (PS(use_cookies) && PS(send_cookie)) { php_session_send_cookie(TSRMLS_C); PS(send_cookie) = 0; } /* if the SID constant exists, destroy it. */ zend_hash_del(EG(zend_constants), "sid", sizeof("sid")); if (PS(define_sid)) { smart_str var = {0}; smart_str_appends(&var, PS(session_name)); smart_str_appendc(&var, '='); smart_str_appends(&var, PS(id)); smart_str_0(&var); REGISTER_STRINGL_CONSTANT("SID", var.c, var.len, 0); } else { REGISTER_STRINGL_CONSTANT("SID", STR_EMPTY_ALLOC(), 0, 0); } if (PS(apply_trans_sid)) { php_url_scanner_reset_vars(TSRMLS_C); php_url_scanner_add_var(PS(session_name), strlen(PS(session_name)), PS(id), strlen(PS(id)), 1 TSRMLS_CC); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Strict session'</s>
<s>[INST] Given the following code containing errors, provide 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 ps_sd *ps_sd_new(ps_mm *data, const char *key) { php_uint32 hv, slot; ps_sd *sd; int keylen; keylen = strlen(key); sd = mm_malloc(data->mm, sizeof(ps_sd) + keylen); if (!sd) { TSRMLS_FETCH(); php_error_docref(NULL TSRMLS_CC, E_WARNING, "mm_malloc failed, avail %d, err %s", mm_available(data->mm), mm_error()); return NULL; } hv = ps_sd_hash(key, keylen); slot = hv & data->hash_max; sd->ctime = 0; sd->hv = hv; sd->data = NULL; sd->alloclen = sd->datalen = 0; memcpy(sd->key, key, keylen + 1); sd->next = data->hash[slot]; data->hash[slot] = sd; data->hash_cnt++; if (!sd->next) { if (data->hash_cnt >= data->hash_max) { hash_split(data); } } ps_mm_debug(("inserting %s(%p) into slot %d\n", key, sd, slot)); return sd; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Strict session'</s>
<s>[INST] Given the following code containing errors, provide 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 php_session_initialize(TSRMLS_D) /* {{{ */ { char *val; int vallen; /* check session name for invalid characters */ if (PS(id) && strpbrk(PS(id), "\r\n\t <>'\"\\")) { efree(PS(id)); PS(id) = NULL; } if (!PS(mod)) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "No storage module chosen - failed to initialize session"); return; } /* Open session handler first */ if (PS(mod)->s_open(&PS(mod_data), PS(save_path), PS(session_name) TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Failed to initialize storage module: %s (path: %s)", PS(mod)->s_name, PS(save_path)); return; } /* If there is no ID, use session module to create one */ if (!PS(id)) { new_session: PS(id) = PS(mod)->s_create_sid(&PS(mod_data), NULL TSRMLS_CC); if (PS(use_cookies)) { PS(send_cookie) = 1; } } /* Read data */ /* Question: if you create a SID here, should you also try to read data? * I'm not sure, but while not doing so will remove one session operation * it could prove usefull for those sites which wish to have "default" * session information. */ php_session_track_init(TSRMLS_C); PS(invalid_session_id) = 0; if (PS(mod)->s_read(&PS(mod_data), PS(id), &val, &vallen TSRMLS_CC) == SUCCESS) { php_session_decode(val, vallen TSRMLS_CC); efree(val); } else if (PS(invalid_session_id)) { /* address instances where the session read fails due to an invalid id */ PS(invalid_session_id) = 0; efree(PS(id)); PS(id) = NULL; goto new_session; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Strict session'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PS_CREATE_SID_FUNC(mm) { char *sid; PS_MM_DATA; sid = php_session_create_id((void **)&data, newlen TSRMLS_CC); return sid; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Strict session. Detect session id collision'</s>
<s>[INST] Given the following code containing errors, provide 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_FUNCTION(session_id) { char *name = NULL; int name_len, argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "|s", &name, &name_len) == FAILURE) { return; } if (PS(id)) { RETVAL_STRING(PS(id), 1); } else { RETVAL_EMPTY_STRING(); } if (name) { if (PS(use_strict_mode) && argc) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Set session ID while session.use_strict_mode is enabled"); } if (PS(id)) { efree(PS(id)); } PS(id) = estrndup(name, name_len); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'fix crash, enable session_id and fix test'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(openssl_x509_parse) { zval ** zcert; X509 * cert = NULL; long certresource = -1; int i; zend_bool useshortnames = 1; char * tmpstr; zval * subitem; X509_EXTENSION *extension; char *extname; BIO *bio_out; BUF_MEM *bio_buf; char buf[256]; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z|b", &zcert, &useshortnames) == FAILURE) { return; } cert = php_openssl_x509_from_zval(zcert, 0, &certresource TSRMLS_CC); if (cert == NULL) { RETURN_FALSE; } array_init(return_value); if (cert->name) { add_assoc_string(return_value, "name", cert->name, 1); } /* add_assoc_bool(return_value, "valid", cert->valid); */ add_assoc_name_entry(return_value, "subject", X509_get_subject_name(cert), useshortnames TSRMLS_CC); /* hash as used in CA directories to lookup cert by subject name */ { char buf[32]; snprintf(buf, sizeof(buf), "%08lx", X509_subject_name_hash(cert)); add_assoc_string(return_value, "hash", buf, 1); } add_assoc_name_entry(return_value, "issuer", X509_get_issuer_name(cert), useshortnames TSRMLS_CC); add_assoc_long(return_value, "version", X509_get_version(cert)); add_assoc_string(return_value, "serialNumber", i2s_ASN1_INTEGER(NULL, X509_get_serialNumber(cert)), 1); add_assoc_asn1_string(return_value, "validFrom", X509_get_notBefore(cert)); add_assoc_asn1_string(return_value, "validTo", X509_get_notAfter(cert)); add_assoc_long(return_value, "validFrom_time_t", asn1_time_to_time_t(X509_get_notBefore(cert) TSRMLS_CC)); add_assoc_long(return_value, "validTo_time_t", asn1_time_to_time_t(X509_get_notAfter(cert) TSRMLS_CC)); tmpstr = (char *)X509_alias_get0(cert, NULL); if (tmpstr) { add_assoc_string(return_value, "alias", tmpstr, 1); } /* add_assoc_long(return_value, "signaturetypeLONG", X509_get_signature_type(cert)); add_assoc_string(return_value, "signaturetype", OBJ_nid2sn(X509_get_signature_type(cert)), 1); add_assoc_string(return_value, "signaturetypeLN", OBJ_nid2ln(X509_get_signature_type(cert)), 1); */ MAKE_STD_ZVAL(subitem); array_init(subitem); /* NOTE: the purposes are added as integer keys - the keys match up to the X509_PURPOSE_SSL_XXX defines in x509v3.h */ for (i = 0; i < X509_PURPOSE_get_count(); i++) { int id, purpset; char * pname; X509_PURPOSE * purp; zval * subsub; MAKE_STD_ZVAL(subsub); array_init(subsub); purp = X509_PURPOSE_get0(i); id = X509_PURPOSE_get_id(purp); purpset = X509_check_purpose(cert, id, 0); add_index_bool(subsub, 0, purpset); purpset = X509_check_purpose(cert, id, 1); add_index_bool(subsub, 1, purpset); pname = useshortnames ? X509_PURPOSE_get0_sname(purp) : X509_PURPOSE_get0_name(purp); add_index_string(subsub, 2, pname, 1); /* NOTE: if purpset > 1 then it's a warning - we should mention it ? */ add_index_zval(subitem, id, subsub); } add_assoc_zval(return_value, "purposes", subitem); MAKE_STD_ZVAL(subitem); array_init(subitem); for (i = 0; i < X509_get_ext_count(cert); i++) { extension = X509_get_ext(cert, i); if (OBJ_obj2nid(X509_EXTENSION_get_object(extension)) != NID_undef) { extname = (char *)OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(extension))); } else { OBJ_obj2txt(buf, sizeof(buf)-1, X509_EXTENSION_get_object(extension), 1); extname = buf; } bio_out = BIO_new(BIO_s_mem()); if (X509V3_EXT_print(bio_out, extension, 0, 0)) { BIO_get_mem_ptr(bio_out, &bio_buf); add_assoc_stringl(subitem, extname, bio_buf->data, bio_buf->length, 1); } else { add_assoc_asn1_string(subitem, extname, X509_EXTENSION_get_data(extension)); } BIO_free(bio_out); } add_assoc_zval(return_value, "extensions", subitem); if (certresource == -1 && cert) { X509_free(cert); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix CVE-2013-4073 - handling of certs with null bytes'</s>
<s>[INST] Given the following code containing errors, provide 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 ssl_parse_certificate( ssl_context *ssl ) { int ret; size_t i, n; SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) ); if( ssl->endpoint == SSL_IS_SERVER && ssl->authmode == SSL_VERIFY_NONE ) { ssl->verify_result = BADCERT_SKIP_VERIFY; SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); ssl->state++; return( 0 ); } if( ( ret = ssl_read_record( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_read_record", ret ); return( ret ); } ssl->state++; /* * Check if the client sent an empty certificate */ if( ssl->endpoint == SSL_IS_SERVER && ssl->minor_ver == SSL_MINOR_VERSION_0 ) { if( ssl->in_msglen == 2 && ssl->in_msgtype == SSL_MSG_ALERT && ssl->in_msg[0] == SSL_ALERT_LEVEL_WARNING && ssl->in_msg[1] == SSL_ALERT_MSG_NO_CERT ) { SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) ); ssl->verify_result = BADCERT_MISSING; if( ssl->authmode == SSL_VERIFY_OPTIONAL ) return( 0 ); else return( POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE ); } } if( ssl->endpoint == SSL_IS_SERVER && ssl->minor_ver != SSL_MINOR_VERSION_0 ) { if( ssl->in_hslen == 7 && ssl->in_msgtype == SSL_MSG_HANDSHAKE && ssl->in_msg[0] == SSL_HS_CERTIFICATE && memcmp( ssl->in_msg + 4, "\0\0\0", 3 ) == 0 ) { SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) ); ssl->verify_result = BADCERT_MISSING; if( ssl->authmode == SSL_VERIFY_REQUIRED ) return( POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE ); else return( 0 ); } } if( ssl->in_msgtype != SSL_MSG_HANDSHAKE ) { SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE ); } if( ssl->in_msg[0] != SSL_HS_CERTIFICATE || ssl->in_hslen < 10 ) { SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE ); } /* * Same message structure as in ssl_write_certificate() */ n = ( ssl->in_msg[5] << 8 ) | ssl->in_msg[6]; if( ssl->in_msg[4] != 0 || ssl->in_hslen != 7 + n ) { SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE ); } if( ( ssl->session_negotiate->peer_cert = (x509_cert *) malloc( sizeof( x509_cert ) ) ) == NULL ) { SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed", sizeof( x509_cert ) ) ); return( POLARSSL_ERR_SSL_MALLOC_FAILED ); } memset( ssl->session_negotiate->peer_cert, 0, sizeof( x509_cert ) ); i = 7; while( i < ssl->in_hslen ) { if( ssl->in_msg[i] != 0 ) { SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE ); } n = ( (unsigned int) ssl->in_msg[i + 1] << 8 ) | (unsigned int) ssl->in_msg[i + 2]; i += 3; if( n < 128 || i + n > ssl->in_hslen ) { SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE ); } ret = x509parse_crt( ssl->session_negotiate->peer_cert, ssl->in_msg + i, n ); if( ret != 0 ) { SSL_DEBUG_RET( 1, " x509parse_crt", ret ); return( ret ); } i += n; } SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert ); if( ssl->authmode != SSL_VERIFY_NONE ) { if( ssl->ca_chain == NULL ) { SSL_DEBUG_MSG( 1, ( "got no CA chain" ) ); return( POLARSSL_ERR_SSL_CA_CHAIN_REQUIRED ); } ret = x509parse_verify( ssl->session_negotiate->peer_cert, ssl->ca_chain, ssl->ca_crl, ssl->peer_cn, &ssl->verify_result, ssl->f_vrfy, ssl->p_vrfy ); if( ret != 0 ) SSL_DEBUG_RET( 1, "x509_verify_cert", ret ); if( ssl->authmode != SSL_VERIFY_REQUIRED ) ret = 0; } SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) ); return( ret ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'ssl_parse_certificate() now calls x509parse_crt_der() 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: LibRaw_byte_buffer *LibRaw_abstract_datastream::make_byte_buffer(unsigned int sz) { LibRaw_byte_buffer *ret = new LibRaw_byte_buffer(sz); read(ret->get_buffer(),sz,1); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'cumulated data checks patch'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: LibRaw_byte_buffer *LibRaw_buffer_datastream::make_byte_buffer(unsigned int sz) { LibRaw_byte_buffer *ret = new LibRaw_byte_buffer(0); if(streampos + sz > streamsize) sz = streamsize - streampos; ret->set_buffer(buf+streampos,sz); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'cumulated data checks patch'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void CLASS bad_pixels (const char *cfname) { FILE *fp=NULL; #ifndef LIBRAW_LIBRARY_BUILD char *fname, *cp, line[128]; int len, time, row, col, r, c, rad, tot, n, fixed=0; #else char *cp, line[128]; int time, row, col, r, c, rad, tot, n; #ifdef DCRAW_VERBOSE int fixed = 0; #endif #endif if (!filters) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS,0,2); #endif if (cfname) fp = fopen (cfname, "r"); #line 4009 "dcraw/dcraw.c" if (!fp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_BADPIXELMAP; #endif return; } while (fgets (line, 128, fp)) { cp = strchr (line, '#'); if (cp) *cp = 0; if (sscanf (line, "%d %d %d", &col, &row, &time) != 3) continue; if ((unsigned) col >= width || (unsigned) row >= height) continue; if (time > timestamp) continue; for (tot=n=0, rad=1; rad < 3 && n==0; rad++) for (r = row-rad; r <= row+rad; r++) for (c = col-rad; c <= col+rad; c++) if ((unsigned) r < height && (unsigned) c < width && (r != row || c != col) && fcol(r,c) == fcol(row,col)) { tot += BAYER2(r,c); n++; } BAYER2(row,col) = tot/n; #ifdef DCRAW_VERBOSE if (verbose) { if (!fixed++) fprintf (stderr,_("Fixed dead pixels at:")); fprintf (stderr, " %d,%d", col, row); } #endif } #ifdef DCRAW_VERBOSE if (fixed) fputc ('\n', stderr); #endif fclose (fp); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS,1,2); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'cumulated data checks patch'</s>
<s>[INST] Given the following code containing errors, provide 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 CLASS parse_tiff_ifd (int base) { unsigned entries, tag, type, len, plen=16, save; int ifd, use_cm=0, cfa, i, j, c, ima_len=0; int blrr=1, blrc=1, dblack[] = { 0,0,0,0 }; char software[64], *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256]; double cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 }; unsigned sony_curve[] = { 0,0,0,0,0,4095 }; unsigned *buf, sony_offset=0, sony_length=0, sony_key=0; struct jhead jh; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j=0; j < 4; j++) for (i=0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; while (entries--) { tiff_get (base, &tag, &type, &len, &save); switch (tag) { case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: filters = get2(); break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag-17)*2] = get2() / 256.0; break; case 23: if (type == 3) iso_speed = get2(); break; case 36: case 37: case 38: cam_mul[tag-0x24] = get2(); break; case 39: if (len < 50 || cam_mul[0]) break; fseek (ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ parse_tiff_ifd (base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); break; case 61446: raw_height = 0; load_raw = &CLASS packed_load_raw; load_flags = get4() && (filters=0x16161616) ? 24:80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread (desc, 512, 1, ifp); break; case 271: /* Make */ fgets (make, 64, ifp); break; case 272: /* Model */ fgets (model, 64, ifp); break; case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4()+base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; i = order; parse_tiff (tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7]-'0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: FORC3 cam_mul[(4-c) % 3] = getint(type); break; case 305: case 11: /* Software */ fgets (software, 64, ifp); if (!strncmp(software,"Adobe",5) || !strncmp(software,"dcraw",5) || !strncmp(software,"UFRaw",5) || !strncmp(software,"Bibble",6) || !strncmp(software,"Nikon Scan",10) || !strcmp (software,"Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread (artist, 64, 1, ifp); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; #ifdef LIBRAW_LIBRARY_BUILD case 325: /* TileByteCount */ tiff_ifd[ifd].tile_maxbytes = 0; for(int jj=0;jj<len;jj++) { int s = get4(); if(s > tiff_ifd[ifd].tile_maxbytes) tiff_ifd[ifd].tile_maxbytes=s; } break; #endif case 330: /* SubIFDs */ if (!strcmp(model,"DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4()+base; ifd++; break; } while (len--) { i = ftell(ifp); fseek (ifp, get4()+base, SEEK_SET); if (parse_tiff_ifd (base)) break; fseek (ifp, i+4, SEEK_SET); } break; case 400: strcpy (make, "Sarnoff"); maximum = 0xfff; break; case 28688: FORC4 sony_curve[c+1] = get2() >> 2 & 0xfff; for (i=0; i < 5; i++) for (j = sony_curve[i]+1; j <= sony_curve[i+1]; j++) curve[j] = curve[j-1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta (ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP (cam_mul[i],cam_mul[i+1]) break; case 33405: /* Model2 */ fgets (model2, 64, ifp); break; case 33422: /* CFAPattern */ case 64777: /* Kodak P-series */ if ((plen=len) > 16) plen = 16; fread (cfa_pat, 1, plen, ifp); for (colors=cfa=i=0; i < plen; i++) { colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy (cfa_pc,"\003\004\005",3); /* CMY */ if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4); /* GMCY */ goto guess_cfa_pc; case 33424: case 65024: fseek (ifp, get4()+base, SEEK_SET); parse_kodak_ifd (base); break; case 33434: /* ExposureTime */ shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; case 34306: /* Leaf white balance */ FORC4 cam_mul[c ^ 1] = 4096.0 / get2(); break; case 34307: /* Leaf CatchLight color matrix */ fread (software, 1, 7, ifp); if (strncmp(software,"MATRIX",6)) break; colors = 4; for (raw_color = i=0; i < 3; i++) { FORC4 fscanf (ifp, "%f", &rgb_cam[i][c^1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= num; } break; case 34310: /* Leaf metadata */ parse_mos (ftell(ifp)); case 34303: strcpy (make, "Leaf"); break; case 34665: /* EXIF tag */ fseek (ifp, get4()+base, SEEK_SET); parse_exif (base); break; case 34853: /* GPSInfo tag */ fseek (ifp, get4()+base, SEEK_SET); parse_gps (base); break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i=0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 46275: /* Imacon tags */ strcpy (make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek (ifp, 38, SEEK_CUR); case 46274: fseek (ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952 ) { height = 5412; width = 7216; left_margin = 7; filters=0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek (ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek (ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width,height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf (model, "Ixpress %d-Mp", height*width/1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (!(cbuf = (char *) malloc(len))) break; fread (cbuf, 1, len, ifp); for (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\n')) if (!strncmp (++cp,"Neutral ",8)) sscanf (cp+8, "%f %f %f", cam_mul, cam_mul+1, cam_mul+2); free (cbuf); break; case 50458: if (!make[0]) strcpy (make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek (ifp, j+(get2(),get4()), SEEK_SET); parse_tiff_ifd (j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy (make, "DNG"); is_raw = 1; break; case 50710: /* CFAPlaneColor */ if (len > 4) len = 4; colors = len; fread (cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i=16; i--; ) filters = filters << 2 | tab[cfa_pat[i % plen]]; break; case 50711: /* CFALayout */ if (get2() == 2) { fuji_width = 1; filters = 0x49494949; } break; case 291: case 50712: /* LinearizationTable */ linear_table (len); break; case 50713: /* BlackLevelRepeatDim */ blrr = get2(); blrc = get2(); break; case 61450: blrr = blrc = 2; case 50714: /* BlackLevel */ black = getreal(type); if (!filters || !~filters) break; dblack[0] = black; dblack[1] = (blrc == 2) ? getreal(type):dblack[0]; dblack[2] = (blrr == 2) ? getreal(type):dblack[0]; dblack[3] = (blrc == 2 && blrr == 2) ? getreal(type):dblack[1]; if (colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; FORC4 cblack[filters >> (c << 1) & 3] = dblack[c]; black = 0; break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num=i=0; i < len; i++) num += getreal(type); black += num/len + 0.5; break; case 50717: /* WhiteLevel */ maximum = getint(type); break; case 50718: /* DefaultScale */ pixel_aspect = getreal(type); pixel_aspect /= getreal(type); break; case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ FORCC for (j=0; j < 3; j++) cm[c][j] = getreal(type); use_cm = 1; break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ for (i=0; i < colors; i++) FORCC cc[i][c] = getreal(type); break; case 50727: /* AnalogBalance */ FORCC ab[c] = getreal(type); break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; case 50740: /* DNGPrivateData */ if (dng_version) break; parse_minolta (j = get4()+base); fseek (ifp, j, SEEK_SET); parse_tiff_ifd (base); break; case 50752: read_shorts (cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i=0; i < len && i < 32; i++) mask[0][i] = getint(type); black = 0; break; case 51009: /* OpcodeList2 */ meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek (ifp, 16, SEEK_CUR); data_offset = get4(); fseek (ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets (model2, 64, ifp); } fseek (ifp, save, SEEK_SET); } if (sony_length && (buf = (unsigned *) malloc(sony_length))) { fseek (ifp, sony_offset, SEEK_SET); fread (buf, sony_length, 1, ifp); sony_decrypt (buf, sony_length/4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite (buf, sony_length, 1, ifp); fseek (ifp, 0, SEEK_SET); parse_tiff_ifd (-sony_offset); fclose (ifp); } ifp = sfp; #else if( !ifp->tempbuffer_open(buf,sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free (buf); } for (i=0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i=0; i < 3; i++) for (cam_xyz[c][i]=j=0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff (cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC pre_mul[c] /= cc[c][c]; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'cumulated data checks patch'</s>
<s>[INST] Given the following code containing errors, provide 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 read_exceptions(struct pstore *ps, int (*callback)(void *callback_context, chunk_t old, chunk_t new), void *callback_context) { int r, full = 1; /* * Keeping reading chunks and inserting exceptions until * we find a partially full area. */ for (ps->current_area = 0; full; ps->current_area++) { r = area_io(ps, READ); if (r) return r; r = insert_exceptions(ps, callback, callback_context, &full); if (r) return r; } ps->current_area--; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-264'], 'message': 'dm snapshot: fix data corruption This patch fixes a particular type of data corruption that has been encountered when loading a snapshot's metadata from disk. When we allocate a new chunk in persistent_prepare, we increment ps->next_free and we make sure that it doesn't point to a metadata area by further incrementing it if necessary. When we load metadata from disk on device activation, ps->next_free is positioned after the last used data chunk. However, if this last used data chunk is followed by a metadata area, ps->next_free is positioned erroneously to the metadata area. A newly-allocated chunk is placed at the same location as the metadata area, resulting in data or metadata corruption. This patch changes the code so that ps->next_free skips the metadata area when metadata are loaded in function read_exceptions. The patch also moves a piece of code from persistent_prepare_exception to a separate function skip_metadata to avoid code duplication. CVE-2013-4299 Signed-off-by: Mikulas Patocka <[email protected]> Cc: [email protected] Cc: Mike Snitzer <[email protected]> Signed-off-by: Alasdair G Kergon <[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 sctp_v6_xmit(struct sk_buff *skb, struct sctp_transport *transport) { struct sock *sk = skb->sk; struct ipv6_pinfo *np = inet6_sk(sk); struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = sk->sk_protocol; /* Fill in the dest address from the route entry passed with the skb * and the source address from the transport. */ fl6.daddr = transport->ipaddr.v6.sin6_addr; fl6.saddr = transport->saddr.v6.sin6_addr; fl6.flowlabel = np->flow_label; IP6_ECN_flow_xmit(sk, fl6.flowlabel); if (ipv6_addr_type(&fl6.saddr) & IPV6_ADDR_LINKLOCAL) fl6.flowi6_oif = transport->saddr.v6.sin6_scope_id; else fl6.flowi6_oif = sk->sk_bound_dev_if; if (np->opt && np->opt->srcrt) { struct rt0_hdr *rt0 = (struct rt0_hdr *) np->opt->srcrt; fl6.daddr = *rt0->addr; } pr_debug("%s: skb:%p, len:%d, src:%pI6 dst:%pI6\n", __func__, skb, skb->len, &fl6.saddr, &fl6.daddr); SCTP_INC_STATS(sock_net(sk), SCTP_MIB_OUTSCTPPACKS); if (!(transport->param_flags & SPP_PMTUD_ENABLE)) skb->local_df = 1; return ip6_xmit(sk, skb, &fl6, np->opt, np->tclass); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'net: sctp: fix ipv6 ipsec encryption bug in sctp_v6_xmit Alan Chester reported an issue with IPv6 on SCTP that IPsec traffic is not being encrypted, whereas on IPv4 it is. Setting up an AH + ESP transport does not seem to have the desired effect: SCTP + IPv4: 22:14:20.809645 IP (tos 0x2,ECT(0), ttl 64, id 0, offset 0, flags [DF], proto AH (51), length 116) 192.168.0.2 > 192.168.0.5: AH(spi=0x00000042,sumlen=16,seq=0x1): ESP(spi=0x00000044,seq=0x1), length 72 22:14:20.813270 IP (tos 0x2,ECT(0), ttl 64, id 0, offset 0, flags [DF], proto AH (51), length 340) 192.168.0.5 > 192.168.0.2: AH(spi=0x00000043,sumlen=16,seq=0x1): SCTP + IPv6: 22:31:19.215029 IP6 (class 0x02, hlim 64, next-header SCTP (132) payload length: 364) fe80::222:15ff:fe87:7fc.3333 > fe80::92e6:baff:fe0d:5a54.36767: sctp 1) [INIT ACK] [init tag: 747759530] [rwnd: 62464] [OS: 10] [MIS: 10] Moreover, Alan says: This problem was seen with both Racoon and Racoon2. Other people have seen this with OpenSwan. When IPsec is configured to encrypt all upper layer protocols the SCTP connection does not initialize. After using Wireshark to follow packets, this is because the SCTP packet leaves Box A unencrypted and Box B believes all upper layer protocols are to be encrypted so it drops this packet, causing the SCTP connection to fail to initialize. When IPsec is configured to encrypt just SCTP, the SCTP packets are observed unencrypted. In fact, using `socat sctp6-listen:3333 -` on one end and transferring "plaintext" string on the other end, results in cleartext on the wire where SCTP eventually does not report any errors, thus in the latter case that Alan reports, the non-paranoid user might think he's communicating over an encrypted transport on SCTP although he's not (tcpdump ... -X): ... 0x0030: 5d70 8e1a 0003 001a 177d eb6c 0000 0000 ]p.......}.l.... 0x0040: 0000 0000 706c 6169 6e74 6578 740a 0000 ....plaintext... Only in /proc/net/xfrm_stat we can see XfrmInTmplMismatch increasing on the receiver side. Initial follow-up analysis from Alan's bug report was done by Alexey Dobriyan. Also thanks to Vlad Yasevich for feedback on this. SCTP has its own implementation of sctp_v6_xmit() not calling inet6_csk_xmit(). This has the implication that it probably never really got updated along with changes in inet6_csk_xmit() and therefore does not seem to invoke xfrm handlers. SCTP's IPv4 xmit however, properly calls ip_queue_xmit() to do the work. Since a call to inet6_csk_xmit() would solve this problem, but result in unecessary route lookups, let us just use the cached flowi6 instead that we got through sctp_v6_get_dst(). Since all SCTP packets are being sent through sctp_packet_transmit(), we do the route lookup / flow caching in sctp_transport_route(), hold it in tp->dst and skb_dst_set() right after that. If we would alter fl6->daddr in sctp_v6_xmit() to np->opt->srcrt, we possibly could run into the same effect of not having xfrm layer pick it up, hence, use fl6_update_dst() in sctp_v6_get_dst() instead to get the correct source routed dst entry, which we assign to the skb. Also source address routing example from 625034113 ("sctp: fix sctp to work with ipv6 source address routing") still works with this patch! Nevertheless, in RFC5095 it is actually 'recommended' to not use that anyway due to traffic amplification [1]. So it seems we're not supposed to do that anyway in sctp_v6_xmit(). Moreover, if we overwrite the flow destination here, the lower IPv6 layer will be unable to put the correct destination address into IP header, as routing header is added in ipv6_push_nfrag_opts() but then probably with wrong final destination. Things aside, result of this patch is that we do not have any XfrmInTmplMismatch increase plus on the wire with this patch it now looks like: SCTP + IPv6: 08:17:47.074080 IP6 2620:52:0:102f:7a2b:cbff:fe27:1b0a > 2620:52:0:102f:213:72ff:fe32:7eba: AH(spi=0x00005fb4,seq=0x1): ESP(spi=0x00005fb5,seq=0x1), length 72 08:17:47.074264 IP6 2620:52:0:102f:213:72ff:fe32:7eba > 2620:52:0:102f:7a2b:cbff:fe27:1b0a: AH(spi=0x00003d54,seq=0x1): ESP(spi=0x00003d55,seq=0x1), length 296 This fixes Kernel Bugzilla 24412. This security issue seems to be present since 2.6.18 kernels. Lets just hope some big passive adversary in the wild didn't have its fun with that. lksctp-tools IPv6 regression test suite passes as well with this patch. [1] http://www.secdev.org/conf/IPv6_RH_security-csw07.pdf Reported-by: Alan Chester <[email protected]> Reported-by: Alexey Dobriyan <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Cc: Steffen Klassert <[email protected]> Cc: Hannes Frederic Sowa <[email protected]> Acked-by: Vlad Yasevich <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_key_usage (PKT_signature * sig) { int key_usage = 0; const byte *p; size_t n; byte flags; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n); if (p && n) { /* First octet of the keyflags. */ flags = *p; if (flags & 1) { key_usage |= PUBKEY_USAGE_CERT; flags &= ~1; } if (flags & 2) { key_usage |= PUBKEY_USAGE_SIG; flags &= ~2; } /* We do not distinguish between encrypting communications and encrypting storage. */ if (flags & (0x04 | 0x08)) { key_usage |= PUBKEY_USAGE_ENC; flags &= ~(0x04 | 0x08); } if (flags & 0x20) { key_usage |= PUBKEY_USAGE_AUTH; flags &= ~0x20; } if (flags) key_usage |= PUBKEY_USAGE_UNKNOWN; } /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a capability that we do not handle. This serves to distinguish between a zero key usage which we handle as the default capabilities for that algorithm, and a usage that we do not handle. */ return key_usage; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'gpg: Distinguish between missing and cleared key flags. * include/cipher.h (PUBKEY_USAGE_NONE): New. * g10/getkey.c (parse_key_usage): Set new flag. -- We do not want to use the default capabilities (derived from the algorithm) if any key flags are given in a signature. Thus if key flags are used in any way, the default key capabilities are never used. This allows to create a key with key flags set to all zero so it can't be used. This better reflects common sense.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SYSCALL_DEFINE2(fchmod, unsigned int, fd, mode_t, mode) { struct inode * inode; struct dentry * dentry; struct file * file; int err = -EBADF; struct iattr newattrs; file = fget(fd); if (!file) goto out; dentry = file->f_path.dentry; inode = dentry->d_inode; audit_inode(NULL, dentry); err = mnt_want_write_file(file); if (err) goto out_putf; mutex_lock(&inode->i_mutex); err = security_path_chmod(dentry, file->f_vfsmnt, mode); if (err) goto out_unlock; if (mode == (mode_t) -1) mode = inode->i_mode; newattrs.ia_mode = (mode & S_IALLUGO) | (inode->i_mode & ~S_IALLUGO); newattrs.ia_valid = ATTR_MODE | ATTR_CTIME; err = notify_change(dentry, &newattrs); out_unlock: mutex_unlock(&inode->i_mutex); mnt_drop_write(file->f_path.mnt); out_putf: fput(file); out: return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-732'], 'message': 'merge fchmod() and fchmodat() guts, kill ancient broken kludge The kludge in question is undocumented and doesn't work for 32bit binaries on amd64, sparc64 and s390. Passing (mode_t)-1 as mode had (since 0.99.14v and contrary to behaviour of any other Unix, prescriptions of POSIX, SuS and our own manpages) was kinda-sorta no-op. Note that any software relying on that (and looking for examples shows none) would be visibly broken on sparc64, where practically all userland is built 32bit. No such complaints noticed... Signed-off-by: Al Viro <[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 rsa_pkcs1_decrypt( rsa_context *ctx, int mode, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len) { switch( ctx->padding ) { case RSA_PKCS_V15: return rsa_rsaes_pkcs1_v15_decrypt( ctx, mode, olen, input, output, output_max_len ); #if defined(POLARSSL_PKCS1_V21) case RSA_PKCS_V21: return rsa_rsaes_oaep_decrypt( ctx, mode, NULL, 0, olen, input, output, output_max_len ); #endif default: return( POLARSSL_ERR_RSA_INVALID_PADDING ); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main( int argc, char *argv[] ) { int keysize; unsigned long i, j, tsc; unsigned char tmp[64]; #if defined(POLARSSL_ARC4_C) arc4_context arc4; #endif #if defined(POLARSSL_DES_C) des3_context des3; des_context des; #endif #if defined(POLARSSL_AES_C) aes_context aes; #if defined(POLARSSL_GCM_C) gcm_context gcm; #endif #endif #if defined(POLARSSL_BLOWFISH_C) blowfish_context blowfish; #endif #if defined(POLARSSL_CAMELLIA_C) camellia_context camellia; #endif #if defined(POLARSSL_RSA_C) && defined(POLARSSL_BIGNUM_C) && \ defined(POLARSSL_GENPRIME) rsa_context rsa; #endif #if defined(POLARSSL_HAVEGE_C) havege_state hs; #endif #if defined(POLARSSL_CTR_DRBG_C) ctr_drbg_context ctr_drbg; #endif ((void) argc); ((void) argv); memset( buf, 0xAA, sizeof( buf ) ); printf( "\n" ); #if defined(POLARSSL_MD4_C) printf( HEADER_FORMAT, "MD4" ); fflush( stdout ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) md4( buf, BUFSIZE, tmp ); tsc = hardclock(); for( j = 0; j < 1024; j++ ) md4( buf, BUFSIZE, tmp ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_MD5_C) printf( HEADER_FORMAT, "MD5" ); fflush( stdout ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) md5( buf, BUFSIZE, tmp ); tsc = hardclock(); for( j = 0; j < 1024; j++ ) md5( buf, BUFSIZE, tmp ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_SHA1_C) printf( HEADER_FORMAT, "SHA-1" ); fflush( stdout ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) sha1( buf, BUFSIZE, tmp ); tsc = hardclock(); for( j = 0; j < 1024; j++ ) sha1( buf, BUFSIZE, tmp ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_SHA2_C) printf( HEADER_FORMAT, "SHA-256" ); fflush( stdout ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) sha2( buf, BUFSIZE, tmp, 0 ); tsc = hardclock(); for( j = 0; j < 1024; j++ ) sha2( buf, BUFSIZE, tmp, 0 ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_SHA4_C) printf( HEADER_FORMAT, "SHA-512" ); fflush( stdout ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) sha4( buf, BUFSIZE, tmp, 0 ); tsc = hardclock(); for( j = 0; j < 1024; j++ ) sha4( buf, BUFSIZE, tmp, 0 ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_ARC4_C) printf( HEADER_FORMAT, "ARC4" ); fflush( stdout ); arc4_setup( &arc4, tmp, 32 ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) arc4_crypt( &arc4, BUFSIZE, buf, buf ); tsc = hardclock(); for( j = 0; j < 1024; j++ ) arc4_crypt( &arc4, BUFSIZE, buf, buf ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_DES_C) printf( HEADER_FORMAT, "3DES" ); fflush( stdout ); des3_set3key_enc( &des3, tmp ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) des3_crypt_cbc( &des3, DES_ENCRYPT, BUFSIZE, tmp, buf, buf ); tsc = hardclock(); for( j = 0; j < 1024; j++ ) des3_crypt_cbc( &des3, DES_ENCRYPT, BUFSIZE, tmp, buf, buf ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); printf( HEADER_FORMAT, "DES" ); fflush( stdout ); des_setkey_enc( &des, tmp ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) des_crypt_cbc( &des, DES_ENCRYPT, BUFSIZE, tmp, buf, buf ); tsc = hardclock(); for( j = 0; j < 1024; j++ ) des_crypt_cbc( &des, DES_ENCRYPT, BUFSIZE, tmp, buf, buf ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_AES_C) for( keysize = 128; keysize <= 256; keysize += 64 ) { printf( " AES-CBC-%d : ", keysize ); fflush( stdout ); memset( buf, 0, sizeof( buf ) ); memset( tmp, 0, sizeof( tmp ) ); aes_setkey_enc( &aes, tmp, keysize ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) aes_crypt_cbc( &aes, AES_ENCRYPT, BUFSIZE, tmp, buf, buf ); tsc = hardclock(); for( j = 0; j < 4096; j++ ) aes_crypt_cbc( &aes, AES_ENCRYPT, BUFSIZE, tmp, buf, buf ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); } #if defined(POLARSSL_GCM_C) for( keysize = 128; keysize <= 256; keysize += 64 ) { printf( " AES-GCM-%d : ", keysize ); fflush( stdout ); memset( buf, 0, sizeof( buf ) ); memset( tmp, 0, sizeof( tmp ) ); gcm_init( &gcm, tmp, keysize ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) gcm_crypt_and_tag( &gcm, GCM_ENCRYPT, BUFSIZE, tmp, 12, NULL, 0, buf, buf, 16, tmp ); tsc = hardclock(); for( j = 0; j < 4096; j++ ) gcm_crypt_and_tag( &gcm, GCM_ENCRYPT, BUFSIZE, tmp, 12, NULL, 0, buf, buf, 16, tmp ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); } #endif #endif #if defined(POLARSSL_CAMELLIA_C) for( keysize = 128; keysize <= 256; keysize += 64 ) { printf( " CAMELLIA-CBC-%d: ", keysize ); fflush( stdout ); memset( buf, 0, sizeof( buf ) ); memset( tmp, 0, sizeof( tmp ) ); camellia_setkey_enc( &camellia, tmp, keysize ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) camellia_crypt_cbc( &camellia, CAMELLIA_ENCRYPT, BUFSIZE, tmp, buf, buf ); tsc = hardclock(); for( j = 0; j < 4096; j++ ) camellia_crypt_cbc( &camellia, CAMELLIA_ENCRYPT, BUFSIZE, tmp, buf, buf ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); } #endif #if defined(POLARSSL_BLOWFISH_C) for( keysize = 128; keysize <= 256; keysize += 64 ) { printf( " BLOWFISH-CBC-%d: ", keysize ); fflush( stdout ); memset( buf, 0, sizeof( buf ) ); memset( tmp, 0, sizeof( tmp ) ); blowfish_setkey( &blowfish, tmp, keysize ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) blowfish_crypt_cbc( &blowfish, BLOWFISH_ENCRYPT, BUFSIZE, tmp, buf, buf ); tsc = hardclock(); for( j = 0; j < 4096; j++ ) blowfish_crypt_cbc( &blowfish, BLOWFISH_ENCRYPT, BUFSIZE, tmp, buf, buf ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); } #endif #if defined(POLARSSL_HAVEGE_C) printf( HEADER_FORMAT, "HAVEGE" ); fflush( stdout ); havege_init( &hs ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) havege_random( &hs, buf, BUFSIZE ); tsc = hardclock(); for( j = 1; j < 1024; j++ ) havege_random( &hs, buf, BUFSIZE ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_CTR_DRBG_C) printf( HEADER_FORMAT, "CTR_DRBG (NOPR)" ); fflush( stdout ); if( ctr_drbg_init( &ctr_drbg, myrand, NULL, NULL, 0 ) != 0 ) exit(1); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 ) exit(1); tsc = hardclock(); for( j = 1; j < 1024; j++ ) if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 ) exit(1); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); printf( HEADER_FORMAT, "CTR_DRBG (PR)" ); fflush( stdout ); if( ctr_drbg_init( &ctr_drbg, myrand, NULL, NULL, 0 ) != 0 ) exit(1); ctr_drbg_set_prediction_resistance( &ctr_drbg, CTR_DRBG_PR_ON ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 ) exit(1); tsc = hardclock(); for( j = 1; j < 1024; j++ ) if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 ) exit(1); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_RSA_C) && defined(POLARSSL_BIGNUM_C) && \ defined(POLARSSL_GENPRIME) rsa_init( &rsa, RSA_PKCS_V15, 0 ); rsa_gen_key( &rsa, myrand, NULL, 1024, 65537 ); printf( HEADER_FORMAT, "RSA-1024" ); fflush( stdout ); set_alarm( 3 ); for( i = 1; ! alarmed; i++ ) { buf[0] = 0; rsa_public( &rsa, buf, buf ); } printf( "%9lu public/s\n", i / 3 ); printf( HEADER_FORMAT, "RSA-1024" ); fflush( stdout ); set_alarm( 3 ); for( i = 1; ! alarmed; i++ ) { buf[0] = 0; rsa_private( &rsa, buf, buf ); } printf( "%9lu private/s\n", i / 3 ); rsa_free( &rsa ); rsa_init( &rsa, RSA_PKCS_V15, 0 ); rsa_gen_key( &rsa, myrand, NULL, 2048, 65537 ); printf( HEADER_FORMAT, "RSA-2048" ); fflush( stdout ); set_alarm( 3 ); for( i = 1; ! alarmed; i++ ) { buf[0] = 0; rsa_public( &rsa, buf, buf ); } printf( "%9lu public/s\n", i / 3 ); printf( HEADER_FORMAT, "RSA-2048" ); fflush( stdout ); set_alarm( 3 ); for( i = 1; ! alarmed; i++ ) { buf[0] = 0; rsa_private( &rsa, buf, buf ); } printf( "%9lu private/s\n", i / 3 ); rsa_free( &rsa ); rsa_init( &rsa, RSA_PKCS_V15, 0 ); rsa_gen_key( &rsa, myrand, NULL, 4096, 65537 ); printf( HEADER_FORMAT, "RSA-4096" ); fflush( stdout ); set_alarm( 3 ); for( i = 1; ! alarmed; i++ ) { buf[0] = 0; rsa_public( &rsa, buf, buf ); } printf( "%9lu public/s\n", i / 3 ); printf( HEADER_FORMAT, "RSA-4096" ); fflush( stdout ); set_alarm( 3 ); for( i = 1; ! alarmed; i++ ) { buf[0] = 0; rsa_private( &rsa, buf, buf ); } printf( "%9lu private/s\n", i / 3 ); rsa_free( &rsa ); #endif printf( "\n" ); #if defined(_WIN32) printf( " Press Enter to exit this program.\n" ); fflush( stdout ); getchar(); #endif return( 0 ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main( int argc, char *argv[] ) { ((void) argc); ((void) argv); printf("POLARSSL_BIGNUM_C and/or POLARSSL_RSA_C and/or " "POLARSSL_SHA1_C and/or POLARSSL_X509_PARSE_C and/or " "POLARSSL_FS_IO not defined.\n"); return( 0 ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide 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 ssl_parse_server_key_exchange( ssl_context *ssl ) { #if defined(POLARSSL_DHM_C) int ret; size_t n; unsigned char *p, *end; unsigned char hash[64]; md5_context md5; sha1_context sha1; int hash_id = SIG_RSA_RAW; unsigned int hashlen = 0; #endif SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) ); if( ssl->session_negotiate->ciphersuite != TLS_DHE_RSA_WITH_DES_CBC_SHA && ssl->session_negotiate->ciphersuite != TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA && ssl->session_negotiate->ciphersuite != TLS_DHE_RSA_WITH_AES_128_CBC_SHA && ssl->session_negotiate->ciphersuite != TLS_DHE_RSA_WITH_AES_256_CBC_SHA && ssl->session_negotiate->ciphersuite != TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 && ssl->session_negotiate->ciphersuite != TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 && ssl->session_negotiate->ciphersuite != TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA && ssl->session_negotiate->ciphersuite != TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA && ssl->session_negotiate->ciphersuite != TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 && ssl->session_negotiate->ciphersuite != TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 && ssl->session_negotiate->ciphersuite != TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 && ssl->session_negotiate->ciphersuite != TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 ) { SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) ); ssl->state++; return( 0 ); } #if !defined(POLARSSL_DHM_C) SSL_DEBUG_MSG( 1, ( "support for dhm in not available" ) ); return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE ); #else if( ( ret = ssl_read_record( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != SSL_MSG_HANDSHAKE ) { SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE ); } if( ssl->in_msg[0] != SSL_HS_SERVER_KEY_EXCHANGE ) { SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } SSL_DEBUG_BUF( 3, "server key exchange", ssl->in_msg + 4, ssl->in_hslen - 4 ); /* * Ephemeral DH parameters: * * struct { * opaque dh_p<1..2^16-1>; * opaque dh_g<1..2^16-1>; * opaque dh_Ys<1..2^16-1>; * } ServerDHParams; */ p = ssl->in_msg + 4; end = ssl->in_msg + ssl->in_hslen; if( ( ret = dhm_read_params( &ssl->handshake->dhm_ctx, &p, end ) ) != 0 ) { SSL_DEBUG_MSG( 2, ( "DHM Read Params returned -0x%x", -ret ) ); SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } if( ssl->minor_ver == SSL_MINOR_VERSION_3 ) { if( p[1] != SSL_SIG_RSA ) { SSL_DEBUG_MSG( 2, ( "server used unsupported SignatureAlgorithm %d", p[1] ) ); SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } switch( p[0] ) { #if defined(POLARSSL_MD5_C) case SSL_HASH_MD5: hash_id = SIG_RSA_MD5; break; #endif #if defined(POLARSSL_SHA1_C) case SSL_HASH_SHA1: hash_id = SIG_RSA_SHA1; break; #endif #if defined(POLARSSL_SHA2_C) case SSL_HASH_SHA224: hash_id = SIG_RSA_SHA224; break; case SSL_HASH_SHA256: hash_id = SIG_RSA_SHA256; break; #endif #if defined(POLARSSL_SHA4_C) case SSL_HASH_SHA384: hash_id = SIG_RSA_SHA384; break; case SSL_HASH_SHA512: hash_id = SIG_RSA_SHA512; break; #endif default: SSL_DEBUG_MSG( 2, ( "Server used unsupported HashAlgorithm %d", p[0] ) ); SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } SSL_DEBUG_MSG( 2, ( "Server used SignatureAlgorithm %d", p[1] ) ); SSL_DEBUG_MSG( 2, ( "Server used HashAlgorithm %d", p[0] ) ); p += 2; } n = ( p[0] << 8 ) | p[1]; p += 2; if( end != p + n ) { SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } if( (unsigned int)( end - p ) != ssl->session_negotiate->peer_cert->rsa.len ) { SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } if( ssl->handshake->dhm_ctx.len < 64 || ssl->handshake->dhm_ctx.len > 512 ) { SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P ); SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G ); SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY ); if( ssl->minor_ver != SSL_MINOR_VERSION_3 ) { /* * digitally-signed struct { * opaque md5_hash[16]; * opaque sha_hash[20]; * }; * * md5_hash * MD5(ClientHello.random + ServerHello.random * + ServerParams); * sha_hash * SHA(ClientHello.random + ServerHello.random * + ServerParams); */ n = ssl->in_hslen - ( end - p ) - 6; md5_starts( &md5 ); md5_update( &md5, ssl->handshake->randbytes, 64 ); md5_update( &md5, ssl->in_msg + 4, n ); md5_finish( &md5, hash ); sha1_starts( &sha1 ); sha1_update( &sha1, ssl->handshake->randbytes, 64 ); sha1_update( &sha1, ssl->in_msg + 4, n ); sha1_finish( &sha1, hash + 16 ); hash_id = SIG_RSA_RAW; hashlen = 36; } else { sha2_context sha2; #if defined(POLARSSL_SHA4_C) sha4_context sha4; #endif n = ssl->in_hslen - ( end - p ) - 8; /* * digitally-signed struct { * opaque client_random[32]; * opaque server_random[32]; * ServerDHParams params; * }; */ switch( hash_id ) { #if defined(POLARSSL_MD5_C) case SIG_RSA_MD5: md5_starts( &md5 ); md5_update( &md5, ssl->handshake->randbytes, 64 ); md5_update( &md5, ssl->in_msg + 4, n ); md5_finish( &md5, hash ); hashlen = 16; break; #endif #if defined(POLARSSL_SHA1_C) case SIG_RSA_SHA1: sha1_starts( &sha1 ); sha1_update( &sha1, ssl->handshake->randbytes, 64 ); sha1_update( &sha1, ssl->in_msg + 4, n ); sha1_finish( &sha1, hash ); hashlen = 20; break; #endif #if defined(POLARSSL_SHA2_C) case SIG_RSA_SHA224: sha2_starts( &sha2, 1 ); sha2_update( &sha2, ssl->handshake->randbytes, 64 ); sha2_update( &sha2, ssl->in_msg + 4, n ); sha2_finish( &sha2, hash ); hashlen = 28; break; case SIG_RSA_SHA256: sha2_starts( &sha2, 0 ); sha2_update( &sha2, ssl->handshake->randbytes, 64 ); sha2_update( &sha2, ssl->in_msg + 4, n ); sha2_finish( &sha2, hash ); hashlen = 32; break; #endif #if defined(POLARSSL_SHA4_C) case SIG_RSA_SHA384: sha4_starts( &sha4, 1 ); sha4_update( &sha4, ssl->handshake->randbytes, 64 ); sha4_update( &sha4, ssl->in_msg + 4, n ); sha4_finish( &sha4, hash ); hashlen = 48; break; case SIG_RSA_SHA512: sha4_starts( &sha4, 0 ); sha4_update( &sha4, ssl->handshake->randbytes, 64 ); sha4_update( &sha4, ssl->in_msg + 4, n ); sha4_finish( &sha4, hash ); hashlen = 64; break; #endif } } SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen ); if( ( ret = rsa_pkcs1_verify( &ssl->session_negotiate->peer_cert->rsa, RSA_PUBLIC, hash_id, hashlen, hash, p ) ) != 0 ) { SSL_DEBUG_RET( 1, "rsa_pkcs1_verify", ret ); return( ret ); } ssl->state++; SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) ); return( 0 ); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main( int argc, char *argv[] ) { FILE *f; int ret, c; size_t i; rsa_context rsa; unsigned char result[1024]; unsigned char buf[512]; ((void) argv); memset(result, 0, sizeof( result ) ); ret = 1; if( argc != 1 ) { printf( "usage: rsa_decrypt\n" ); #if defined(_WIN32) printf( "\n" ); #endif goto exit; } printf( "\n . Reading private key from rsa_priv.txt" ); fflush( stdout ); if( ( f = fopen( "rsa_priv.txt", "rb" ) ) == NULL ) { printf( " failed\n ! Could not open rsa_priv.txt\n" \ " ! Please run rsa_genkey first\n\n" ); goto exit; } rsa_init( &rsa, RSA_PKCS_V15, 0 ); if( ( ret = mpi_read_file( &rsa.N , 16, f ) ) != 0 || ( ret = mpi_read_file( &rsa.E , 16, f ) ) != 0 || ( ret = mpi_read_file( &rsa.D , 16, f ) ) != 0 || ( ret = mpi_read_file( &rsa.P , 16, f ) ) != 0 || ( ret = mpi_read_file( &rsa.Q , 16, f ) ) != 0 || ( ret = mpi_read_file( &rsa.DP, 16, f ) ) != 0 || ( ret = mpi_read_file( &rsa.DQ, 16, f ) ) != 0 || ( ret = mpi_read_file( &rsa.QP, 16, f ) ) != 0 ) { printf( " failed\n ! mpi_read_file returned %d\n\n", ret ); goto exit; } rsa.len = ( mpi_msb( &rsa.N ) + 7 ) >> 3; fclose( f ); /* * Extract the RSA encrypted value from the text file */ ret = 1; if( ( f = fopen( "result-enc.txt", "rb" ) ) == NULL ) { printf( "\n ! Could not open %s\n\n", "result-enc.txt" ); goto exit; } i = 0; while( fscanf( f, "%02X", &c ) > 0 && i < (int) sizeof( buf ) ) buf[i++] = (unsigned char) c; fclose( f ); if( i != rsa.len ) { printf( "\n ! Invalid RSA signature format\n\n" ); goto exit; } /* * Decrypt the encrypted RSA data and print the result. */ printf( "\n . Decrypting the encrypted data" ); fflush( stdout ); if( ( ret = rsa_pkcs1_decrypt( &rsa, RSA_PRIVATE, &i, buf, result, 1024 ) ) != 0 ) { printf( " failed\n ! rsa_pkcs1_decrypt returned %d\n\n", ret ); goto exit; } printf( "\n . OK\n\n" ); printf( "The decrypted result is: '%s'\n\n", result ); ret = 0; exit: #if defined(_WIN32) printf( " + Press Enter to exit this program.\n" ); fflush( stdout ); getchar(); #endif return( ret ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide 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 rsa_rsaes_pkcs1_v15_decrypt( rsa_context *ctx, int mode, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len) { int ret, correct = 1; size_t ilen, pad_count = 0; unsigned char *p, *q; unsigned char bt; unsigned char buf[POLARSSL_MPI_MAX_SIZE]; if( ctx->padding != RSA_PKCS_V15 ) return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); ilen = ctx->len; if( ilen < 16 || ilen > sizeof( buf ) ) return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); ret = ( mode == RSA_PUBLIC ) ? rsa_public( ctx, input, buf ) : rsa_private( ctx, input, buf ); if( ret != 0 ) return( ret ); p = buf; if( *p++ != 0 ) correct = 0; bt = *p++; if( ( bt != RSA_CRYPT && mode == RSA_PRIVATE ) || ( bt != RSA_SIGN && mode == RSA_PUBLIC ) ) { correct = 0; } if( bt == RSA_CRYPT ) { while( *p != 0 && p < buf + ilen - 1 ) pad_count += ( *p++ != 0 ); correct &= ( *p == 0 && p < buf + ilen - 1 ); q = p; // Also pass over all other bytes to reduce timing differences // while ( q < buf + ilen - 1 ) pad_count += ( *q++ != 0 ); // Prevent compiler optimization of pad_count // correct |= pad_count & 0x100000; /* Always 0 unless 1M bit keys */ p++; } else { while( *p == 0xFF && p < buf + ilen - 1 ) pad_count += ( *p++ == 0xFF ); correct &= ( *p == 0 && p < buf + ilen - 1 ); q = p; // Also pass over all other bytes to reduce timing differences // while ( q < buf + ilen - 1 ) pad_count += ( *q++ != 0 ); // Prevent compiler optimization of pad_count // correct |= pad_count & 0x100000; /* Always 0 unless 1M bit keys */ p++; } if( correct == 0 ) return( POLARSSL_ERR_RSA_INVALID_PADDING ); if (ilen - (p - buf) > output_max_len) return( POLARSSL_ERR_RSA_OUTPUT_TOO_LARGE ); *olen = ilen - (p - buf); memcpy( output, p, *olen ); return( 0 ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide 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 rsa_rsassa_pkcs1_v15_sign( rsa_context *ctx, int mode, int hash_id, unsigned int hashlen, const unsigned char *hash, unsigned char *sig ) { size_t nb_pad, olen; unsigned char *p = sig; if( ctx->padding != RSA_PKCS_V15 ) return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); olen = ctx->len; switch( hash_id ) { case SIG_RSA_RAW: nb_pad = olen - 3 - hashlen; break; case SIG_RSA_MD2: case SIG_RSA_MD4: case SIG_RSA_MD5: nb_pad = olen - 3 - 34; break; case SIG_RSA_SHA1: nb_pad = olen - 3 - 35; break; case SIG_RSA_SHA224: nb_pad = olen - 3 - 47; break; case SIG_RSA_SHA256: nb_pad = olen - 3 - 51; break; case SIG_RSA_SHA384: nb_pad = olen - 3 - 67; break; case SIG_RSA_SHA512: nb_pad = olen - 3 - 83; break; default: return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); } if( ( nb_pad < 8 ) || ( nb_pad > olen ) ) return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); *p++ = 0; *p++ = RSA_SIGN; memset( p, 0xFF, nb_pad ); p += nb_pad; *p++ = 0; switch( hash_id ) { case SIG_RSA_RAW: memcpy( p, hash, hashlen ); break; case SIG_RSA_MD2: memcpy( p, ASN1_HASH_MDX, 18 ); memcpy( p + 18, hash, 16 ); p[13] = 2; break; case SIG_RSA_MD4: memcpy( p, ASN1_HASH_MDX, 18 ); memcpy( p + 18, hash, 16 ); p[13] = 4; break; case SIG_RSA_MD5: memcpy( p, ASN1_HASH_MDX, 18 ); memcpy( p + 18, hash, 16 ); p[13] = 5; break; case SIG_RSA_SHA1: memcpy( p, ASN1_HASH_SHA1, 15 ); memcpy( p + 15, hash, 20 ); break; case SIG_RSA_SHA224: memcpy( p, ASN1_HASH_SHA2X, 19 ); memcpy( p + 19, hash, 28 ); p[1] += 28; p[14] = 4; p[18] += 28; break; case SIG_RSA_SHA256: memcpy( p, ASN1_HASH_SHA2X, 19 ); memcpy( p + 19, hash, 32 ); p[1] += 32; p[14] = 1; p[18] += 32; break; case SIG_RSA_SHA384: memcpy( p, ASN1_HASH_SHA2X, 19 ); memcpy( p + 19, hash, 48 ); p[1] += 48; p[14] = 2; p[18] += 48; break; case SIG_RSA_SHA512: memcpy( p, ASN1_HASH_SHA2X, 19 ); memcpy( p + 19, hash, 64 ); p[1] += 64; p[14] = 3; p[18] += 64; break; default: return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); } return( ( mode == RSA_PUBLIC ) ? rsa_public( ctx, sig, sig ) : rsa_private( ctx, sig, sig ) ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide 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 x509parse_verify_child( x509_cert *child, x509_cert *parent, x509_cert *trust_ca, x509_crl *ca_crl, int path_cnt, int *flags, int (*f_vrfy)(void *, x509_cert *, int, int *), void *p_vrfy ) { int hash_id, ret; int parent_flags = 0; unsigned char hash[64]; x509_cert *grandparent; if( x509parse_time_expired( &child->valid_to ) ) *flags |= BADCERT_EXPIRED; hash_id = child->sig_alg; x509_hash( child->tbs.p, child->tbs.len, hash_id, hash ); if( rsa_pkcs1_verify( &parent->rsa, RSA_PUBLIC, hash_id, 0, hash, child->sig.p ) != 0 ) *flags |= BADCERT_NOT_TRUSTED; /* Check trusted CA's CRL for the given crt */ *flags |= x509parse_verifycrl(child, parent, ca_crl); grandparent = parent->next; while( grandparent != NULL ) { if( grandparent->version == 0 || grandparent->ca_istrue == 0 || parent->issuer_raw.len != grandparent->subject_raw.len || memcmp( parent->issuer_raw.p, grandparent->subject_raw.p, parent->issuer_raw.len ) != 0 ) { grandparent = grandparent->next; continue; } break; } if( grandparent != NULL ) { /* * Part of the chain */ ret = x509parse_verify_child( parent, grandparent, trust_ca, ca_crl, path_cnt + 1, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } else { ret = x509parse_verify_top( parent, trust_ca, ca_crl, path_cnt + 1, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } /* child is verified to be a child of the parent, call verify callback */ if( NULL != f_vrfy ) if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 ) return( ret ); *flags |= parent_flags; return( 0 ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main( int argc, char *argv[] ) { ((void) argc); ((void) argv); printf("POLARSSL_BIGNUM_C and/or POLARSSL_RSA_C and/or " "POLARSSL_SHA1_C and/or POLARSSL_FS_IO not defined.\n"); return( 0 ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide 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 ssl_rsa_decrypt( void *ctx, int mode, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len ) { return rsa_pkcs1_decrypt( (rsa_context *) ctx, mode, olen, input, output, output_max_len ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide 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 myrand( void *rng_state, unsigned char *output, size_t len ) { size_t i; if( rng_state != NULL ) rng_state = NULL; for( i = 0; i < len; ++i ) output[i] = rand(); return( 0 ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide 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 rsa_self_test( int verbose ) { size_t len; rsa_context rsa; unsigned char rsa_plaintext[PT_LEN]; unsigned char rsa_decrypted[PT_LEN]; unsigned char rsa_ciphertext[KEY_LEN]; #if defined(POLARSSL_SHA1_C) unsigned char sha1sum[20]; #endif rsa_init( &rsa, RSA_PKCS_V15, 0 ); rsa.len = KEY_LEN; mpi_read_string( &rsa.N , 16, RSA_N ); mpi_read_string( &rsa.E , 16, RSA_E ); mpi_read_string( &rsa.D , 16, RSA_D ); mpi_read_string( &rsa.P , 16, RSA_P ); mpi_read_string( &rsa.Q , 16, RSA_Q ); mpi_read_string( &rsa.DP, 16, RSA_DP ); mpi_read_string( &rsa.DQ, 16, RSA_DQ ); mpi_read_string( &rsa.QP, 16, RSA_QP ); if( verbose != 0 ) printf( " RSA key validation: " ); if( rsa_check_pubkey( &rsa ) != 0 || rsa_check_privkey( &rsa ) != 0 ) { if( verbose != 0 ) printf( "failed\n" ); return( 1 ); } if( verbose != 0 ) printf( "passed\n PKCS#1 encryption : " ); memcpy( rsa_plaintext, RSA_PT, PT_LEN ); if( rsa_pkcs1_encrypt( &rsa, &myrand, NULL, RSA_PUBLIC, PT_LEN, rsa_plaintext, rsa_ciphertext ) != 0 ) { if( verbose != 0 ) printf( "failed\n" ); return( 1 ); } if( verbose != 0 ) printf( "passed\n PKCS#1 decryption : " ); if( rsa_pkcs1_decrypt( &rsa, RSA_PRIVATE, &len, rsa_ciphertext, rsa_decrypted, sizeof(rsa_decrypted) ) != 0 ) { if( verbose != 0 ) printf( "failed\n" ); return( 1 ); } if( memcmp( rsa_decrypted, rsa_plaintext, len ) != 0 ) { if( verbose != 0 ) printf( "failed\n" ); return( 1 ); } #if defined(POLARSSL_SHA1_C) if( verbose != 0 ) printf( "passed\n PKCS#1 data sign : " ); sha1( rsa_plaintext, PT_LEN, sha1sum ); if( rsa_pkcs1_sign( &rsa, NULL, NULL, RSA_PRIVATE, SIG_RSA_SHA1, 20, sha1sum, rsa_ciphertext ) != 0 ) { if( verbose != 0 ) printf( "failed\n" ); return( 1 ); } if( verbose != 0 ) printf( "passed\n PKCS#1 sig. verify: " ); if( rsa_pkcs1_verify( &rsa, RSA_PUBLIC, SIG_RSA_SHA1, 20, sha1sum, rsa_ciphertext ) != 0 ) { if( verbose != 0 ) printf( "failed\n" ); return( 1 ); } if( verbose != 0 ) printf( "passed\n\n" ); #endif /* POLARSSL_SHA1_C */ rsa_free( &rsa ); return( 0 ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide 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 rsa_rsaes_oaep_encrypt( rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, const unsigned char *label, size_t label_len, size_t ilen, const unsigned char *input, unsigned char *output ) { size_t olen; int ret; unsigned char *p = output; unsigned int hlen; const md_info_t *md_info; md_context_t md_ctx; if( ctx->padding != RSA_PKCS_V21 || f_rng == NULL ) return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); md_info = md_info_from_type( ctx->hash_id ); if( md_info == NULL ) return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); olen = ctx->len; hlen = md_get_size( md_info ); if( olen < ilen + 2 * hlen + 2 || f_rng == NULL ) return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); memset( output, 0, olen ); *p++ = 0; // Generate a random octet string seed // if( ( ret = f_rng( p_rng, p, hlen ) ) != 0 ) return( POLARSSL_ERR_RSA_RNG_FAILED + ret ); p += hlen; // Construct DB // md( md_info, label, label_len, p ); p += hlen; p += olen - 2 * hlen - 2 - ilen; *p++ = 1; memcpy( p, input, ilen ); md_init_ctx( &md_ctx, md_info ); // maskedDB: Apply dbMask to DB // mgf_mask( output + hlen + 1, olen - hlen - 1, output + 1, hlen, &md_ctx ); // maskedSeed: Apply seedMask to seed // mgf_mask( output + 1, hlen, output + hlen + 1, olen - hlen - 1, &md_ctx ); md_free_ctx( &md_ctx ); return( ( mode == RSA_PUBLIC ) ? rsa_public( ctx, output, output ) : rsa_private( ctx, output, output ) ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide 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 rsa_rsassa_pkcs1_v15_verify( rsa_context *ctx, int mode, int hash_id, unsigned int hashlen, const unsigned char *hash, unsigned char *sig ) { int ret; size_t len, siglen; unsigned char *p, c; unsigned char buf[POLARSSL_MPI_MAX_SIZE]; if( ctx->padding != RSA_PKCS_V15 ) return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); siglen = ctx->len; if( siglen < 16 || siglen > sizeof( buf ) ) return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); ret = ( mode == RSA_PUBLIC ) ? rsa_public( ctx, sig, buf ) : rsa_private( ctx, sig, buf ); if( ret != 0 ) return( ret ); p = buf; if( *p++ != 0 || *p++ != RSA_SIGN ) return( POLARSSL_ERR_RSA_INVALID_PADDING ); while( *p != 0 ) { if( p >= buf + siglen - 1 || *p != 0xFF ) return( POLARSSL_ERR_RSA_INVALID_PADDING ); p++; } p++; len = siglen - ( p - buf ); if( len == 33 && hash_id == SIG_RSA_SHA1 ) { if( memcmp( p, ASN1_HASH_SHA1_ALT, 13 ) == 0 && memcmp( p + 13, hash, 20 ) == 0 ) return( 0 ); else return( POLARSSL_ERR_RSA_VERIFY_FAILED ); } if( len == 34 ) { c = p[13]; p[13] = 0; if( memcmp( p, ASN1_HASH_MDX, 18 ) != 0 ) return( POLARSSL_ERR_RSA_VERIFY_FAILED ); if( ( c == 2 && hash_id == SIG_RSA_MD2 ) || ( c == 4 && hash_id == SIG_RSA_MD4 ) || ( c == 5 && hash_id == SIG_RSA_MD5 ) ) { if( memcmp( p + 18, hash, 16 ) == 0 ) return( 0 ); else return( POLARSSL_ERR_RSA_VERIFY_FAILED ); } } if( len == 35 && hash_id == SIG_RSA_SHA1 ) { if( memcmp( p, ASN1_HASH_SHA1, 15 ) == 0 && memcmp( p + 15, hash, 20 ) == 0 ) return( 0 ); else return( POLARSSL_ERR_RSA_VERIFY_FAILED ); } if( ( len == 19 + 28 && p[14] == 4 && hash_id == SIG_RSA_SHA224 ) || ( len == 19 + 32 && p[14] == 1 && hash_id == SIG_RSA_SHA256 ) || ( len == 19 + 48 && p[14] == 2 && hash_id == SIG_RSA_SHA384 ) || ( len == 19 + 64 && p[14] == 3 && hash_id == SIG_RSA_SHA512 ) ) { c = p[1] - 17; p[1] = 17; p[14] = 0; if( p[18] == c && memcmp( p, ASN1_HASH_SHA2X, 18 ) == 0 && memcmp( p + 19, hash, c ) == 0 ) return( 0 ); else return( POLARSSL_ERR_RSA_VERIFY_FAILED ); } if( len == hashlen && hash_id == SIG_RSA_RAW ) { if( memcmp( p, hash, hashlen ) == 0 ) return( 0 ); else return( POLARSSL_ERR_RSA_VERIFY_FAILED ); } return( POLARSSL_ERR_RSA_INVALID_PADDING ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide 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 rsa_rsaes_pkcs1_v15_encrypt( rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t ilen, const unsigned char *input, unsigned char *output ) { size_t nb_pad, olen; int ret; unsigned char *p = output; if( ctx->padding != RSA_PKCS_V15 || f_rng == NULL ) return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); olen = ctx->len; if( olen < ilen + 11 ) return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); nb_pad = olen - 3 - ilen; *p++ = 0; if( mode == RSA_PUBLIC ) { *p++ = RSA_CRYPT; while( nb_pad-- > 0 ) { int rng_dl = 100; do { ret = f_rng( p_rng, p, 1 ); } while( *p == 0 && --rng_dl && ret == 0 ); // Check if RNG failed to generate data // if( rng_dl == 0 || ret != 0) return POLARSSL_ERR_RSA_RNG_FAILED + ret; p++; } } else { *p++ = RSA_SIGN; while( nb_pad-- > 0 ) *p++ = 0xFF; } *p++ = 0; memcpy( p, input, ilen ); return( ( mode == RSA_PUBLIC ) ? rsa_public( ctx, output, output ) : rsa_private( ctx, output, output ) ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide 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 rsa_rsassa_pss_sign( rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, int hash_id, unsigned int hashlen, const unsigned char *hash, unsigned char *sig ) { size_t olen; unsigned char *p = sig; unsigned char salt[POLARSSL_MD_MAX_SIZE]; unsigned int slen, hlen, offset = 0; int ret; size_t msb; const md_info_t *md_info; md_context_t md_ctx; if( ctx->padding != RSA_PKCS_V21 || f_rng == NULL ) return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); olen = ctx->len; switch( hash_id ) { case SIG_RSA_MD2: case SIG_RSA_MD4: case SIG_RSA_MD5: hashlen = 16; break; case SIG_RSA_SHA1: hashlen = 20; break; case SIG_RSA_SHA224: hashlen = 28; break; case SIG_RSA_SHA256: hashlen = 32; break; case SIG_RSA_SHA384: hashlen = 48; break; case SIG_RSA_SHA512: hashlen = 64; break; default: return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); } md_info = md_info_from_type( ctx->hash_id ); if( md_info == NULL ) return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); hlen = md_get_size( md_info ); slen = hlen; if( olen < hlen + slen + 2 ) return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); memset( sig, 0, olen ); msb = mpi_msb( &ctx->N ) - 1; // Generate salt of length slen // if( ( ret = f_rng( p_rng, salt, slen ) ) != 0 ) return( POLARSSL_ERR_RSA_RNG_FAILED + ret ); // Note: EMSA-PSS encoding is over the length of N - 1 bits // msb = mpi_msb( &ctx->N ) - 1; p += olen - hlen * 2 - 2; *p++ = 0x01; memcpy( p, salt, slen ); p += slen; md_init_ctx( &md_ctx, md_info ); // Generate H = Hash( M' ) // md_starts( &md_ctx ); md_update( &md_ctx, p, 8 ); md_update( &md_ctx, hash, hashlen ); md_update( &md_ctx, salt, slen ); md_finish( &md_ctx, p ); // Compensate for boundary condition when applying mask // if( msb % 8 == 0 ) offset = 1; // maskedDB: Apply dbMask to DB // mgf_mask( sig + offset, olen - hlen - 1 - offset, p, hlen, &md_ctx ); md_free_ctx( &md_ctx ); msb = mpi_msb( &ctx->N ) - 1; sig[0] &= 0xFF >> ( olen * 8 - msb ); p += hlen; *p++ = 0xBC; return( ( mode == RSA_PUBLIC ) ? rsa_public( ctx, sig, sig ) : rsa_private( ctx, sig, sig ) ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main( int argc, char *argv[] ) { ((void) argc); ((void) argv); printf("POLARSSL_AES_C and/or POLARSSL_DHM_C and/or POLARSSL_ENTROPY_C " "and/or POLARSSL_NET_C and/or POLARSSL_RSA_C and/or " "POLARSSL_SHA1_C and/or POLARSSL_FS_IO and/or " "POLARSSL_CTR_DBRG_C not defined.\n"); return( 0 ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide 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 rsa_prepare_blinding( rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret; if( ctx->Vf.p != NULL ) { /* We already have blinding values, just update them by squaring */ MPI_CHK( mpi_mul_mpi( &ctx->Vi, &ctx->Vi, &ctx->Vi ) ); MPI_CHK( mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) ); MPI_CHK( mpi_mul_mpi( &ctx->Vf, &ctx->Vf, &ctx->Vf ) ); MPI_CHK( mpi_mod_mpi( &ctx->Vf, &ctx->Vf, &ctx->N ) ); return( 0 ); } /* Unblinding value: Vf = random number */ MPI_CHK( mpi_fill_random( &ctx->Vf, ctx->len - 1, f_rng, p_rng ) ); /* Mathematically speaking, the algorithm should check Vf * against 0, P and Q (Vf should be relatively prime to N, and 0 < Vf < N), * so that Vf^-1 exists. */ /* Blinding value: Vi = Vf^(-e) mod N */ MPI_CHK( mpi_inv_mod( &ctx->Vi, &ctx->Vf, &ctx->N ) ); MPI_CHK( mpi_exp_mod( &ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN ) ); cleanup: return( ret ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Changed RSA blinding to a slower but thread-safe version'</s>
<s>[INST] Given the following code containing errors, provide 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 AbstractSqlStorage::addConnectionToPool() { QMutexLocker locker(&_connectionPoolMutex); // we have to recheck if the connection pool already contains a connection for // this thread. Since now (after the lock) we can only tell for sure if (_connectionPool.contains(QThread::currentThread())) return; QThread *currentThread = QThread::currentThread(); int connectionId = _nextConnectionId++; Connection *connection = new Connection(QLatin1String(QString("quassel_%1_con_%2").arg(driverName()).arg(connectionId).toLatin1())); connection->moveToThread(currentThread); connect(this, SIGNAL(destroyed()), connection, SLOT(deleteLater())); connect(currentThread, SIGNAL(destroyed()), connection, SLOT(deleteLater())); connect(connection, SIGNAL(destroyed()), this, SLOT(connectionDestroyed())); _connectionPool[currentThread] = connection; QSqlDatabase db = QSqlDatabase::addDatabase(driverName(), connection->name()); db.setDatabaseName(databaseName()); if (!hostName().isEmpty()) db.setHostName(hostName()); if (port() != -1) db.setPort(port()); if (!userName().isEmpty()) { db.setUserName(userName()); db.setPassword(password()); } if (!db.open()) { qWarning() << "Unable to open database" << displayName() << "for thread" << QThread::currentThread(); qWarning() << "-" << db.lastError().text(); } else { initDbSession(db); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-89'], 'message': 'Fixing security vulnerability with Qt 4.8.5+ and PostgreSQL. Properly detects whether Qt performs slash escaping in SQL queries or not, and then configures PostgreSQL accordingly. This bug was a introduced due to a bugfix in Qt 4.8.5 disables slash escaping when binding queries: https://bugreports.qt-project.org/browse/QTBUG-30076 Thanks to brot and Tucos. [Fixes #1244]'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: inline virtual void initDbSession(QSqlDatabase & /* db */) {} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-89'], 'message': 'Fixing security vulnerability with Qt 4.8.5+ and PostgreSQL. Properly detects whether Qt performs slash escaping in SQL queries or not, and then configures PostgreSQL accordingly. This bug was a introduced due to a bugfix in Qt 4.8.5 disables slash escaping when binding queries: https://bugreports.qt-project.org/browse/QTBUG-30076 Thanks to brot and Tucos. [Fixes #1244]'</s>
<s>[INST] Given the following code containing errors, provide 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 dane_state_set_dlv_file(dane_state_t s, const char* file) { int ret; ret = ub_ctx_set_option(s->ctx, (char*)"dlv-anchor-file:", (void*)file); if (ret != 0) return gnutls_assert_val(DANE_E_FILE_ERROR); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Adding dane_raw_tlsa to allow initialization of dane_query_t from DANE records based on external DNS resolutions. Also fixing a buffer overflow. Signed-off-by: Nikos Mavrogiannopoulos <[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 dane_verify_session_crt ( dane_state_t s, gnutls_session_t session, const char * hostname, const char* proto, unsigned int port, unsigned int sflags, unsigned int vflags, unsigned int *verify) { const gnutls_datum_t *cert_list; unsigned int cert_list_size = 0; unsigned int type; cert_list = gnutls_certificate_get_peers(session, &cert_list_size); if (cert_list_size == 0) { return gnutls_assert_val(DANE_E_NO_CERT); } type = gnutls_certificate_type_get(session); return dane_verify_crt(s, cert_list, cert_list_size, type, hostname, proto, port, sflags, vflags, verify); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Adding dane_raw_tlsa to allow initialization of dane_query_t from DANE records based on external DNS resolutions. Also fixing a buffer overflow. Signed-off-by: Nikos Mavrogiannopoulos <[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 dane_query_deinit(dane_query_t q) { ub_resolve_free(q->result); free(q); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Adding dane_raw_tlsa to allow initialization of dane_query_t from DANE records based on external DNS resolutions. Also fixing a buffer overflow. Signed-off-by: Nikos Mavrogiannopoulos <[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 dane_verify_crt (dane_state_t s, const gnutls_datum_t *chain, unsigned chain_size, gnutls_certificate_type_t chain_type, const char * hostname, const char* proto, unsigned int port, unsigned int sflags, unsigned int vflags, unsigned int *verify) { dane_state_t _s = NULL; dane_query_t r = NULL; int ret; unsigned checked = 0; unsigned int usage, type, match, idx; gnutls_datum_t data; if (chain_type != GNUTLS_CRT_X509) return gnutls_assert_val(DANE_E_INVALID_REQUEST); *verify = 0; if (s == NULL) { ret = dane_state_init(&_s, sflags); if (ret < 0) { gnutls_assert(); return ret; } } else _s = s; ret = dane_query_tlsa(_s, &r, hostname, proto, port); if (ret < 0) { gnutls_assert(); goto cleanup; } idx = 0; do { ret = dane_query_data(r, idx++, &usage, &type, &match, &data); if (ret == DANE_E_REQUESTED_DATA_NOT_AVAILABLE) break; if (ret < 0) { gnutls_assert(); goto cleanup; } if (!(vflags & DANE_VFLAG_ONLY_CHECK_EE_USAGE) && (usage == DANE_CERT_USAGE_LOCAL_CA || usage == DANE_CERT_USAGE_CA)) { ret = verify_ca(chain, chain_size, chain_type, type, match, &data, verify); if (ret < 0) { gnutls_assert(); goto cleanup; } checked = 1; } else if (!(vflags & DANE_VFLAG_ONLY_CHECK_CA_USAGE) && (usage == DANE_CERT_USAGE_LOCAL_EE || usage == DANE_CERT_USAGE_EE)) { ret = verify_ee(&chain[0], chain_type, type, match, &data, verify); if (ret < 0) { gnutls_assert(); goto cleanup; } checked = 1; } } while(1); if ((vflags & DANE_VFLAG_FAIL_IF_NOT_CHECKED) && checked == 0) ret = gnutls_assert_val(DANE_E_REQUESTED_DATA_NOT_AVAILABLE); else ret = 0; cleanup: if (s == NULL) dane_state_deinit(_s); if (r != NULL) dane_query_deinit(r); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Adding dane_raw_tlsa to allow initialization of dane_query_t from DANE records based on external DNS resolutions. Also fixing a buffer overflow. Signed-off-by: Nikos Mavrogiannopoulos <[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 dane_state_init(dane_state_t* s, unsigned int flags) { struct ub_ctx* ctx; int ret; *s = calloc(1, sizeof(struct dane_state_st)); if (*s == NULL) return gnutls_assert_val(DANE_E_MEMORY_ERROR); ctx = ub_ctx_create(); if(!ctx) { gnutls_assert(); ret = DANE_E_INITIALIZATION_ERROR; goto cleanup; } ub_ctx_debugout(ctx, stderr); if (!(flags & DANE_F_IGNORE_LOCAL_RESOLVER)) { if( (ret=ub_ctx_resolvconf(ctx, NULL)) != 0) { gnutls_assert(); ret = DANE_E_INITIALIZATION_ERROR; goto cleanup; } if( (ret=ub_ctx_hosts(ctx, NULL)) != 0) { gnutls_assert(); ret = DANE_E_INITIALIZATION_ERROR; goto cleanup; } } /* read public keys for DNSSEC verification */ if( (ret=ub_ctx_add_ta_file(ctx, (char*)UNBOUND_ROOT_KEY_FILE)) != 0) { gnutls_assert(); ret = DANE_E_INITIALIZATION_ERROR; goto cleanup; } (*s)->ctx = ctx; (*s)->flags = flags; return DANE_E_SUCCESS; cleanup: if (ctx) ub_ctx_delete(ctx); free(*s); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Adding dane_raw_tlsa to allow initialization of dane_query_t from DANE records based on external DNS resolutions. Also fixing a buffer overflow. Signed-off-by: Nikos Mavrogiannopoulos <[email protected]>'</s>