text
stringlengths
481
107k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: w64_read_header (SF_PRIVATE *psf, int *blockalign, int *framesperblock) { WAVLIKE_PRIVATE *wpriv ; WAV_FMT *wav_fmt ; int dword = 0, marker, format = 0 ; sf_count_t chunk_size, bytesread = 0 ; int parsestage = 0, error, done = 0 ; if ((wpriv = psf->container_data) == NULL) return SFE_INTERNAL ; wav_fmt = &wpriv->wav_fmt ; /* Set position to start of file to begin reading header. */ psf_binheader_readf (psf, "p", 0) ; while (! done) { /* Each new chunk must start on an 8 byte boundary, so jump if needed. */ if (psf->header.indx & 0x7) psf_binheader_readf (psf, "j", 8 - (psf->header.indx & 0x7)) ; /* Generate hash of 16 byte marker. */ marker = chunk_size = 0 ; bytesread = psf_binheader_readf (psf, "eh8", &marker, &chunk_size) ; if (bytesread == 0) break ; switch (marker) { case riff_HASH16 : if (parsestage) return SFE_W64_NO_RIFF ; if (psf->filelength != chunk_size) psf_log_printf (psf, "riff : %D (should be %D)\n", chunk_size, psf->filelength) ; else psf_log_printf (psf, "riff : %D\n", chunk_size) ; parsestage |= HAVE_riff ; bytesread += psf_binheader_readf (psf, "h", &marker) ; if (marker == wave_HASH16) { if ((parsestage & HAVE_riff) != HAVE_riff) return SFE_W64_NO_WAVE ; psf_log_printf (psf, "wave\n") ; parsestage |= HAVE_wave ; } ; chunk_size = 0 ; break ; case ACID_HASH16: psf_log_printf (psf, "Looks like an ACID file. Exiting.\n") ; return SFE_UNIMPLEMENTED ; case fmt_HASH16 : if ((parsestage & (HAVE_riff | HAVE_wave)) != (HAVE_riff | HAVE_wave)) return SFE_WAV_NO_FMT ; psf_log_printf (psf, " fmt : %D\n", chunk_size) ; /* size of 16 byte marker and 8 byte chunk_size value. */ chunk_size -= 24 ; if ((error = wavlike_read_fmt_chunk (psf, (int) chunk_size))) return error ; if (chunk_size % 8) psf_binheader_readf (psf, "j", 8 - (chunk_size % 8)) ; format = wav_fmt->format ; parsestage |= HAVE_fmt ; chunk_size = 0 ; break ; case fact_HASH16: { sf_count_t frames ; psf_binheader_readf (psf, "e8", &frames) ; psf_log_printf (psf, "fact : %D\n frames : %D\n", chunk_size, frames) ; } ; chunk_size = 0 ; break ; case data_HASH16 : if ((parsestage & (HAVE_riff | HAVE_wave | HAVE_fmt)) != (HAVE_riff | HAVE_wave | HAVE_fmt)) return SFE_W64_NO_DATA ; psf->dataoffset = psf_ftell (psf) ; psf->datalength = SF_MIN (chunk_size - 24, psf->filelength - psf->dataoffset) ; if (chunk_size % 8) chunk_size += 8 - (chunk_size % 8) ; psf_log_printf (psf, "data : %D\n", chunk_size) ; parsestage |= HAVE_data ; if (! psf->sf.seekable) break ; /* Seek past data and continue reading header. */ psf_fseek (psf, chunk_size, SEEK_CUR) ; chunk_size = 0 ; break ; case levl_HASH16 : psf_log_printf (psf, "levl : %D\n", chunk_size) ; chunk_size -= 24 ; break ; case list_HASH16 : psf_log_printf (psf, "list : %D\n", chunk_size) ; chunk_size -= 24 ; break ; case junk_HASH16 : psf_log_printf (psf, "junk : %D\n", chunk_size) ; chunk_size -= 24 ; break ; case bext_HASH16 : psf_log_printf (psf, "bext : %D\n", chunk_size) ; chunk_size -= 24 ; break ; case MARKER_HASH16 : psf_log_printf (psf, "marker : %D\n", chunk_size) ; chunk_size -= 24 ; break ; case SUMLIST_HASH16 : psf_log_printf (psf, "summary list : %D\n", chunk_size) ; chunk_size -= 24 ; break ; default : psf_log_printf (psf, "*** Unknown chunk marker (%X) at position %D with length %D. Exiting parser.\n", marker, psf_ftell (psf) - 8, chunk_size) ; done = SF_TRUE ; break ; } ; /* switch (dword) */ if (chunk_size >= psf->filelength) { psf_log_printf (psf, "*** Chunk size %u > file length %D. Exiting parser.\n", chunk_size, psf->filelength) ; break ; } ; if (psf->sf.seekable == 0 && (parsestage & HAVE_data)) break ; if (psf_ftell (psf) >= (psf->filelength - (2 * SIGNED_SIZEOF (dword)))) break ; if (chunk_size > 0 && chunk_size < 0xffff0000) { dword = chunk_size ; psf_binheader_readf (psf, "j", dword - 24) ; } ; } ; /* while (1) */ if (psf->dataoffset <= 0) return SFE_W64_NO_DATA ; if (psf->sf.channels < 1) return SFE_CHANNEL_COUNT_ZERO ; if (psf->sf.channels >= SF_MAX_CHANNELS) return SFE_CHANNEL_COUNT ; psf->endian = SF_ENDIAN_LITTLE ; /* All W64 files are little endian. */ if (psf_ftell (psf) != psf->dataoffset) psf_fseek (psf, psf->dataoffset, SEEK_SET) ; if (psf->blockwidth) { if (psf->filelength - psf->dataoffset < psf->datalength) psf->sf.frames = (psf->filelength - psf->dataoffset) / psf->blockwidth ; else psf->sf.frames = psf->datalength / psf->blockwidth ; } ; switch (format) { case WAVE_FORMAT_PCM : case WAVE_FORMAT_EXTENSIBLE : /* extensible might be FLOAT, MULAW, etc as well! */ psf->sf.format = SF_FORMAT_W64 | u_bitwidth_to_subformat (psf->bytewidth * 8) ; break ; case WAVE_FORMAT_MULAW : psf->sf.format = (SF_FORMAT_W64 | SF_FORMAT_ULAW) ; break ; case WAVE_FORMAT_ALAW : psf->sf.format = (SF_FORMAT_W64 | SF_FORMAT_ALAW) ; break ; case WAVE_FORMAT_MS_ADPCM : psf->sf.format = (SF_FORMAT_W64 | SF_FORMAT_MS_ADPCM) ; *blockalign = wav_fmt->msadpcm.blockalign ; *framesperblock = wav_fmt->msadpcm.samplesperblock ; break ; case WAVE_FORMAT_IMA_ADPCM : psf->sf.format = (SF_FORMAT_W64 | SF_FORMAT_IMA_ADPCM) ; *blockalign = wav_fmt->ima.blockalign ; *framesperblock = wav_fmt->ima.samplesperblock ; break ; case WAVE_FORMAT_GSM610 : psf->sf.format = (SF_FORMAT_W64 | SF_FORMAT_GSM610) ; break ; case WAVE_FORMAT_IEEE_FLOAT : psf->sf.format = SF_FORMAT_W64 ; psf->sf.format |= (psf->bytewidth == 8) ? SF_FORMAT_DOUBLE : SF_FORMAT_FLOAT ; break ; default : return SFE_UNIMPLEMENTED ; } ; return 0 ; } /* w64_read_header */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix max channel count bug The code was allowing files to be written with a channel count of exactly `SF_MAX_CHANNELS` but was failing to read some file formats with the same channel count.'</s>
<s>[INST] Given the following code containing errors, provide 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 read_next_sample(int ifd, int action, int curr, char *file, int *rtype, int tab, struct file_magic *file_magic, struct file_activity *file_actlst, struct tm *rectime, struct tm *loctime, int oneof) { int rc; char rec_hdr_tmp[MAX_RECORD_HEADER_SIZE]; /* Read current record */ if ((rc = read_record_hdr(ifd, rec_hdr_tmp, &record_hdr[curr], &file_hdr, arch_64, endian_mismatch, oneof)) != 0) /* End of sa file */ return rc; *rtype = record_hdr[curr].record_type; if (*rtype == R_COMMENT) { if (action & IGNORE_COMMENT) { /* Ignore COMMENT record */ if (lseek(ifd, MAX_COMMENT_LEN, SEEK_CUR) < MAX_COMMENT_LEN) { perror("lseek"); if (oneof == UEOF_CONT) return 2; close(ifd); exit(2); } if (action & SET_TIMESTAMPS) { sa_get_record_timestamp_struct(flags, &record_hdr[curr], rectime, loctime); } } else { /* Display COMMENT record */ print_special_record(&record_hdr[curr], flags, &tm_start, &tm_end, *rtype, ifd, rectime, loctime, file, tab, file_magic, &file_hdr, act, fmt[f_position], endian_mismatch, arch_64); } } else if (*rtype == R_RESTART) { if (action & IGNORE_RESTART) { /* * Ignore RESTART record (don't display it) * but anyway we have to read the CPU number that follows it * (unless we don't want to do it now). */ if (!(action & DONT_READ_CPU_NR)) { file_hdr.sa_cpu_nr = read_nr_value(ifd, file, file_magic, endian_mismatch, arch_64, TRUE); } if (action & SET_TIMESTAMPS) { sa_get_record_timestamp_struct(flags, &record_hdr[curr], rectime, loctime); } } else { /* Display RESTART record */ print_special_record(&record_hdr[curr], flags, &tm_start, &tm_end, *rtype, ifd, rectime, loctime, file, tab, file_magic, &file_hdr, act, fmt[f_position], endian_mismatch, arch_64); } } else { /* * OK: Previous record was not a special one. * So read now the extra fields. */ if (read_file_stat_bunch(act, curr, ifd, file_hdr.sa_act_nr, file_actlst, endian_mismatch, arch_64, file, file_magic, oneof) > 0) return 2; sa_get_record_timestamp_struct(flags, &record_hdr[curr], rectime, loctime); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #196 and #199: Out of bound reads security issues Check args before calling memmove() and memset() in remap_struct() function to avoid out of bound reads which would possibly lead to unknown code execution and/or sadf command crash. Signed-off-by: Sebastien GODARD <sysstat@users.noreply.github.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static char* set_iovec_field_free(struct iovec *iovec, size_t *n_iovec, const char *field, char *value) { char *x; x = set_iovec_field(iovec, n_iovec, field, value); free(value); return x; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': 'journald: do not store the iovec entry for process commandline on stack This fixes a crash where we would read the commandline, whose length is under control of the sending program, and then crash when trying to create a stack allocation for it. CVE-2018-16864 https://bugzilla.redhat.com/show_bug.cgi?id=1653855 The message actually doesn't get written to disk, because journal_file_append_entry() returns -E2BIG.'</s>
<s>[INST] Given the following code containing errors, provide 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(void) { test_syslog_parse_identifier("pidu[111]: xxx", "pidu", "111", 11); test_syslog_parse_identifier("pidu: xxx", "pidu", NULL, 6); test_syslog_parse_identifier("pidu: xxx", "pidu", NULL, 7); test_syslog_parse_identifier("pidu xxx", NULL, NULL, 0); test_syslog_parse_identifier(":", "", NULL, 1); test_syslog_parse_identifier(": ", "", NULL, 3); test_syslog_parse_identifier("pidu:", "pidu", NULL, 5); test_syslog_parse_identifier("pidu: ", "pidu", NULL, 6); test_syslog_parse_identifier("pidu : ", NULL, NULL, 0); test_syslog_parse_priority("<>", 0, 0); test_syslog_parse_priority("<>aaa", 0, 0); test_syslog_parse_priority("<aaaa>", 0, 0); test_syslog_parse_priority("<aaaa>aaa", 0, 0); test_syslog_parse_priority(" <aaaa>", 0, 0); test_syslog_parse_priority(" <aaaa>aaa", 0, 0); /* TODO: add test cases of valid priorities */ return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'journal: do not remove multiple spaces after identifier in syslog message Single space is used as separator. C.f. discussions in #156. Fixes #9839 introduced by a6aadf4ae0bae185dc4c414d492a4a781c80ffe5.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: sub_font_params(gs_memory_t *mem, const ref *op, gs_matrix *pmat, gs_matrix *pomat, ref *pfname) { ref *pmatrix, *pfontname, *pfontstyle, *porigfont, *pfontinfo; if (dict_find_string(op, "FontMatrix", &pmatrix) <= 0 || read_matrix(mem, pmatrix, pmat) < 0 ) return_error(gs_error_invalidfont); if (dict_find_string(op, "OrigFont", &porigfont) <= 0) porigfont = NULL; if (pomat!= NULL) { if (porigfont == NULL || dict_find_string(porigfont, "FontMatrix", &pmatrix) <= 0 || read_matrix(mem, pmatrix, pomat) < 0 ) memset(pomat, 0, sizeof(*pomat)); } /* Use the FontInfo/OrigFontName key preferrentially (created by MS PSCRIPT driver) */ if ((dict_find_string((porigfont != NULL ? porigfont : op), "FontInfo", &pfontinfo) > 0) && r_has_type(pfontinfo, t_dictionary) && (dict_find_string(pfontinfo, "OrigFontName", &pfontname) > 0)) { if ((dict_find_string(pfontinfo, "OrigFontStyle", &pfontstyle) > 0) && r_size(pfontstyle) > 0) { const byte *tmpStr1 = pfontname->value.const_bytes; const byte *tmpStr2 = pfontstyle->value.const_bytes; int fssize1 = r_size(pfontname), fssize2 = r_size(pfontstyle), fssize = fssize1 + fssize2 + 1; byte *sfname = gs_alloc_string(mem, fssize, "sub_font_params"); if (sfname == NULL) return_error(gs_error_VMerror); memcpy(sfname, tmpStr1, fssize1); sfname[fssize1]=',' ; memcpy(sfname + fssize1 + 1, tmpStr2, fssize2); make_string(pfname, a_readonly, fssize, sfname); } else get_font_name(mem, pfname, pfontname); } else if (dict_find_string((porigfont != NULL ? porigfont : op), ".Alias", &pfontname) > 0) { /* If we emulate the font, we want the requested name rather than a substitute. */ get_font_name(mem, pfname, pfontname); } else if (dict_find_string((porigfont != NULL ? porigfont : op), "FontName", &pfontname) > 0) { get_font_name(mem, pfname, pfontname); } else make_empty_string(pfname, a_readonly); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - add some type checking These were 'probably' safe anyway, since they mostly treat the objects as integers without checking, which at least can't result in a crash. Nevertheless, we ought to check. The return from comparedictkeys could be wrong if one of the keys had a value which was not an array, it could incorrectly decide the two were in fact the same.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: zcrd1_params(os_ptr op, gs_cie_render * pcrd, ref_cie_render_procs * pcprocs, gs_memory_t * mem) { int code; int ignore; gx_color_lookup_table *const prtl = &pcrd->RenderTable.lookup; ref *pRT; if ((code = dict_int_param(op, "ColorRenderingType", 1, 1, 0, &ignore)) < 0) return code; if ((code = zcrd1_proc_params(mem, op, pcprocs)) < 0) return code; if ((code = dict_matrix3_param(mem, op, "MatrixLMN", &pcrd->MatrixLMN)) < 0) return code; if ((code = dict_range3_param(mem, op, "RangeLMN", &pcrd->RangeLMN)) < 0) return code; if ((code = dict_matrix3_param(mem, op, "MatrixABC", &pcrd->MatrixABC)) < 0) return code; if ((code = dict_range3_param(mem, op, "RangeABC", &pcrd->RangeABC)) < 0) return code; if ((code = cie_points_param(mem, op, &pcrd->points)) < 0) return code; if ((code = dict_matrix3_param(mem, op, "MatrixPQR", &pcrd->MatrixPQR)) < 0) return code; if ((code = dict_range3_param(mem,op, "RangePQR", &pcrd->RangePQR)) < 0) return code; if (dict_find_string(op, "RenderTable", &pRT) > 0) { const ref *prte = pRT->value.const_refs; /* Finish unpacking and checking the RenderTable parameter. */ check_type_only(prte[4], t_integer); if (!(prte[4].value.intval == 3 || prte[4].value.intval == 4)) return_error(gs_error_rangecheck); prtl->n = 3; prtl->m = prte[4].value.intval; if (r_size(pRT) != prtl->m + 5) return_error(gs_error_rangecheck); code = cie_table_param(pRT, prtl, mem); if (code < 0) return code; } else { prtl->table = 0; } pcrd->EncodeLMN = Encode_default; pcrd->EncodeABC = Encode_default; pcrd->TransformPQR = TransformPQR_default; pcrd->RenderTable.T = RenderTableT_default; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - add some type checking These were 'probably' safe anyway, since they mostly treat the objects as integers without checking, which at least can't result in a crash. Nevertheless, we ought to check. The return from comparedictkeys could be wrong if one of the keys had a value which was not an array, it could incorrectly decide the two were in fact the same.'</s>
<s>[INST] Given the following code containing errors, provide 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 usb_audio_probe(struct usb_interface *intf, const struct usb_device_id *usb_id) { struct usb_device *dev = interface_to_usbdev(intf); const struct snd_usb_audio_quirk *quirk = (const struct snd_usb_audio_quirk *)usb_id->driver_info; struct snd_usb_audio *chip; int i, err; struct usb_host_interface *alts; int ifnum; u32 id; alts = &intf->altsetting[0]; ifnum = get_iface_desc(alts)->bInterfaceNumber; id = USB_ID(le16_to_cpu(dev->descriptor.idVendor), le16_to_cpu(dev->descriptor.idProduct)); if (get_alias_id(dev, &id)) quirk = get_alias_quirk(dev, id); if (quirk && quirk->ifnum >= 0 && ifnum != quirk->ifnum) return -ENXIO; err = snd_usb_apply_boot_quirk(dev, intf, quirk, id); if (err < 0) return err; /* * found a config. now register to ALSA */ /* check whether it's already registered */ chip = NULL; mutex_lock(&register_mutex); for (i = 0; i < SNDRV_CARDS; i++) { if (usb_chip[i] && usb_chip[i]->dev == dev) { if (atomic_read(&usb_chip[i]->shutdown)) { dev_err(&dev->dev, "USB device is in the shutdown state, cannot create a card instance\n"); err = -EIO; goto __error; } chip = usb_chip[i]; atomic_inc(&chip->active); /* avoid autopm */ break; } } if (! chip) { /* it's a fresh one. * now look for an empty slot and create a new card instance */ for (i = 0; i < SNDRV_CARDS; i++) if (!usb_chip[i] && (vid[i] == -1 || vid[i] == USB_ID_VENDOR(id)) && (pid[i] == -1 || pid[i] == USB_ID_PRODUCT(id))) { if (enable[i]) { err = snd_usb_audio_create(intf, dev, i, quirk, id, &chip); if (err < 0) goto __error; chip->pm_intf = intf; break; } else if (vid[i] != -1 || pid[i] != -1) { dev_info(&dev->dev, "device (%04x:%04x) is disabled\n", USB_ID_VENDOR(id), USB_ID_PRODUCT(id)); err = -ENOENT; goto __error; } } if (!chip) { dev_err(&dev->dev, "no available usb audio device\n"); err = -ENODEV; goto __error; } } dev_set_drvdata(&dev->dev, chip); /* * For devices with more than one control interface, we assume the * first contains the audio controls. We might need a more specific * check here in the future. */ if (!chip->ctrl_intf) chip->ctrl_intf = alts; chip->txfr_quirk = 0; err = 1; /* continue */ if (quirk && quirk->ifnum != QUIRK_NO_INTERFACE) { /* need some special handlings */ err = snd_usb_create_quirk(chip, intf, &usb_audio_driver, quirk); if (err < 0) goto __error; } if (err > 0) { /* create normal USB audio interfaces */ err = snd_usb_create_streams(chip, ifnum); if (err < 0) goto __error; err = snd_usb_create_mixer(chip, ifnum, ignore_ctl_error); if (err < 0) goto __error; } /* we are allowed to call snd_card_register() many times */ err = snd_card_register(chip->card); if (err < 0) goto __error; usb_chip[chip->index] = chip; chip->num_interfaces++; usb_set_intfdata(intf, chip); atomic_dec(&chip->active); mutex_unlock(&register_mutex); return 0; __error: if (chip) { if (!chip->num_interfaces) snd_card_free(chip->card); atomic_dec(&chip->active); } mutex_unlock(&register_mutex); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'ALSA: usb-audio: Fix UAF decrement if card has no live interfaces in card.c If a USB sound card reports 0 interfaces, an error condition is triggered and the function usb_audio_probe errors out. In the error path, there was a use-after-free vulnerability where the memory object of the card was first freed, followed by a decrement of the number of active chips. Moving the decrement above the atomic_dec fixes the UAF. [ The original problem was introduced in 3.1 kernel, while it was developed in a different form. The Fixes tag below indicates the original commit but it doesn't mean that the patch is applicable cleanly. -- tiwai ] Fixes: 362e4e49abe5 ("ALSA: usb-audio - clear chip->probing on error exit") Reported-by: Hui Peng <benquike@gmail.com> Reported-by: Mathias Payer <mathias.payer@nebelwelt.net> Signed-off-by: Hui Peng <benquike@gmail.com> Signed-off-by: Mathias Payer <mathias.payer@nebelwelt.net> Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int crypto_report_comp(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_comp rcomp; strlcpy(rcomp.type, "compression", sizeof(rcomp.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_COMPRESS, sizeof(struct crypto_report_comp), &rcomp)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'crypto: user - fix leaking uninitialized memory to userspace All bytes of the NETLINK_CRYPTO report structures must be initialized, since they are copied to userspace. The change from strncpy() to strlcpy() broke this. As a minimal fix, change it back. Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion") Cc: <stable@vger.kernel.org> # v4.12+ Signed-off-by: Eric Biggers <ebiggers@google.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: wav_read_smpl_chunk (SF_PRIVATE *psf, uint32_t chunklen) { char buffer [512] ; uint32_t thisread, bytesread = 0, dword, sampler_data, loop_count ; uint32_t note, pitch, start, end, type = -1, count ; int j, k ; chunklen += (chunklen & 1) ; bytesread += psf_binheader_readf (psf, "4", &dword) ; psf_log_printf (psf, " Manufacturer : %X\n", dword) ; bytesread += psf_binheader_readf (psf, "4", &dword) ; psf_log_printf (psf, " Product : %u\n", dword) ; bytesread += psf_binheader_readf (psf, "4", &dword) ; psf_log_printf (psf, " Period : %u nsec\n", dword) ; bytesread += psf_binheader_readf (psf, "4", &note) ; psf_log_printf (psf, " Midi Note : %u\n", note) ; bytesread += psf_binheader_readf (psf, "4", &pitch) ; if (pitch != 0) { snprintf (buffer, sizeof (buffer), "%f", (1.0 * 0x80000000) / ((uint32_t) pitch)) ; psf_log_printf (psf, " Pitch Fract. : %s\n", buffer) ; } else psf_log_printf (psf, " Pitch Fract. : 0\n") ; bytesread += psf_binheader_readf (psf, "4", &dword) ; psf_log_printf (psf, " SMPTE Format : %u\n", dword) ; bytesread += psf_binheader_readf (psf, "4", &dword) ; snprintf (buffer, sizeof (buffer), "%02d:%02d:%02d %02d", (dword >> 24) & 0x7F, (dword >> 16) & 0x7F, (dword >> 8) & 0x7F, dword & 0x7F) ; psf_log_printf (psf, " SMPTE Offset : %s\n", buffer) ; bytesread += psf_binheader_readf (psf, "4", &loop_count) ; psf_log_printf (psf, " Loop Count : %u\n", loop_count) ; if (loop_count == 0 && chunklen == bytesread) return 0 ; /* Sampler Data holds the number of data bytes after the CUE chunks which ** is not actually CUE data. Display value after CUE data. */ bytesread += psf_binheader_readf (psf, "4", &sampler_data) ; if ((psf->instrument = psf_instrument_alloc ()) == NULL) return SFE_MALLOC_FAILED ; psf->instrument->loop_count = loop_count ; for (j = 0 ; loop_count > 0 && chunklen - bytesread >= 24 ; j ++) { if ((thisread = psf_binheader_readf (psf, "4", &dword)) == 0) break ; bytesread += thisread ; psf_log_printf (psf, " Cue ID : %2u", dword) ; bytesread += psf_binheader_readf (psf, "4", &type) ; psf_log_printf (psf, " Type : %2u", type) ; bytesread += psf_binheader_readf (psf, "4", &start) ; psf_log_printf (psf, " Start : %5u", start) ; bytesread += psf_binheader_readf (psf, "4", &end) ; psf_log_printf (psf, " End : %5u", end) ; bytesread += psf_binheader_readf (psf, "4", &dword) ; psf_log_printf (psf, " Fraction : %5u", dword) ; bytesread += psf_binheader_readf (psf, "4", &count) ; psf_log_printf (psf, " Count : %5u\n", count) ; if (j < ARRAY_LEN (psf->instrument->loops)) { psf->instrument->loops [j].start = start ; psf->instrument->loops [j].end = end + 1 ; psf->instrument->loops [j].count = count ; switch (type) { case 0 : psf->instrument->loops [j].mode = SF_LOOP_FORWARD ; break ; case 1 : psf->instrument->loops [j].mode = SF_LOOP_ALTERNATING ; break ; case 2 : psf->instrument->loops [j].mode = SF_LOOP_BACKWARD ; break ; default: psf->instrument->loops [j].mode = SF_LOOP_NONE ; break ; } ; } ; loop_count -- ; } ; if (chunklen - bytesread == 0) { if (sampler_data != 0) psf_log_printf (psf, " Sampler Data : %u (should be 0)\n", sampler_data) ; else psf_log_printf (psf, " Sampler Data : %u\n", sampler_data) ; } else { if (sampler_data != chunklen - bytesread) { psf_log_printf (psf, " Sampler Data : %u (should have been %u)\n", sampler_data, chunklen - bytesread) ; sampler_data = chunklen - bytesread ; } else psf_log_printf (psf, " Sampler Data : %u\n", sampler_data) ; psf_log_printf (psf, " ") ; for (k = 0 ; k < (int) sampler_data ; k++) { char ch ; if (k > 0 && (k % 20) == 0) psf_log_printf (psf, "\n ") ; if ((thisread = psf_binheader_readf (psf, "1", &ch)) == 0) break ; bytesread += thisread ; psf_log_printf (psf, "%02X ", ch & 0xFF) ; } ; psf_log_printf (psf, "\n") ; } ; psf->instrument->basenote = note ; psf->instrument->detune = (int8_t)(pitch / (0x40000000 / 25.0) + 0.5) ; psf->instrument->gain = 1 ; psf->instrument->velocity_lo = psf->instrument->key_lo = 0 ; psf->instrument->velocity_hi = psf->instrument->key_hi = 127 ; return 0 ; } /* wav_read_smpl_chunk */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'src/wav.c: Fix heap read overflow This is CVE-2018-19758. Closes: https://github.com/erikd/libsndfile/issues/435'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rfbHandleAuthResult(rfbClient* client) { uint32_t authResult=0, reasonLen=0; char *reason=NULL; if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE; authResult = rfbClientSwap32IfLE(authResult); switch (authResult) { case rfbVncAuthOK: rfbClientLog("VNC authentication succeeded\n"); return TRUE; break; case rfbVncAuthFailed: if (client->major==3 && client->minor>7) { /* we have an error following */ if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return FALSE; reasonLen = rfbClientSwap32IfLE(reasonLen); reason = malloc(reasonLen+1); if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return FALSE; } reason[reasonLen]=0; rfbClientLog("VNC connection failed: %s\n",reason); free(reason); return FALSE; } rfbClientLog("VNC authentication failed\n"); return FALSE; case rfbVncAuthTooMany: rfbClientLog("VNC authentication failed - too many tries\n"); return FALSE; } rfbClientLog("Unknown VNC authentication result: %d\n", (int)authResult); return FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'LibVNCClient: fix three possible heap buffer overflows An attacker could feed `0xffffffff`, causing a `malloc(0)` for the buffers which are subsequently written to. Closes #247'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: HandleUltraZipBPP (rfbClient* client, int rx, int ry, int rw, int rh) { rfbZlibHeader hdr; int i=0; int toRead=0; int inflateResult=0; unsigned char *ptr=NULL; lzo_uint uncompressedBytes = ry + (rw * 65535); unsigned int numCacheRects = rx; if (!ReadFromRFBServer(client, (char *)&hdr, sz_rfbZlibHeader)) return FALSE; toRead = rfbClientSwap32IfLE(hdr.nBytes); if (toRead==0) return TRUE; if (uncompressedBytes==0) { rfbClientLog("ultrazip error: rectangle has 0 uncomressed bytes (%dy + (%dw * 65535)) (%d rectangles)\n", ry, rw, rx); return FALSE; } /* First make sure we have a large enough raw buffer to hold the * decompressed data. In practice, with a fixed BPP, fixed frame * buffer size and the first update containing the entire frame * buffer, this buffer allocation should only happen once, on the * first update. */ if ( client->raw_buffer_size < (int)(uncompressedBytes + 500)) { if ( client->raw_buffer != NULL ) { free( client->raw_buffer ); } client->raw_buffer_size = uncompressedBytes + 500; /* buffer needs to be aligned on 4-byte boundaries */ if ((client->raw_buffer_size % 4)!=0) client->raw_buffer_size += (4-(client->raw_buffer_size % 4)); client->raw_buffer = (char*) malloc( client->raw_buffer_size ); } /* allocate enough space to store the incoming compressed packet */ if ( client->ultra_buffer_size < toRead ) { if ( client->ultra_buffer != NULL ) { free( client->ultra_buffer ); } client->ultra_buffer_size = toRead; client->ultra_buffer = (char*) malloc( client->ultra_buffer_size ); } /* Fill the buffer, obtaining data from the server. */ if (!ReadFromRFBServer(client, client->ultra_buffer, toRead)) return FALSE; /* uncompress the data */ uncompressedBytes = client->raw_buffer_size; inflateResult = lzo1x_decompress_safe( (lzo_byte *)client->ultra_buffer, toRead, (lzo_byte *)client->raw_buffer, &uncompressedBytes, NULL); if ( inflateResult != LZO_E_OK ) { rfbClientLog("ultra decompress returned error: %d\n", inflateResult); return FALSE; } /* Put the uncompressed contents of the update on the screen. */ ptr = (unsigned char *)client->raw_buffer; for (i=0; i<numCacheRects; i++) { unsigned short sx, sy, sw, sh; unsigned int se; memcpy((char *)&sx, ptr, 2); ptr += 2; memcpy((char *)&sy, ptr, 2); ptr += 2; memcpy((char *)&sw, ptr, 2); ptr += 2; memcpy((char *)&sh, ptr, 2); ptr += 2; memcpy((char *)&se, ptr, 4); ptr += 4; sx = rfbClientSwap16IfLE(sx); sy = rfbClientSwap16IfLE(sy); sw = rfbClientSwap16IfLE(sw); sh = rfbClientSwap16IfLE(sh); se = rfbClientSwap32IfLE(se); if (se == rfbEncodingRaw) { client->GotBitmap(client, (unsigned char *)ptr, sx, sy, sw, sh); ptr += ((sw * sh) * (BPP / 8)); } } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'LibVNCClient: make sure Ultra decoding cannot dereference a null pointer Closes #254'</s>
<s>[INST] Given the following code containing errors, provide 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 parse_exif (int base) { unsigned kodak, entries, tag, type, len, save, c; double expo,ape; kodak = !strncmp(make,"EASTMAN",7) && tiff_nifds < 3; entries = get2(); if(!strncmp(make,"Hasselblad",10) && (tiff_nifds > 3) && (entries > 512)) return; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && savepos + len > fsize*2) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64(2.0f, (getreal(type) / 2.0f)); break; #endif case 33434: tiff_ifd[tiff_nifds-1].t_shutter = shutter = getreal(type); break; case 33437: aperture = getreal(type); break; // 0x829d FNumber case 34855: iso_speed = get2(); break; case 34866: if (iso_speed == 0xffff && (!strncasecmp(make, "SONY",4) || !strncasecmp(make, "CANON",5))) iso_speed = getreal(type); break; case 36867: case 36868: get_timestamp(0); break; case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds-1].t_shutter = shutter = libraw_powf64(2.0, expo); break; case 37378: // 0x9202 ApertureValue if ((fabs(ape = getreal(type))<256.0) && (!aperture)) aperture = libraw_powf64(2.0, ape/2); break; case 37385: flash_used = getreal(type); break; case 37386: focal_len = getreal(type); break; case 37500: // tag 0x927c #ifdef LIBRAW_LIBRARY_BUILD if (((make[0] == '\0') && (!strncmp(model, "ov5647",6))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_OV5647",9))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_imx219",9)))) { char mn_text[512]; char* pos; char ccms[512]; ushort l; float num; fgets(mn_text, len, ifp); pos = strstr(mn_text, "gain_r="); if (pos) cam_mul[0] = atof(pos+7); pos = strstr(mn_text, "gain_b="); if (pos) cam_mul[2] = atof(pos+7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, "ccm=") + 4; l = strstr(pos, " ") - pos; memcpy (ccms, pos, l); ccms[l] = '\0'; pos = strtok (ccms, ","); for (l=0; l<4; l++) { num = 0.0; for (c=0; c<3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; pos = strtok (NULL, ","); } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } else #endif parse_makernote (base, 0); break; case 40962: if (kodak) raw_width = get4(); break; case 40963: if (kodak) raw_height = get4(); break; case 41730: if (get4() == 0x20002) for (exif_cfa=c=0; c < 8; c+=2) exif_cfa |= fgetc(ifp) * 0x01010101 << c; } fseek (ifp, save, SEEK_SET); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Secunia 81800#1: samsumg_load_raw Secunia 81800#2: find_green Secunia 81800#3: rollei_load_raw remove_trailing_spaces: isspace() does not works right with signed non-latin chars Secunia 81800#5/6: nikon_coolscan_load_raw Secunia 81800#4: rollei_load_raw'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: defaults (void) { char *tmp; /* Most of the default values are 0 (and 0.0, NULL, and false). Just reset everything, and fill in the non-zero values. Note that initializing pointers to NULL this way is technically illegal, but porting Wget to a machine where NULL is not all-zero bit pattern will be the least of the implementors' worries. */ xzero (opt); #ifdef HAVE_METALINK opt.metalink_index = -1; #endif opt.cookies = true; opt.verbose = -1; opt.ntry = 20; opt.reclevel = 5; opt.add_hostdir = true; opt.netrc = true; opt.ftp_glob = true; opt.htmlify = true; opt.http_keep_alive = true; opt.use_proxy = true; opt.convert_file_only = false; tmp = getenv ("no_proxy"); if (tmp) opt.no_proxy = sepstring (tmp); opt.prefer_family = prefer_none; opt.allow_cache = true; opt.if_modified_since = true; opt.read_timeout = 900; opt.use_robots = true; opt.remove_listing = true; opt.dot_bytes = 1024; opt.dot_spacing = 10; opt.dots_in_line = 50; opt.dns_cache = true; opt.ftp_pasv = true; /* 2014-09-07 Darshit Shah <darnir@gmail.com> * opt.retr_symlinks is set to true by default. Creating symbolic links on the * local filesystem pose a security threat by malicious FTP Servers that * server a specially crafted .listing file akin to this: * * lrwxrwxrwx 1 root root 33 Dec 25 2012 JoCxl6d8rFU -> / * drwxrwxr-x 15 1024 106 4096 Aug 28 02:02 JoCxl6d8rFU * * A .listing file in this fashion makes Wget susceptiple to a symlink attack * wherein the attacker is able to create arbitrary files, directories and * symbolic links on the target system and even set permissions. * * Hence, by default Wget attempts to retrieve the pointed-to files and does * not create the symbolic links locally. */ opt.retr_symlinks = true; #ifdef HAVE_SSL opt.check_cert = CHECK_CERT_ON; opt.ftps_resume_ssl = true; opt.ftps_fallback_to_ftp = false; opt.ftps_implicit = false; opt.ftps_clear_data_connection = false; #endif #ifdef HAVE_LIBZ opt.compression = compression_none; #endif /* The default for file name restriction defaults to the OS type. */ #if defined(WINDOWS) || defined(MSDOS) || defined(__CYGWIN__) opt.restrict_files_os = restrict_windows; #elif defined(__VMS) opt.restrict_files_os = restrict_vms; #else opt.restrict_files_os = restrict_unix; #endif opt.restrict_files_ctrl = true; opt.restrict_files_nonascii = false; opt.restrict_files_case = restrict_no_case_restriction; opt.regex_type = regex_type_posix; opt.max_redirect = 20; opt.waitretry = 10; #ifdef ENABLE_IRI opt.enable_iri = true; #else opt.enable_iri = false; #endif opt.locale = NULL; opt.encoding_remote = NULL; opt.useservertimestamps = true; opt.show_all_dns_entries = false; opt.warc_maxsize = 0; /* 1024 * 1024 * 1024; */ #ifdef HAVE_LIBZ opt.warc_compression_enabled = true; #else opt.warc_compression_enabled = false; #endif opt.warc_digests_enabled = true; opt.warc_cdx_enabled = false; opt.warc_cdx_dedup_filename = NULL; opt.warc_tempdir = NULL; opt.warc_keep_log = true; /* Use a negative value to mark the absence of --start-pos option */ opt.start_pos = -1; opt.show_progress = -1; opt.noscroll = false; #ifdef HAVE_HSTS /* HSTS is enabled by default */ opt.hsts = true; #endif #ifdef ENABLE_XATTR opt.enable_xattr = true; #else opt.enable_xattr = false; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Don't use extended attributes (--xattr) by default * src/init.c (defaults): Set enable_xattr to false by default * src/main.c (print_help): Reverse option logic of --xattr * doc/wget.texi: Add description for --xattr Users may not be aware that the origin URL and Referer are saved including credentials, and possibly access tokens within the urls.'</s>
<s>[INST] Given the following code containing errors, provide 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 ipddp_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { struct ipddp_route __user *rt = ifr->ifr_data; struct ipddp_route rcp, rcp2, *rp; if(!capable(CAP_NET_ADMIN)) return -EPERM; if(copy_from_user(&rcp, rt, sizeof(rcp))) return -EFAULT; switch(cmd) { case SIOCADDIPDDPRT: return ipddp_create(&rcp); case SIOCFINDIPDDPRT: spin_lock_bh(&ipddp_route_lock); rp = __ipddp_find_route(&rcp); if (rp) memcpy(&rcp2, rp, sizeof(rcp2)); spin_unlock_bh(&ipddp_route_lock); if (rp) { if (copy_to_user(rt, &rcp2, sizeof(struct ipddp_route))) return -EFAULT; return 0; } else return -ENOENT; case SIOCDELIPDDPRT: return ipddp_delete(&rcp); default: return -EINVAL; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'net/appletalk: fix minor pointer leak to userspace in SIOCFINDIPDDPRT Fields ->dev and ->next of struct ipddp_route may be copied to userspace on the SIOCFINDIPDDPRT ioctl. This is only accessible to CAP_NET_ADMIN though. Let's manually copy the relevant fields instead of using memcpy(). BugLink: http://blog.infosectcbr.com.au/2018/09/linux-kernel-infoleaks.html Cc: Jann Horn <jannh@google.com> Signed-off-by: Willy Tarreau <w@1wt.eu> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: send_request (ctrl_t ctrl, const char *request, const char *hostportstr, const char *httphost, unsigned int httpflags, gpg_error_t (*post_cb)(void *, http_t), void *post_cb_value, estream_t *r_fp, unsigned int *r_http_status) { gpg_error_t err; http_session_t session = NULL; http_t http = NULL; int redirects_left = MAX_REDIRECTS; estream_t fp = NULL; char *request_buffer = NULL; parsed_uri_t uri = NULL; int is_onion; *r_fp = NULL; err = http_parse_uri (&uri, request, 0); if (err) goto leave; is_onion = uri->onion; err = http_session_new (&session, httphost, ((ctrl->http_no_crl? HTTP_FLAG_NO_CRL : 0) | HTTP_FLAG_TRUST_DEF), gnupg_http_tls_verify_cb, ctrl); if (err) goto leave; http_session_set_log_cb (session, cert_log_cb); http_session_set_timeout (session, ctrl->timeout); once_more: err = http_open (&http, post_cb? HTTP_REQ_POST : HTTP_REQ_GET, request, httphost, /* fixme: AUTH */ NULL, (httpflags |(opt.honor_http_proxy? HTTP_FLAG_TRY_PROXY:0) |(dirmngr_use_tor ()? HTTP_FLAG_FORCE_TOR:0) |(opt.disable_ipv4? HTTP_FLAG_IGNORE_IPv4 : 0) |(opt.disable_ipv6? HTTP_FLAG_IGNORE_IPv6 : 0)), ctrl->http_proxy, session, NULL, /*FIXME curl->srvtag*/NULL); if (!err) { fp = http_get_write_ptr (http); /* Avoid caches to get the most recent copy of the key. We set both the Pragma and Cache-Control versions of the header, so we're good with both HTTP 1.0 and 1.1. */ es_fputs ("Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n", fp); if (post_cb) err = post_cb (post_cb_value, http); if (!err) { http_start_data (http); if (es_ferror (fp)) err = gpg_error_from_syserror (); } } if (err) { /* Fixme: After a redirection we show the old host name. */ log_error (_("error connecting to '%s': %s\n"), hostportstr, gpg_strerror (err)); goto leave; } /* Wait for the response. */ dirmngr_tick (ctrl); err = http_wait_response (http); if (err) { log_error (_("error reading HTTP response for '%s': %s\n"), hostportstr, gpg_strerror (err)); goto leave; } if (http_get_tls_info (http, NULL)) { /* Update the httpflags so that a redirect won't fallback to an unencrypted connection. */ httpflags |= HTTP_FLAG_FORCE_TLS; } if (r_http_status) *r_http_status = http_get_status_code (http); switch (http_get_status_code (http)) { case 200: err = 0; break; /* Success. */ case 301: case 302: case 307: { const char *s = http_get_header (http, "Location"); log_info (_("URL '%s' redirected to '%s' (%u)\n"), request, s?s:"[none]", http_get_status_code (http)); if (s && *s && redirects_left-- ) { if (is_onion) { /* Make sure that an onion address only redirects to * another onion address. */ http_release_parsed_uri (uri); uri = NULL; err = http_parse_uri (&uri, s, 0); if (err) goto leave; if (! uri->onion) { err = gpg_error (GPG_ERR_FORBIDDEN); goto leave; } } xfree (request_buffer); request_buffer = xtrystrdup (s); if (request_buffer) { request = request_buffer; http_close (http, 0); http = NULL; goto once_more; } err = gpg_error_from_syserror (); } else err = gpg_error (GPG_ERR_NO_DATA); log_error (_("too many redirections\n")); } goto leave; case 501: err = gpg_error (GPG_ERR_NOT_IMPLEMENTED); goto leave; default: log_error (_("error accessing '%s': http status %u\n"), request, http_get_status_code (http)); err = gpg_error (GPG_ERR_NO_DATA); goto leave; } /* FIXME: We should register a permanent redirection and whether a host has ever used TLS so that future calls will always use TLS. */ fp = http_get_read_ptr (http); if (!fp) { err = gpg_error (GPG_ERR_BUG); goto leave; } /* Return the read stream and close the HTTP context. */ *r_fp = fp; http_close (http, 1); http = NULL; leave: http_close (http, 0); http_session_release (session); xfree (request_buffer); http_release_parsed_uri (uri); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-352'], 'message': 'dirmngr: Avoid possible CSRF attacks via http redirects. * dirmngr/http.h (parsed_uri_s): Add fields off_host and off_path. (http_redir_info_t): New. * dirmngr/http.c (do_parse_uri): Set new fields. (same_host_p): New. (http_prepare_redirect): New. * dirmngr/t-http-basic.c: New test. * dirmngr/ks-engine-hkp.c (send_request): Use http_prepare_redirect instead of the open code. * dirmngr/ks-engine-http.c (ks_http_fetch): Ditto. -- With this change a http query will not follow a redirect unless the Location header gives the same host. If the host is different only the host and port is taken from the Location header and the original path and query parts are kept. Signed-off-by: Werner Koch <wk@gnupg.org> (cherry picked from commit fa1b1eaa4241ff3f0634c8bdf8591cbc7c464144)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _pickle_UnpicklerMemoProxy_copy_impl(UnpicklerMemoProxyObject *self) /*[clinic end generated code: output=e12af7e9bc1e4c77 input=97769247ce032c1d]*/ { Py_ssize_t i; PyObject *new_memo = PyDict_New(); if (new_memo == NULL) return NULL; for (i = 0; i < self->unpickler->memo_size; i++) { int status; PyObject *key, *value; value = self->unpickler->memo[i]; if (value == NULL) continue; key = PyLong_FromSsize_t(i); if (key == NULL) goto error; status = PyDict_SetItem(new_memo, key, value); Py_DECREF(key); if (status < 0) goto error; } return new_memo; error: Py_DECREF(new_memo); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-369'], 'message': 'closes bpo-34656: Avoid relying on signed overflow in _pickle memos. (GH-9261)'</s>
<s>[INST] Given the following code containing errors, provide 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 jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in, int compno, int rlvlno, int prcno, int lyrno) { jpc_bitstream_t *inb; jpc_dec_tcomp_t *tcomp; jpc_dec_rlvl_t *rlvl; jpc_dec_band_t *band; jpc_dec_cblk_t *cblk; int n; int m; int i; jpc_tagtreenode_t *leaf; int included; int ret; int numnewpasses; jpc_dec_seg_t *seg; int len; int present; int savenumnewpasses; int mycounter; jpc_ms_t *ms; jpc_dec_tile_t *tile; jpc_dec_ccp_t *ccp; jpc_dec_cp_t *cp; int bandno; jpc_dec_prc_t *prc; int usedcblkcnt; int cblkno; uint_fast32_t bodylen; bool discard; int passno; int maxpasses; int hdrlen; int hdroffstart; int hdroffend; /* Avoid compiler warning about possible use of uninitialized variable. */ bodylen = 0; discard = (lyrno >= dec->maxlyrs); tile = dec->curtile; cp = tile->cp; ccp = &cp->ccps[compno]; /* * Decode the packet header. */ /* Decode the SOP marker segment if present. */ if (cp->csty & JPC_COD_SOP) { if (jpc_dec_lookahead(in) == JPC_MS_SOP) { if (!(ms = jpc_getms(in, dec->cstate))) { return -1; } if (jpc_ms_gettype(ms) != JPC_MS_SOP) { jpc_ms_destroy(ms); jas_eprintf("missing SOP marker segment\n"); return -1; } jpc_ms_destroy(ms); } } hdroffstart = jas_stream_getrwcount(pkthdrstream); if (!(inb = jpc_bitstream_sopen(pkthdrstream, "r"))) { return -1; } if ((present = jpc_bitstream_getbit(inb)) < 0) { return 1; } JAS_DBGLOG(10, ("\n", present)); JAS_DBGLOG(10, ("present=%d ", present)); /* Is the packet non-empty? */ if (present) { /* The packet is non-empty. */ tcomp = &tile->tcomps[compno]; rlvl = &tcomp->rlvls[rlvlno]; bodylen = 0; for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { if (!band->data) { continue; } prc = &band->prcs[prcno]; if (!prc->cblks) { continue; } usedcblkcnt = 0; for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) { ++usedcblkcnt; if (!cblk->numpasses) { leaf = jpc_tagtree_getleaf(prc->incltagtree, usedcblkcnt - 1); if ((included = jpc_tagtree_decode(prc->incltagtree, leaf, lyrno + 1, inb)) < 0) { return -1; } } else { if ((included = jpc_bitstream_getbit(inb)) < 0) { return -1; } } JAS_DBGLOG(10, ("\n")); JAS_DBGLOG(10, ("included=%d ", included)); if (!included) { continue; } if (!cblk->numpasses) { i = 1; leaf = jpc_tagtree_getleaf(prc->numimsbstagtree, usedcblkcnt - 1); for (;;) { if ((ret = jpc_tagtree_decode(prc->numimsbstagtree, leaf, i, inb)) < 0) { return -1; } if (ret) { break; } ++i; } cblk->numimsbs = i - 1; cblk->firstpassno = cblk->numimsbs * 3; } if ((numnewpasses = jpc_getnumnewpasses(inb)) < 0) { return -1; } JAS_DBGLOG(10, ("numnewpasses=%d ", numnewpasses)); seg = cblk->curseg; savenumnewpasses = numnewpasses; mycounter = 0; if (numnewpasses > 0) { if ((m = jpc_getcommacode(inb)) < 0) { return -1; } cblk->numlenbits += m; JAS_DBGLOG(10, ("increment=%d ", m)); while (numnewpasses > 0) { passno = cblk->firstpassno + cblk->numpasses + mycounter; /* XXX - the maxpasses is not set precisely but this doesn't matter... */ maxpasses = JPC_SEGPASSCNT(passno, cblk->firstpassno, 10000, (ccp->cblkctx & JPC_COX_LAZY) != 0, (ccp->cblkctx & JPC_COX_TERMALL) != 0); if (!discard && !seg) { if (!(seg = jpc_seg_alloc())) { return -1; } jpc_seglist_insert(&cblk->segs, cblk->segs.tail, seg); if (!cblk->curseg) { cblk->curseg = seg; } seg->passno = passno; seg->type = JPC_SEGTYPE(seg->passno, cblk->firstpassno, (ccp->cblkctx & JPC_COX_LAZY) != 0); seg->maxpasses = maxpasses; } n = JAS_MIN(numnewpasses, maxpasses); mycounter += n; numnewpasses -= n; if ((len = jpc_bitstream_getbits(inb, cblk->numlenbits + jpc_floorlog2(n))) < 0) { return -1; } JAS_DBGLOG(10, ("len=%d ", len)); if (!discard) { seg->lyrno = lyrno; seg->numpasses += n; seg->cnt = len; seg = seg->next; } bodylen += len; } } cblk->numpasses += savenumnewpasses; } } jpc_bitstream_inalign(inb, 0, 0); } else { if (jpc_bitstream_inalign(inb, 0x7f, 0)) { jas_eprintf("alignment failed\n"); return -1; } } jpc_bitstream_close(inb); hdroffend = jas_stream_getrwcount(pkthdrstream); hdrlen = hdroffend - hdroffstart; if (jas_getdbglevel() >= 5) { jas_eprintf("hdrlen=%lu bodylen=%lu \n", (unsigned long) hdrlen, (unsigned long) bodylen); } if (cp->csty & JPC_COD_EPH) { if (jpc_dec_lookahead(pkthdrstream) == JPC_MS_EPH) { if (!(ms = jpc_getms(pkthdrstream, dec->cstate))) { jas_eprintf("cannot get (EPH) marker segment\n"); return -1; } if (jpc_ms_gettype(ms) != JPC_MS_EPH) { jpc_ms_destroy(ms); jas_eprintf("missing EPH marker segment\n"); return -1; } jpc_ms_destroy(ms); } } /* decode the packet body. */ if (jas_getdbglevel() >= 1) { jas_eprintf("packet body offset=%06ld\n", (long) jas_stream_getrwcount(in)); } if (!discard) { tcomp = &tile->tcomps[compno]; rlvl = &tcomp->rlvls[rlvlno]; for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { if (!band->data) { continue; } prc = &band->prcs[prcno]; if (!prc->cblks) { continue; } for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) { seg = cblk->curseg; while (seg) { if (!seg->stream) { if (!(seg->stream = jas_stream_memopen(0, 0))) { return -1; } } #if 0 jas_eprintf("lyrno=%02d, compno=%02d, lvlno=%02d, prcno=%02d, bandno=%02d, cblkno=%02d, passno=%02d numpasses=%02d cnt=%d numbps=%d, numimsbs=%d\n", lyrno, compno, rlvlno, prcno, band - rlvl->bands, cblk - prc->cblks, seg->passno, seg->numpasses, seg->cnt, band->numbps, cblk->numimsbs); #endif if (seg->cnt > 0) { if (jpc_getdata(in, seg->stream, seg->cnt) < 0) { return -1; } seg->cnt = 0; } if (seg->numpasses >= seg->maxpasses) { cblk->curseg = seg->next; } seg = seg->next; } } } } else { if (jas_stream_gobble(in, bodylen) != JAS_CAST(int, bodylen)) { return -1; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'jpc_t2dec: fix various memory leaks in jpc_dec_decodepkt() Fixes CVE-2018-20622 Closes https://github.com/jasper-maint/jasper/issues/12 Closes https://github.com/mdadams/jasper/issues/193'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: return_enc_padata(krb5_context context, krb5_data *req_pkt, krb5_kdc_req *request, krb5_keyblock *reply_key, krb5_db_entry *server, krb5_enc_kdc_rep_part *reply_encpart, krb5_boolean is_referral) { krb5_error_code code = 0; /* This should be initialized and only used for Win2K compat and other * specific standardized uses such as FAST negotiation. */ assert(reply_encpart->enc_padata == NULL); if (is_referral) { code = return_referral_enc_padata(context, reply_encpart, server); if (code) return code; } code = kdc_handle_protected_negotiation(context, req_pkt, request, reply_key, &reply_encpart->enc_padata); if (code) goto cleanup; /*Add potentially other enc_padata providers*/ cleanup: return code; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'Remove incorrect KDC assertion The assertion in return_enc_padata() is reachable because kdc_make_s4u2self_rep() may have previously added encrypted padata. It is no longer necessary because the code uses add_pa_data_element() instead of allocating a new list. CVE-2018-20217: In MIT krb5 1.8 or later, an authenticated user who can obtain a TGT using an older encryption type (DES, DES3, or RC4) can cause an assertion failure in the KDC by sending an S4U2Self request. [ghudson@mit.edu: rewrote commit message with CVE description] ticket: 8767 (new) tags: pullup target_version: 1.17 target_version: 1.16-next target_version: 1.15-next'</s>
<s>[INST] Given the following code containing errors, provide 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 hso_probe(struct usb_interface *interface, const struct usb_device_id *id) { int mux, i, if_num, port_spec; unsigned char port_mask; struct hso_device *hso_dev = NULL; struct hso_shared_int *shared_int; struct hso_device *tmp_dev = NULL; if (interface->cur_altsetting->desc.bInterfaceClass != 0xFF) { dev_err(&interface->dev, "Not our interface\n"); return -ENODEV; } if_num = interface->cur_altsetting->desc.bInterfaceNumber; /* Get the interface/port specification from either driver_info or from * the device itself */ if (id->driver_info) port_spec = ((u32 *)(id->driver_info))[if_num]; else port_spec = hso_get_config_data(interface); /* Check if we need to switch to alt interfaces prior to port * configuration */ if (interface->num_altsetting > 1) usb_set_interface(interface_to_usbdev(interface), if_num, 1); interface->needs_remote_wakeup = 1; /* Allocate new hso device(s) */ switch (port_spec & HSO_INTF_MASK) { case HSO_INTF_MUX: if ((port_spec & HSO_PORT_MASK) == HSO_PORT_NETWORK) { /* Create the network device */ if (!disable_net) { hso_dev = hso_create_net_device(interface, port_spec); if (!hso_dev) goto exit; tmp_dev = hso_dev; } } if (hso_get_mux_ports(interface, &port_mask)) /* TODO: de-allocate everything */ goto exit; shared_int = hso_create_shared_int(interface); if (!shared_int) goto exit; for (i = 1, mux = 0; i < 0x100; i = i << 1, mux++) { if (port_mask & i) { hso_dev = hso_create_mux_serial_device( interface, i, shared_int); if (!hso_dev) goto exit; } } if (tmp_dev) hso_dev = tmp_dev; break; case HSO_INTF_BULK: /* It's a regular bulk interface */ if ((port_spec & HSO_PORT_MASK) == HSO_PORT_NETWORK) { if (!disable_net) hso_dev = hso_create_net_device(interface, port_spec); } else { hso_dev = hso_create_bulk_serial_device(interface, port_spec); } if (!hso_dev) goto exit; break; default: goto exit; } /* save our data pointer in this device */ usb_set_intfdata(interface, hso_dev); /* done */ return 0; exit: hso_free_interface(interface); return -ENODEV; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'USB: hso: Fix OOB memory access in hso_probe/hso_get_config_data The function hso_probe reads if_num from the USB device (as an u8) and uses it without a length check to index an array, resulting in an OOB memory read in hso_probe or hso_get_config_data. Add a length check for both locations and updated hso_probe to bail on error. This issue has been assigned CVE-2018-19985. Reported-by: Hui Peng <benquike@gmail.com> Reported-by: Mathias Payer <mathias.payer@nebelwelt.net> Signed-off-by: Hui Peng <benquike@gmail.com> Signed-off-by: Mathias Payer <mathias.payer@nebelwelt.net> Reviewed-by: Sebastian Andrzej Siewior <bigeasy@linutronix.de> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: uint8_t* FAST_FUNC udhcp_get_option32(struct dhcp_packet *packet, int code) { uint8_t *r = udhcp_get_option(packet, code); if (r) { if (r[-1] != 4) r = NULL; } return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'udhcpc: when decoding DHCP_SUBNET, ensure it is 4 bytes long function old new delta udhcp_run_script 795 801 +6 Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: long strnlen_user(const char __user *str, long count) { unsigned long max_addr, src_addr; if (unlikely(count <= 0)) return 0; max_addr = user_addr_max(); src_addr = (unsigned long)str; if (likely(src_addr < max_addr)) { unsigned long max = max_addr - src_addr; long retval; user_access_begin(); retval = do_strnlen_user(str, count, max); user_access_end(); return retval; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'make 'user_access_begin()' do 'access_ok()' Originally, the rule used to be that you'd have to do access_ok() separately, and then user_access_begin() before actually doing the direct (optimized) user access. But experience has shown that people then decide not to do access_ok() at all, and instead rely on it being implied by other operations or similar. Which makes it very hard to verify that the access has actually been range-checked. If you use the unsafe direct user accesses, hardware features (either SMAP - Supervisor Mode Access Protection - on x86, or PAN - Privileged Access Never - on ARM) do force you to use user_access_begin(). But nothing really forces the range check. By putting the range check into user_access_begin(), we actually force people to do the right thing (tm), and the range check vill be visible near the actual accesses. We have way too long a history of people trying to avoid them. Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: sec_recv(uint8 * rdpver) { uint32 sec_flags; uint16 channel; STREAM s; while ((s = mcs_recv(&channel, rdpver)) != NULL) { if (rdpver != NULL) { if (*rdpver != 3) { if (*rdpver & 0x80) { in_uint8s(s, 8); /* signature */ sec_decrypt(s->p, s->end - s->p); } return s; } } if (g_encryption || (!g_licence_issued && !g_licence_error_result)) { in_uint32_le(s, sec_flags); if (g_encryption) { if (sec_flags & SEC_ENCRYPT) { in_uint8s(s, 8); /* signature */ sec_decrypt(s->p, s->end - s->p); } if (sec_flags & SEC_LICENCE_NEG) { licence_process(s); continue; } if (sec_flags & 0x0400) /* SEC_REDIRECT_ENCRYPT */ { uint8 swapbyte; in_uint8s(s, 8); /* signature */ sec_decrypt(s->p, s->end - s->p); /* Check for a redirect packet, starts with 00 04 */ if (s->p[0] == 0 && s->p[1] == 4) { /* for some reason the PDU and the length seem to be swapped. This isn't good, but we're going to do a byte for byte swap. So the first foure value appear as: 00 04 XX YY, where XX YY is the little endian length. We're going to use 04 00 as the PDU type, so after our swap this will look like: XX YY 04 00 */ swapbyte = s->p[0]; s->p[0] = s->p[2]; s->p[2] = swapbyte; swapbyte = s->p[1]; s->p[1] = s->p[3]; s->p[3] = swapbyte; swapbyte = s->p[2]; s->p[2] = s->p[3]; s->p[3] = swapbyte; } #ifdef WITH_DEBUG /* warning! this debug statement will show passwords in the clear! */ hexdump(s->p, s->end - s->p); #endif } } else { if ((sec_flags & 0xffff) == SEC_LICENCE_NEG) { licence_process(s); continue; } s->p -= 4; } } if (channel != MCS_GLOBAL_CHANNEL) { channel_process(s, channel); if (rdpver != NULL) *rdpver = 0xff; return s; } return s; } return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void change_port_settings(struct tty_struct *tty, struct edgeport_port *edge_port, struct ktermios *old_termios) { struct device *dev = &edge_port->port->dev; struct ump_uart_config *config; int baud; unsigned cflag; int status; int port_number = edge_port->port->port_number; config = kmalloc (sizeof (*config), GFP_KERNEL); if (!config) { tty->termios = *old_termios; return; } cflag = tty->termios.c_cflag; config->wFlags = 0; /* These flags must be set */ config->wFlags |= UMP_MASK_UART_FLAGS_RECEIVE_MS_INT; config->wFlags |= UMP_MASK_UART_FLAGS_AUTO_START_ON_ERR; config->bUartMode = (__u8)(edge_port->bUartMode); switch (cflag & CSIZE) { case CS5: config->bDataBits = UMP_UART_CHAR5BITS; dev_dbg(dev, "%s - data bits = 5\n", __func__); break; case CS6: config->bDataBits = UMP_UART_CHAR6BITS; dev_dbg(dev, "%s - data bits = 6\n", __func__); break; case CS7: config->bDataBits = UMP_UART_CHAR7BITS; dev_dbg(dev, "%s - data bits = 7\n", __func__); break; default: case CS8: config->bDataBits = UMP_UART_CHAR8BITS; dev_dbg(dev, "%s - data bits = 8\n", __func__); break; } if (cflag & PARENB) { if (cflag & PARODD) { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_ODDPARITY; dev_dbg(dev, "%s - parity = odd\n", __func__); } else { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_EVENPARITY; dev_dbg(dev, "%s - parity = even\n", __func__); } } else { config->bParity = UMP_UART_NOPARITY; dev_dbg(dev, "%s - parity = none\n", __func__); } if (cflag & CSTOPB) { config->bStopBits = UMP_UART_STOPBIT2; dev_dbg(dev, "%s - stop bits = 2\n", __func__); } else { config->bStopBits = UMP_UART_STOPBIT1; dev_dbg(dev, "%s - stop bits = 1\n", __func__); } /* figure out the flow control settings */ if (cflag & CRTSCTS) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X_CTS_FLOW; config->wFlags |= UMP_MASK_UART_FLAGS_RTS_FLOW; dev_dbg(dev, "%s - RTS/CTS is enabled\n", __func__); } else { dev_dbg(dev, "%s - RTS/CTS is disabled\n", __func__); restart_read(edge_port); } /* * if we are implementing XON/XOFF, set the start and stop * character in the device */ config->cXon = START_CHAR(tty); config->cXoff = STOP_CHAR(tty); /* if we are implementing INBOUND XON/XOFF */ if (I_IXOFF(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_IN_X; dev_dbg(dev, "%s - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, "%s - INBOUND XON/XOFF is disabled\n", __func__); /* if we are implementing OUTBOUND XON/XOFF */ if (I_IXON(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X; dev_dbg(dev, "%s - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, "%s - OUTBOUND XON/XOFF is disabled\n", __func__); tty->termios.c_cflag &= ~CMSPAR; /* Round the baud rate */ baud = tty_get_baud_rate(tty); if (!baud) { /* pick a default, any default... */ baud = 9600; } else tty_encode_baud_rate(tty, baud, baud); edge_port->baud_rate = baud; config->wBaudRate = (__u16)((461550L + baud/2) / baud); /* FIXME: Recompute actual baud from divisor here */ dev_dbg(dev, "%s - baud rate = %d, wBaudRate = %d\n", __func__, baud, config->wBaudRate); dev_dbg(dev, "wBaudRate: %d\n", (int)(461550L / config->wBaudRate)); dev_dbg(dev, "wFlags: 0x%x\n", config->wFlags); dev_dbg(dev, "bDataBits: %d\n", config->bDataBits); dev_dbg(dev, "bParity: %d\n", config->bParity); dev_dbg(dev, "bStopBits: %d\n", config->bStopBits); dev_dbg(dev, "cXon: %d\n", config->cXon); dev_dbg(dev, "cXoff: %d\n", config->cXoff); dev_dbg(dev, "bUartMode: %d\n", config->bUartMode); /* move the word values into big endian mode */ cpu_to_be16s(&config->wFlags); cpu_to_be16s(&config->wBaudRate); status = send_cmd(edge_port->port->serial->dev, UMPC_SET_CONFIG, (__u8)(UMPM_UART1_PORT + port_number), 0, (__u8 *)config, sizeof(*config)); if (status) dev_dbg(dev, "%s - error %d when trying to write config to device\n", __func__, status); kfree(config); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'USB: serial: io_ti: fix div-by-zero in set_termios Fix a division-by-zero in set_termios when debugging is enabled and a high-enough speed has been requested so that the divisor value becomes zero. Instead of just fixing the offending debug statement, cap the baud rate at the base as a zero divisor value also appears to crash the firmware. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable <stable@vger.kernel.org> # 2.6.12 Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Johan Hovold <johan@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void nsc_rle_decompress_data(NSC_CONTEXT* context) { UINT16 i; BYTE* rle; UINT32 planeSize; UINT32 originalSize; rle = context->Planes; for (i = 0; i < 4; i++) { originalSize = context->OrgByteCount[i]; planeSize = context->PlaneByteCount[i]; if (planeSize == 0) FillMemory(context->priv->PlaneBuffers[i], originalSize, 0xFF); else if (planeSize < originalSize) nsc_rle_decode(rle, context->priv->PlaneBuffers[i], originalSize); else CopyMemory(context->priv->PlaneBuffers[i], rle, originalSize); rle += planeSize; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-787'], 'message': 'Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies.'</s>
<s>[INST] Given the following code containing errors, provide 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 ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { if ((fields->BufferOffset + fields->Len) > Stream_Length(s)) return -1; fields->Buffer = (PBYTE) malloc(fields->Len); if (!fields->Buffer) return -1; Stream_SetPosition(s, fields->BufferOffset); Stream_Read(s, fields->Buffer, fields->Len); } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-125'], 'message': 'Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: BGD_DECLARE(void) gdImageWBMPCtx(gdImagePtr image, int fg, gdIOCtx *out) { int x, y, pos; Wbmp *wbmp; /* create the WBMP */ if((wbmp = createwbmp(gdImageSX(image), gdImageSY(image), WBMP_WHITE)) == NULL) { gd_error("Could not create WBMP\n"); return; } /* fill up the WBMP structure */ pos = 0; for(y = 0; y < gdImageSY(image); y++) { for(x = 0; x < gdImageSX(image); x++) { if(gdImageGetPixel(image, x, y) == fg) { wbmp->bitmap[pos] = WBMP_BLACK; } pos++; } } /* write the WBMP to a gd file descriptor */ if(writewbmp(wbmp, &gd_putout, out)) { gd_error("Could not save WBMP\n"); } /* des submitted this bugfix: gdFree the memory. */ freewbmp(wbmp); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Fix #492: Potential double-free in gdImage*Ptr() Whenever `gdImage*Ptr()` calls `gdImage*Ctx()` and the latter fails, we must not call `gdDPExtractData()`; otherwise a double-free would happen. Since `gdImage*Ctx()` are void functions, and we can't change that for BC reasons, we're introducing static helpers which are used internally. We're adding a regression test for `gdImageJpegPtr()`, but not for `gdImageGifPtr()` and `gdImageWbmpPtr()` since we don't know how to trigger failure of the respective `gdImage*Ctx()` calls. This potential security issue has been reported by Solmaz Salimi (aka. Rooney).'</s>
<s>[INST] Given the following code containing errors, provide 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 *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length) { char *buffer=NULL; int n=0; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, NULL); /* rfbLog("rfbProcessFileTransferReadBuffer(%dlen)\n", length); */ if (length>0) { buffer=malloc((uint64_t)length+1); if (buffer!=NULL) { if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessFileTransferReadBuffer: read"); rfbCloseClient(cl); /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return NULL; } /* Null Terminate */ buffer[length]=0; } } return buffer; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Error out in rfbProcessFileTransferReadBuffer if length can not be allocated re #273'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ldb_wildcard_compare(struct ldb_context *ldb, const struct ldb_parse_tree *tree, const struct ldb_val value, bool *matched) { const struct ldb_schema_attribute *a; struct ldb_val val; struct ldb_val cnk; struct ldb_val *chunk; uint8_t *save_p = NULL; unsigned int c = 0; a = ldb_schema_attribute_by_name(ldb, tree->u.substring.attr); if (!a) { return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX; } if (tree->u.substring.chunks == NULL) { *matched = false; return LDB_SUCCESS; } if (a->syntax->canonicalise_fn(ldb, ldb, &value, &val) != 0) { return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX; } save_p = val.data; cnk.data = NULL; if ( ! tree->u.substring.start_with_wildcard ) { chunk = tree->u.substring.chunks[c]; if (a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch; /* This deals with wildcard prefix searches on binary attributes (eg objectGUID) */ if (cnk.length > val.length) { goto mismatch; } /* * Empty strings are returned as length 0. Ensure * we can cope with this. */ if (cnk.length == 0) { goto mismatch; } if (memcmp((char *)val.data, (char *)cnk.data, cnk.length) != 0) goto mismatch; val.length -= cnk.length; val.data += cnk.length; c++; talloc_free(cnk.data); cnk.data = NULL; } while (tree->u.substring.chunks[c]) { uint8_t *p; chunk = tree->u.substring.chunks[c]; if(a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch; /* * Empty strings are returned as length 0. Ensure * we can cope with this. */ if (cnk.length == 0) { goto mismatch; } /* * Values might be binary blobs. Don't use string * search, but memory search instead. */ p = memmem((const void *)val.data,val.length, (const void *)cnk.data, cnk.length); if (p == NULL) goto mismatch; /* * At this point we know cnk.length <= val.length as * otherwise there could be no match */ if ( (! tree->u.substring.chunks[c + 1]) && (! tree->u.substring.end_with_wildcard) ) { uint8_t *g; uint8_t *end = val.data + val.length; do { /* greedy */ /* * haystack is a valid pointer in val * because the memmem() can only * succeed if the needle (cnk.length) * is <= haystacklen * * p will be a pointer at least * cnk.length from the end of haystack */ uint8_t *haystack = p + cnk.length; size_t haystacklen = end - (haystack); g = memmem(haystack, haystacklen, (const uint8_t *)cnk.data, cnk.length); if (g) p = g; } while(g); } val.length = val.length - (p - (uint8_t *)(val.data)) - cnk.length; val.data = (uint8_t *)(p + cnk.length); c++; talloc_free(cnk.data); cnk.data = NULL; } /* last chunk may not have reached end of string */ if ( (! tree->u.substring.end_with_wildcard) && (*(val.data) != 0) ) goto mismatch; talloc_free(save_p); *matched = true; return LDB_SUCCESS; mismatch: *matched = false; talloc_free(save_p); talloc_free(cnk.data); return LDB_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2019-3824 ldb: Improve code style and layout in wildcard processing BUG: https://bugzilla.samba.org/show_bug.cgi?id=13773 Signed-off-by: Andrew Bartlett <abartlet@samba.org> Reviewed-by: Gary Lockyer <gary@catalyst.net.nz>'</s>
<s>[INST] Given the following code containing errors, provide 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 copy_verifier_state(struct bpf_verifier_state *dst_state, const struct bpf_verifier_state *src) { struct bpf_func_state *dst; int i, err; /* if dst has more stack frames then src frame, free them */ for (i = src->curframe + 1; i <= dst_state->curframe; i++) { free_func_state(dst_state->frame[i]); dst_state->frame[i] = NULL; } dst_state->curframe = src->curframe; for (i = 0; i <= src->curframe; i++) { dst = dst_state->frame[i]; if (!dst) { dst = kzalloc(sizeof(*dst), GFP_KERNEL); if (!dst) return -ENOMEM; dst_state->frame[i] = dst; } err = copy_func_state(dst, src->frame[i]); if (err) return err; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'bpf: prevent out of bounds speculation on pointer arithmetic Jann reported that the original commit back in b2157399cc98 ("bpf: prevent out-of-bounds speculation") was not sufficient to stop CPU from speculating out of bounds memory access: While b2157399cc98 only focussed on masking array map access for unprivileged users for tail calls and data access such that the user provided index gets sanitized from BPF program and syscall side, there is still a more generic form affected from BPF programs that applies to most maps that hold user data in relation to dynamic map access when dealing with unknown scalars or "slow" known scalars as access offset, for example: - Load a map value pointer into R6 - Load an index into R7 - Do a slow computation (e.g. with a memory dependency) that loads a limit into R8 (e.g. load the limit from a map for high latency, then mask it to make the verifier happy) - Exit if R7 >= R8 (mispredicted branch) - Load R0 = R6[R7] - Load R0 = R6[R0] For unknown scalars there are two options in the BPF verifier where we could derive knowledge from in order to guarantee safe access to the memory: i) While </>/<=/>= variants won't allow to derive any lower or upper bounds from the unknown scalar where it would be safe to add it to the map value pointer, it is possible through ==/!= test however. ii) another option is to transform the unknown scalar into a known scalar, for example, through ALU ops combination such as R &= <imm> followed by R |= <imm> or any similar combination where the original information from the unknown scalar would be destroyed entirely leaving R with a constant. The initial slow load still precedes the latter ALU ops on that register, so the CPU executes speculatively from that point. Once we have the known scalar, any compare operation would work then. A third option only involving registers with known scalars could be crafted as described in [0] where a CPU port (e.g. Slow Int unit) would be filled with many dependent computations such that the subsequent condition depending on its outcome has to wait for evaluation on its execution port and thereby executing speculatively if the speculated code can be scheduled on a different execution port, or any other form of mistraining as described in [1], for example. Given this is not limited to only unknown scalars, not only map but also stack access is affected since both is accessible for unprivileged users and could potentially be used for out of bounds access under speculation. In order to prevent any of these cases, the verifier is now sanitizing pointer arithmetic on the offset such that any out of bounds speculation would be masked in a way where the pointer arithmetic result in the destination register will stay unchanged, meaning offset masked into zero similar as in array_index_nospec() case. With regards to implementation, there are three options that were considered: i) new insn for sanitation, ii) push/pop insn and sanitation as inlined BPF, iii) reuse of ax register and sanitation as inlined BPF. Option i) has the downside that we end up using from reserved bits in the opcode space, but also that we would require each JIT to emit masking as native arch opcodes meaning mitigation would have slow adoption till everyone implements it eventually which is counter-productive. Option ii) and iii) have both in common that a temporary register is needed in order to implement the sanitation as inlined BPF since we are not allowed to modify the source register. While a push / pop insn in ii) would be useful to have in any case, it requires once again that every JIT needs to implement it first. While possible, amount of changes needed would also be unsuitable for a -stable patch. Therefore, the path which has fewer changes, less BPF instructions for the mitigation and does not require anything to be changed in the JITs is option iii) which this work is pursuing. The ax register is already mapped to a register in all JITs (modulo arm32 where it's mapped to stack as various other BPF registers there) and used in constant blinding for JITs-only so far. It can be reused for verifier rewrites under certain constraints. The interpreter's tmp "register" has therefore been remapped into extending the register set with hidden ax register and reusing that for a number of instructions that needed the prior temporary variable internally (e.g. div, mod). This allows for zero increase in stack space usage in the interpreter, and enables (restricted) generic use in rewrites otherwise as long as such a patchlet does not make use of these instructions. The sanitation mask is dynamic and relative to the offset the map value or stack pointer currently holds. There are various cases that need to be taken under consideration for the masking, e.g. such operation could look as follows: ptr += val or val += ptr or ptr -= val. Thus, the value to be sanitized could reside either in source or in destination register, and the limit is different depending on whether the ALU op is addition or subtraction and depending on the current known and bounded offset. The limit is derived as follows: limit := max_value_size - (smin_value + off). For subtraction: limit := umax_value + off. This holds because we do not allow any pointer arithmetic that would temporarily go out of bounds or would have an unknown value with mixed signed bounds where it is unclear at verification time whether the actual runtime value would be either negative or positive. For example, we have a derived map pointer value with constant offset and bounded one, so limit based on smin_value works because the verifier requires that statically analyzed arithmetic on the pointer must be in bounds, and thus it checks if resulting smin_value + off and umax_value + off is still within map value bounds at time of arithmetic in addition to time of access. Similarly, for the case of stack access we derive the limit as follows: MAX_BPF_STACK + off for subtraction and -off for the case of addition where off := ptr_reg->off + ptr_reg->var_off.value. Subtraction is a special case for the masking which can be in form of ptr += -val, ptr -= -val, or ptr -= val. In the first two cases where we know that the value is negative, we need to temporarily negate the value in order to do the sanitation on a positive value where we later swap the ALU op, and restore original source register if the value was in source. The sanitation of pointer arithmetic alone is still not fully sufficient as is, since a scenario like the following could happen ... PTR += 0x1000 (e.g. K-based imm) PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON PTR += 0x1000 PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON [...] ... which under speculation could end up as ... PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] [...] ... and therefore still access out of bounds. To prevent such case, the verifier is also analyzing safety for potential out of bounds access under speculative execution. Meaning, it is also simulating pointer access under truncation. We therefore "branch off" and push the current verification state after the ALU operation with known 0 to the verification stack for later analysis. Given the current path analysis succeeded it is likely that the one under speculation can be pruned. In any case, it is also subject to existing complexity limits and therefore anything beyond this point will be rejected. In terms of pruning, it needs to be ensured that the verification state from speculative execution simulation must never prune a non-speculative execution path, therefore, we mark verifier state accordingly at the time of push_stack(). If verifier detects out of bounds access under speculative execution from one of the possible paths that includes a truncation, it will reject such program. Given we mask every reg-based pointer arithmetic for unprivileged programs, we've been looking into how it could affect real-world programs in terms of size increase. As the majority of programs are targeted for privileged-only use case, we've unconditionally enabled masking (with its alu restrictions on top of it) for privileged programs for the sake of testing in order to check i) whether they get rejected in its current form, and ii) by how much the number of instructions and size will increase. We've tested this by using Katran, Cilium and test_l4lb from the kernel selftests. For Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o and an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb we've used test_l4lb.o as well as test_l4lb_noinline.o. We found that none of the programs got rejected by the verifier with this change, and that impact is rather minimal to none. balancer_kern.o had 13,904 bytes (1,738 insns) xlated and 7,797 bytes JITed before and after the change. Most complex program in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated and 18,538 bytes JITed before and after and none of the other tail call programs in bpf_lxc.o had any changes either. For the older bpf_lxc_opt_-DUNKNOWN.o object we found a small increase from 20,616 bytes (2,576 insns) and 12,536 bytes JITed before to 20,664 bytes (2,582 insns) and 12,558 bytes JITed after the change. Other programs from that object file had similar small increase. Both test_l4lb.o had no change and remained at 6,544 bytes (817 insns) xlated and 3,401 bytes JITed and for test_l4lb_noinline.o constant at 5,080 bytes (634 insns) xlated and 3,313 bytes JITed. This can be explained in that LLVM typically optimizes stack based pointer arithmetic by using K-based operations and that use of dynamic map access is not overly frequent. However, in future we may decide to optimize the algorithm further under known guarantees from branch and value speculation. Latter seems also unclear in terms of prediction heuristics that today's CPUs apply as well as whether there could be collisions in e.g. the predictor's Value History/Pattern Table for triggering out of bounds access, thus masking is performed unconditionally at this point but could be subject to relaxation later on. We were generally also brainstorming various other approaches for mitigation, but the blocker was always lack of available registers at runtime and/or overhead for runtime tracking of limits belonging to a specific pointer. Thus, we found this to be minimally intrusive under given constraints. With that in place, a simple example with sanitized access on unprivileged load at post-verification time looks as follows: # bpftool prog dump xlated id 282 [...] 28: (79) r1 = *(u64 *)(r7 +0) 29: (79) r2 = *(u64 *)(r7 +8) 30: (57) r1 &= 15 31: (79) r3 = *(u64 *)(r0 +4608) 32: (57) r3 &= 1 33: (47) r3 |= 1 34: (2d) if r2 > r3 goto pc+19 35: (b4) (u32) r11 = (u32) 20479 | 36: (1f) r11 -= r2 | Dynamic sanitation for pointer 37: (4f) r11 |= r2 | arithmetic with registers 38: (87) r11 = -r11 | containing bounded or known 39: (c7) r11 s>>= 63 | scalars in order to prevent 40: (5f) r11 &= r2 | out of bounds speculation. 41: (0f) r4 += r11 | 42: (71) r4 = *(u8 *)(r4 +0) 43: (6f) r4 <<= r1 [...] For the case where the scalar sits in the destination register as opposed to the source register, the following code is emitted for the above example: [...] 16: (b4) (u32) r11 = (u32) 20479 17: (1f) r11 -= r2 18: (4f) r11 |= r2 19: (87) r11 = -r11 20: (c7) r11 s>>= 63 21: (5f) r2 &= r11 22: (0f) r2 += r0 23: (61) r0 = *(u32 *)(r2 +0) [...] JIT blinding example with non-conflicting use of r10: [...] d5: je 0x0000000000000106 _ d7: mov 0x0(%rax),%edi | da: mov $0xf153246,%r10d | Index load from map value and e0: xor $0xf153259,%r10 | (const blinded) mask with 0x1f. e7: and %r10,%rdi |_ ea: mov $0x2f,%r10d | f0: sub %rdi,%r10 | Sanitized addition. Both use r10 f3: or %rdi,%r10 | but do not interfere with each f6: neg %r10 | other. (Neither do these instructions f9: sar $0x3f,%r10 | interfere with the use of ax as temp fd: and %r10,%rdi | in interpreter.) 100: add %rax,%rdi |_ 103: mov 0x0(%rdi),%eax [...] Tested that it fixes Jann's reproducer, and also checked that test_verifier and test_progs suite with interpreter, JIT and JIT with hardening enabled on x86-64 and arm64 runs successfully. [0] Speculose: Analyzing the Security Implications of Speculative Execution in CPUs, Giorgi Maisuradze and Christian Rossow, https://arxiv.org/pdf/1801.04084.pdf [1] A Systematic Evaluation of Transient Execution Attacks and Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz, Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens, Dmitry Evtyushkin, Daniel Gruss, https://arxiv.org/pdf/1811.05441.pdf Fixes: b2157399cc98 ("bpf: prevent out-of-bounds speculation") Reported-by: Jann Horn <jannh@google.com> Signed-off-by: Daniel Borkmann <daniel@iogearbox.net> Acked-by: Alexei Starovoitov <ast@kernel.org> Signed-off-by: Alexei Starovoitov <ast@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: empe_inlinepgp_encrypted_parse (EMailParserExtension *extension, EMailParser *parser, CamelMimePart *part, GString *part_id, GCancellable *cancellable, GQueue *out_mail_parts) { CamelCipherContext *cipher; CamelCipherValidity *valid; CamelMimePart *opart; CamelDataWrapper *dw; gchar *mime_type; gint len; GQueue work_queue = G_QUEUE_INIT; GList *head, *link; GError *local_error = NULL; if (g_cancellable_is_cancelled (cancellable)) return FALSE; cipher = camel_gpg_context_new (e_mail_parser_get_session (parser)); opart = camel_mime_part_new (); /* Decrypt the message */ valid = camel_cipher_context_decrypt_sync ( cipher, part, opart, cancellable, &local_error); if (local_error != NULL) { e_mail_parser_error ( parser, out_mail_parts, _("Could not parse PGP message: %s"), local_error->message); g_error_free (local_error); e_mail_parser_parse_part_as ( parser, part, part_id, "application/vnd.evolution.source", cancellable, out_mail_parts); g_object_unref (cipher); g_object_unref (opart); return TRUE; } dw = camel_medium_get_content ((CamelMedium *) opart); mime_type = camel_data_wrapper_get_mime_type (dw); /* this ensures to show the 'opart' as inlined, if possible */ if (mime_type && g_ascii_strcasecmp (mime_type, "application/octet-stream") == 0) { const gchar *snoop; snoop = e_mail_part_snoop_type (opart); if (snoop != NULL) { camel_data_wrapper_set_mime_type (dw, snoop); /* Set the MIME type on the 'opart' itself as well. * If it's "text/plain", then we want the TextPlain * parser extension to treat it as "text/plain" and * NOT wrap it as an attachment. */ camel_data_wrapper_set_mime_type ( CAMEL_DATA_WRAPPER (opart), snoop); } } e_mail_part_preserve_charset_in_content_type (part, opart); g_free (mime_type); /* Pass it off to the real formatter */ len = part_id->len; g_string_append (part_id, ".inlinepgp_encrypted"); mime_type = camel_data_wrapper_get_mime_type (dw); g_warn_if_fail (e_mail_parser_parse_part_as ( parser, opart, part_id, mime_type, cancellable, &work_queue)); g_free (mime_type); g_string_truncate (part_id, len); head = g_queue_peek_head_link (&work_queue); for (link = head; link != NULL; link = g_list_next (link)) { EMailPart *mail_part = link->data; e_mail_part_update_validity ( mail_part, valid, E_MAIL_PART_VALIDITY_ENCRYPTED | E_MAIL_PART_VALIDITY_PGP); } e_queue_transfer (&work_queue, out_mail_parts); /* Add a widget with details about the encryption, but only when * the encrypted isn't itself secured, in that case it has created * the button itself */ if (!e_mail_part_is_secured (opart)) { EMailPart *mail_part; g_string_append (part_id, ".inlinepgp_encrypted.button"); e_mail_parser_parse_part_as ( parser, part, part_id, "application/vnd.evolution.secure-button", cancellable, &work_queue); mail_part = g_queue_peek_head (&work_queue); if (mail_part != NULL) e_mail_part_update_validity ( mail_part, valid, E_MAIL_PART_VALIDITY_ENCRYPTED | E_MAIL_PART_VALIDITY_PGP); e_queue_transfer (&work_queue, out_mail_parts); g_string_truncate (part_id, len); } /* Clean Up */ camel_cipher_validity_free (valid); g_object_unref (opart); g_object_unref (cipher); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-347'], 'message': 'eds-I#3 - [GPG] Mails that are not encrypted look encrypted Related to https://gitlab.gnome.org/GNOME/evolution-data-server/issues/3'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ews_response_cb (SoupSession *session, SoupMessage *msg, gpointer data) { EwsNode *enode = (EwsNode *) data; ESoapResponse *response; ESoapParameter *param; const gchar *persistent_auth; gint log_level; gint wait_ms = 0; persistent_auth = soup_message_headers_get_one (msg->response_headers, "Persistent-Auth"); if (persistent_auth && g_ascii_strcasecmp (persistent_auth, "false") == 0) { SoupSessionFeature *feature; feature = soup_session_get_feature (session, SOUP_TYPE_AUTH_MANAGER); if (feature) { soup_auth_manager_clear_cached_credentials (SOUP_AUTH_MANAGER (feature)); } } if (g_cancellable_is_cancelled (enode->cancellable)) goto exit; if (ews_connection_credentials_failed (enode->cnc, msg, enode->simple)) { goto exit; } else if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) { if (msg->response_headers) { const gchar *diagnostics; diagnostics = soup_message_headers_get_list (msg->response_headers, "X-MS-DIAGNOSTICS"); if (diagnostics && strstr (diagnostics, "invalid_grant")) { g_simple_async_result_set_error ( enode->simple, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_ACCESSDENIED, "%s", diagnostics); goto exit; } else if (diagnostics && *diagnostics) { g_simple_async_result_set_error ( enode->simple, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_AUTHENTICATION_FAILED, "%s", diagnostics); goto exit; } } g_simple_async_result_set_error ( enode->simple, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_AUTHENTICATION_FAILED, _("Authentication failed")); goto exit; } else if (msg->status_code == SOUP_STATUS_CANT_RESOLVE || msg->status_code == SOUP_STATUS_CANT_RESOLVE_PROXY || msg->status_code == SOUP_STATUS_CANT_CONNECT || msg->status_code == SOUP_STATUS_CANT_CONNECT_PROXY || msg->status_code == SOUP_STATUS_IO_ERROR) { g_simple_async_result_set_error ( enode->simple, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_UNAVAILABLE, "%s", msg->reason_phrase); goto exit; } response = e_soap_message_parse_response ((ESoapMessage *) msg); if (response == NULL) { g_simple_async_result_set_error ( enode->simple, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_NORESPONSE, _("No response: %s"), msg->reason_phrase); goto exit; } /* TODO: The stdout can be replaced with Evolution's * Logging framework also */ log_level = e_ews_debug_get_log_level (); if (log_level >= 1 && log_level < 3) { /* This will dump only the headers, since we stole the body. * And only if EWS_DEBUG=1, since higher levels will have dumped * it directly from libsoup anyway. */ e_ews_debug_dump_raw_soup_response (msg); /* And this will dump the body... */ e_soap_response_dump_response (response, stdout); } param = e_soap_response_get_first_parameter_by_name (response, "detail", NULL); if (param) param = e_soap_parameter_get_first_child_by_name (param, "ResponseCode"); if (param) { gchar *value; value = e_soap_parameter_get_string_value (param); if (value && ews_get_error_code (value) == EWS_CONNECTION_ERROR_SERVERBUSY) { param = e_soap_response_get_first_parameter_by_name (response, "detail", NULL); if (param) param = e_soap_parameter_get_first_child_by_name (param, "MessageXml"); if (param) { param = e_soap_parameter_get_first_child_by_name (param, "Value"); if (param) { g_free (value); value = e_soap_parameter_get_property (param, "Name"); if (g_strcmp0 (value, "BackOffMilliseconds") == 0) { wait_ms = e_soap_parameter_get_int_value (param); } } } } g_free (value); } if (wait_ms > 0 && e_ews_connection_get_backoff_enabled (enode->cnc)) { GCancellable *cancellable = enode->cancellable; EFlag *flag; if (cancellable) g_object_ref (cancellable); g_object_ref (msg); flag = e_flag_new (); while (wait_ms > 0 && !g_cancellable_is_cancelled (cancellable) && msg->status_code != SOUP_STATUS_CANCELLED) { gint64 now = g_get_monotonic_time (); gint left_minutes, left_seconds; left_minutes = wait_ms / 60000; left_seconds = (wait_ms / 1000) % 60; if (left_minutes > 0) { camel_operation_push_message (cancellable, g_dngettext (GETTEXT_PACKAGE, "Exchange server is busy, waiting to retry (%d:%02d minute)", "Exchange server is busy, waiting to retry (%d:%02d minutes)", left_minutes), left_minutes, left_seconds); } else { camel_operation_push_message (cancellable, g_dngettext (GETTEXT_PACKAGE, "Exchange server is busy, waiting to retry (%d second)", "Exchange server is busy, waiting to retry (%d seconds)", left_seconds), left_seconds); } e_flag_wait_until (flag, now + (G_TIME_SPAN_MILLISECOND * (wait_ms > 1000 ? 1000 : wait_ms))); now = g_get_monotonic_time () - now; now = now / G_TIME_SPAN_MILLISECOND; if (now >= wait_ms) wait_ms = 0; wait_ms -= now; camel_operation_pop_message (cancellable); } e_flag_free (flag); g_object_unref (response); if (g_cancellable_is_cancelled (cancellable) || msg->status_code == SOUP_STATUS_CANCELLED) { g_clear_object (&cancellable); g_object_unref (msg); } else { EwsNode *new_node; new_node = ews_node_new (); new_node->msg = E_SOAP_MESSAGE (msg); /* takes ownership */ new_node->pri = enode->pri; new_node->cb = enode->cb; new_node->cnc = enode->cnc; new_node->simple = enode->simple; enode->simple = NULL; QUEUE_LOCK (enode->cnc); enode->cnc->priv->jobs = g_slist_prepend (enode->cnc->priv->jobs, new_node); QUEUE_UNLOCK (enode->cnc); if (cancellable) { new_node->cancellable = g_object_ref (cancellable); new_node->cancel_handler_id = g_cancellable_connect ( cancellable, G_CALLBACK (ews_cancel_request), new_node, NULL); } g_clear_object (&cancellable); } goto exit; } if (enode->cb != NULL) enode->cb (response, enode->simple); g_object_unref (response); exit: if (enode->simple) g_simple_async_result_complete_in_idle (enode->simple); ews_active_job_done (enode->cnc, enode); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too. Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: e_ews_autodiscover_ws_url_finish (CamelEwsSettings *settings, GAsyncResult *result, GError **error) { GSimpleAsyncResult *simple; struct _autodiscover_data *ad; g_return_val_if_fail ( g_simple_async_result_is_valid ( result, G_OBJECT (settings), e_ews_autodiscover_ws_url), FALSE); simple = G_SIMPLE_ASYNC_RESULT (result); ad = g_simple_async_result_get_op_res_gpointer (simple); if (g_simple_async_result_propagate_error (simple, error)) return FALSE; g_warn_if_fail (ad->as_url != NULL); g_warn_if_fail (ad->oab_url != NULL); camel_ews_settings_set_hosturl (settings, ad->as_url); if (!has_suffix_icmp (ad->oab_url, "oab.xml")) { gchar *tmp; if (g_str_has_suffix (ad->oab_url, "/")) tmp = g_strconcat (ad->oab_url, "oab.xml", NULL); else tmp = g_strconcat (ad->oab_url, "/", "oab.xml", NULL); camel_ews_settings_set_oaburl (settings, tmp); g_free (tmp); } else { camel_ews_settings_set_oaburl (settings, ad->oab_url); } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too. Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: e_ews_config_utils_open_connection_for (ESource *source, CamelEwsSettings *ews_settings, const gchar *connect_url, EEwsConfigUtilTryCredentialsFunc try_credentials_func, gpointer user_data, GCancellable *cancellable, GError **perror) { EEwsConnection *conn = NULL; CamelNetworkSettings *network_settings; GError *local_error = NULL; g_return_val_if_fail (source != NULL, NULL); g_return_val_if_fail (ews_settings != NULL, NULL); network_settings = CAMEL_NETWORK_SETTINGS (ews_settings); /* use the one from mailer, if there, otherwise open new */ conn = e_ews_connection_find ( connect_url && *connect_url ? connect_url : camel_ews_settings_get_hosturl (ews_settings), camel_network_settings_get_user (network_settings)); if (conn) { if (try_credentials_func && try_credentials_func (conn, NULL, user_data, cancellable, perror) != E_SOURCE_AUTHENTICATION_ACCEPTED) { g_clear_object (&conn); } return conn; } while (!conn && !g_cancellable_is_cancelled (cancellable) && !local_error) { if (e_ews_connection_utils_get_without_password (ews_settings)) { ESourceAuthenticationResult result; gchar *hosturl; hosturl = camel_ews_settings_dup_hosturl (ews_settings); conn = e_ews_connection_new (source, connect_url && *connect_url ? connect_url : hosturl, ews_settings); g_free (hosturl); e_ews_connection_update_credentials (conn, NULL); if (try_credentials_func) result = try_credentials_func (conn, NULL, user_data, cancellable, &local_error); else result = e_ews_connection_try_credentials_sync (conn, NULL, cancellable, &local_error); if (result != E_SOURCE_AUTHENTICATION_ACCEPTED) { g_clear_object (&conn); if (result != E_SOURCE_AUTHENTICATION_REJECTED || local_error) break; } } if (!conn) { EShell *shell; TryCredentialsData data; e_ews_connection_utils_force_off_ntlm_auth_check (); g_clear_error (&local_error); shell = e_shell_get_default (); data.ews_settings = g_object_ref (ews_settings); data.connect_url = connect_url && *connect_url ? connect_url : NULL; data.try_credentials_func = try_credentials_func; data.user_data = user_data; data.conn = NULL; e_credentials_prompter_loop_prompt_sync (e_shell_get_credentials_prompter (shell), source, E_CREDENTIALS_PROMPTER_PROMPT_FLAG_ALLOW_SOURCE_SAVE, ews_config_utils_try_credentials_sync, &data, cancellable, &local_error); if (data.conn) conn = g_object_ref (data.conn); g_clear_object (&data.ews_settings); g_clear_object (&data.conn); } } if (local_error) g_propagate_error (perror, local_error); return conn; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too. Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ns_xfr_start(ns_client_t *client, dns_rdatatype_t reqtype) { isc_result_t result; dns_name_t *question_name; dns_rdataset_t *question_rdataset; dns_zone_t *zone = NULL, *raw = NULL, *mayberaw; dns_db_t *db = NULL; dns_dbversion_t *ver = NULL; dns_rdataclass_t question_class; rrstream_t *soa_stream = NULL; rrstream_t *data_stream = NULL; rrstream_t *stream = NULL; dns_difftuple_t *current_soa_tuple = NULL; dns_name_t *soa_name; dns_rdataset_t *soa_rdataset; dns_rdata_t soa_rdata = DNS_RDATA_INIT; bool have_soa = false; const char *mnemonic = NULL; isc_mem_t *mctx = client->mctx; dns_message_t *request = client->message; xfrout_ctx_t *xfr = NULL; isc_quota_t *quota = NULL; dns_transfer_format_t format = client->view->transfer_format; isc_netaddr_t na; dns_peer_t *peer = NULL; isc_buffer_t *tsigbuf = NULL; char *journalfile; char msg[NS_CLIENT_ACLMSGSIZE("zone transfer")]; char keyname[DNS_NAME_FORMATSIZE]; bool is_poll = false; bool is_dlz = false; bool is_ixfr = false; uint32_t begin_serial = 0, current_serial; switch (reqtype) { case dns_rdatatype_axfr: mnemonic = "AXFR"; break; case dns_rdatatype_ixfr: mnemonic = "IXFR"; break; default: INSIST(0); ISC_UNREACHABLE(); } ns_client_log(client, DNS_LOGCATEGORY_XFER_OUT, NS_LOGMODULE_XFER_OUT, ISC_LOG_DEBUG(6), "%s request", mnemonic); /* * Apply quota. */ result = isc_quota_attach(&ns_g_server->xfroutquota, &quota); if (result != ISC_R_SUCCESS) { isc_log_write(XFROUT_COMMON_LOGARGS, ISC_LOG_WARNING, "%s request denied: %s", mnemonic, isc_result_totext(result)); goto failure; } /* * Interpret the question section. */ result = dns_message_firstname(request, DNS_SECTION_QUESTION); INSIST(result == ISC_R_SUCCESS); /* * The question section must contain exactly one question, and * it must be for AXFR/IXFR as appropriate. */ question_name = NULL; dns_message_currentname(request, DNS_SECTION_QUESTION, &question_name); question_rdataset = ISC_LIST_HEAD(question_name->list); question_class = question_rdataset->rdclass; INSIST(question_rdataset->type == reqtype); if (ISC_LIST_NEXT(question_rdataset, link) != NULL) FAILC(DNS_R_FORMERR, "multiple questions"); result = dns_message_nextname(request, DNS_SECTION_QUESTION); if (result != ISC_R_NOMORE) FAILC(DNS_R_FORMERR, "multiple questions"); result = dns_zt_find(client->view->zonetable, question_name, 0, NULL, &zone); if (result != ISC_R_SUCCESS) { /* * Normal zone table does not have a match. * Try the DLZ database */ // Temporary: only searching the first DLZ database if (! ISC_LIST_EMPTY(client->view->dlz_searched)) { result = dns_dlzallowzonexfr(client->view, question_name, &client->peeraddr, &db); if (result == ISC_R_NOPERM) { char _buf1[DNS_NAME_FORMATSIZE]; char _buf2[DNS_RDATACLASS_FORMATSIZE]; result = DNS_R_REFUSED; dns_name_format(question_name, _buf1, sizeof(_buf1)); dns_rdataclass_format(question_class, _buf2, sizeof(_buf2)); ns_client_log(client, DNS_LOGCATEGORY_SECURITY, NS_LOGMODULE_XFER_OUT, ISC_LOG_ERROR, "zone transfer '%s/%s' denied", _buf1, _buf2); goto failure; } if (result != ISC_R_SUCCESS) FAILQ(DNS_R_NOTAUTH, "non-authoritative zone", question_name, question_class); is_dlz = true; } else { /* * not DLZ and not in normal zone table, we are * not authoritative */ FAILQ(DNS_R_NOTAUTH, "non-authoritative zone", question_name, question_class); } } else { /* zone table has a match */ switch(dns_zone_gettype(zone)) { /* Master and slave zones are OK for transfer. */ case dns_zone_master: case dns_zone_slave: case dns_zone_dlz: break; default: FAILQ(DNS_R_NOTAUTH, "non-authoritative zone", question_name, question_class); } CHECK(dns_zone_getdb(zone, &db)); dns_db_currentversion(db, &ver); } xfrout_log1(client, question_name, question_class, ISC_LOG_DEBUG(6), "%s question section OK", mnemonic); /* * Check the authority section. Look for a SOA record with * the same name and class as the question. */ for (result = dns_message_firstname(request, DNS_SECTION_AUTHORITY); result == ISC_R_SUCCESS; result = dns_message_nextname(request, DNS_SECTION_AUTHORITY)) { soa_name = NULL; dns_message_currentname(request, DNS_SECTION_AUTHORITY, &soa_name); /* * Ignore data whose owner name is not the zone apex. */ if (! dns_name_equal(soa_name, question_name)) continue; for (soa_rdataset = ISC_LIST_HEAD(soa_name->list); soa_rdataset != NULL; soa_rdataset = ISC_LIST_NEXT(soa_rdataset, link)) { /* * Ignore non-SOA data. */ if (soa_rdataset->type != dns_rdatatype_soa) continue; if (soa_rdataset->rdclass != question_class) continue; CHECK(dns_rdataset_first(soa_rdataset)); dns_rdataset_current(soa_rdataset, &soa_rdata); result = dns_rdataset_next(soa_rdataset); if (result == ISC_R_SUCCESS) FAILC(DNS_R_FORMERR, "IXFR authority section " "has multiple SOAs"); have_soa = true; goto got_soa; } } got_soa: if (result != ISC_R_NOMORE) CHECK(result); xfrout_log1(client, question_name, question_class, ISC_LOG_DEBUG(6), "%s authority section OK", mnemonic); /* * If not a DLZ zone, decide whether to allow this transfer. */ if (!is_dlz) { ns_client_aclmsg("zone transfer", question_name, reqtype, client->view->rdclass, msg, sizeof(msg)); CHECK(ns_client_checkacl(client, NULL, msg, dns_zone_getxfracl(zone), true, ISC_LOG_ERROR)); } /* * AXFR over UDP is not possible. */ if (reqtype == dns_rdatatype_axfr && (client->attributes & NS_CLIENTATTR_TCP) == 0) FAILC(DNS_R_FORMERR, "attempted AXFR over UDP"); /* * Look up the requesting server in the peer table. */ isc_netaddr_fromsockaddr(&na, &client->peeraddr); (void)dns_peerlist_peerbyaddr(client->view->peers, &na, &peer); /* * Decide on the transfer format (one-answer or many-answers). */ if (peer != NULL) (void)dns_peer_gettransferformat(peer, &format); /* * Get a dynamically allocated copy of the current SOA. */ if (is_dlz) dns_db_currentversion(db, &ver); CHECK(dns_db_createsoatuple(db, ver, mctx, DNS_DIFFOP_EXISTS, &current_soa_tuple)); current_serial = dns_soa_getserial(&current_soa_tuple->rdata); if (reqtype == dns_rdatatype_ixfr) { bool provide_ixfr; /* * Outgoing IXFR may have been disabled for this peer * or globally. */ provide_ixfr = client->view->provideixfr; if (peer != NULL) (void) dns_peer_getprovideixfr(peer, &provide_ixfr); if (provide_ixfr == false) goto axfr_fallback; if (! have_soa) FAILC(DNS_R_FORMERR, "IXFR request missing SOA"); begin_serial = dns_soa_getserial(&soa_rdata); /* * RFC1995 says "If an IXFR query with the same or * newer version number than that of the server * is received, it is replied to with a single SOA * record of the server's current version, just as * in AXFR". The claim about AXFR is incorrect, * but other than that, we do as the RFC says. * * Sending a single SOA record is also how we refuse * IXFR over UDP (currently, we always do). */ if (DNS_SERIAL_GE(begin_serial, current_serial) || (client->attributes & NS_CLIENTATTR_TCP) == 0) { CHECK(soa_rrstream_create(mctx, db, ver, &stream)); is_poll = true; goto have_stream; } journalfile = is_dlz ? NULL : dns_zone_getjournal(zone); if (journalfile != NULL) result = ixfr_rrstream_create(mctx, journalfile, begin_serial, current_serial, &data_stream); else result = ISC_R_NOTFOUND; if (result == ISC_R_NOTFOUND || result == ISC_R_RANGE) { xfrout_log1(client, question_name, question_class, ISC_LOG_DEBUG(4), "IXFR version not in journal, " "falling back to AXFR"); mnemonic = "AXFR-style IXFR"; goto axfr_fallback; } CHECK(result); is_ixfr = true; } else { axfr_fallback: CHECK(axfr_rrstream_create(mctx, db, ver, &data_stream)); } /* * Bracket the data stream with SOAs. */ CHECK(soa_rrstream_create(mctx, db, ver, &soa_stream)); CHECK(compound_rrstream_create(mctx, &soa_stream, &data_stream, &stream)); soa_stream = NULL; data_stream = NULL; have_stream: CHECK(dns_message_getquerytsig(request, mctx, &tsigbuf)); /* * Create the xfrout context object. This transfers the ownership * of "stream", "db", "ver", and "quota" to the xfrout context object. */ if (is_dlz) CHECK(xfrout_ctx_create(mctx, client, request->id, question_name, reqtype, question_class, zone, db, ver, quota, stream, dns_message_gettsigkey(request), tsigbuf, request->verified_sig, 3600, 3600, (format == dns_many_answers) ? true : false, &xfr)); else CHECK(xfrout_ctx_create(mctx, client, request->id, question_name, reqtype, question_class, zone, db, ver, quota, stream, dns_message_gettsigkey(request), tsigbuf, request->verified_sig, dns_zone_getmaxxfrout(zone), dns_zone_getidleout(zone), (format == dns_many_answers) ? true : false, &xfr)); xfr->mnemonic = mnemonic; stream = NULL; quota = NULL; CHECK(xfr->stream->methods->first(xfr->stream)); if (xfr->tsigkey != NULL) dns_name_format(&xfr->tsigkey->name, keyname, sizeof(keyname)); else keyname[0] = '\0'; if (is_poll) xfrout_log1(client, question_name, question_class, ISC_LOG_DEBUG(1), "IXFR poll up to date%s%s", (xfr->tsigkey != NULL) ? ": TSIG " : "", keyname); else if (is_ixfr) xfrout_log1(client, question_name, question_class, ISC_LOG_INFO, "%s started%s%s (serial %u -> %u)", mnemonic, (xfr->tsigkey != NULL) ? ": TSIG " : "", keyname, begin_serial, current_serial); else xfrout_log1(client, question_name, question_class, ISC_LOG_INFO, "%s started%s%s (serial %u)", mnemonic, (xfr->tsigkey != NULL) ? ": TSIG " : "", keyname, current_serial); if (zone != NULL) { dns_zone_getraw(zone, &raw); mayberaw = (raw != NULL) ? raw : zone; if ((client->attributes & NS_CLIENTATTR_WANTEXPIRE) != 0 && dns_zone_gettype(mayberaw) == dns_zone_slave) { isc_time_t expiretime; uint32_t secs; dns_zone_getexpiretime(zone, &expiretime); secs = isc_time_seconds(&expiretime); if (secs >= client->now && result == ISC_R_SUCCESS) { client->attributes |= NS_CLIENTATTR_HAVEEXPIRE; client->expire = secs - client->now; } } if (raw != NULL) dns_zone_detach(&raw); } /* * Hand the context over to sendstream(). Set xfr to NULL; * sendstream() is responsible for either passing the * context on to a later event handler or destroying it. */ sendstream(xfr); xfr = NULL; result = ISC_R_SUCCESS; failure: if (result == DNS_R_REFUSED) inc_stats(zone, dns_nsstatscounter_xfrrej); if (quota != NULL) isc_quota_detach(&quota); if (current_soa_tuple != NULL) dns_difftuple_free(&current_soa_tuple); if (stream != NULL) stream->methods->destroy(&stream); if (soa_stream != NULL) soa_stream->methods->destroy(&soa_stream); if (data_stream != NULL) data_stream->methods->destroy(&data_stream); if (ver != NULL) dns_db_closeversion(db, &ver, false); if (db != NULL) dns_db_detach(&db); if (zone != NULL) dns_zone_detach(&zone); /* XXX kludge */ if (xfr != NULL) { xfrout_fail(xfr, result, "setting up zone transfer"); } else if (result != ISC_R_SUCCESS) { ns_client_log(client, DNS_LOGCATEGORY_XFER_OUT, NS_LOGMODULE_XFER_OUT, ISC_LOG_DEBUG(3), "zone transfer setup failed"); ns_client_error(client, result); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-732'], 'message': 'denied axfr requests were not effective for writable DLZ zones (cherry picked from commit d9077cd0038e59726e1956de18b4b7872038a283)'</s>
<s>[INST] Given the following code containing errors, provide 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 VTermState *vterm_state_new(VTerm *vt) { VTermState *state = vterm_allocator_malloc(vt, sizeof(VTermState)); state->vt = vt; state->rows = vt->rows; state->cols = vt->cols; state->mouse_col = 0; state->mouse_row = 0; state->mouse_buttons = 0; state->mouse_protocol = MOUSE_X10; state->callbacks = NULL; state->cbdata = NULL; vterm_state_newpen(state); state->bold_is_highbright = 0; return state; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.1.0633: crash when out of memory while opening a terminal window Problem: Crash when out of memory while opening a terminal window. Solution: Handle out-of-memory more gracefully.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: VTerm *vterm_new_with_allocator(int rows, int cols, VTermAllocatorFunctions *funcs, void *allocdata) { /* Need to bootstrap using the allocator function directly */ VTerm *vt = (*funcs->malloc)(sizeof(VTerm), allocdata); vt->allocator = funcs; vt->allocdata = allocdata; vt->rows = rows; vt->cols = cols; vt->parser.state = NORMAL; vt->parser.callbacks = NULL; vt->parser.cbdata = NULL; vt->parser.strbuffer_len = 500; /* should be able to hold an OSC string */ vt->parser.strbuffer_cur = 0; vt->parser.strbuffer = vterm_allocator_malloc(vt, vt->parser.strbuffer_len); vt->outbuffer_len = 200; vt->outbuffer_cur = 0; vt->outbuffer = vterm_allocator_malloc(vt, vt->outbuffer_len); return vt; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.1.0633: crash when out of memory while opening a terminal window Problem: Crash when out of memory while opening a terminal window. Solution: Handle out-of-memory more gracefully.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool context_has_no_new_privileges(const ExecContext *c) { assert(c); if (c->no_new_privileges) return true; if (have_effective_cap(CAP_SYS_ADMIN)) /* if we are privileged, we don't need NNP */ return false; /* We need NNP if we have any form of seccomp and are unprivileged */ return context_has_address_families(c) || c->memory_deny_write_execute || c->restrict_realtime || exec_context_restrict_namespaces_set(c) || c->protect_kernel_tunables || c->protect_kernel_modules || c->private_devices || context_has_syscall_filters(c) || !set_isempty(c->syscall_archs) || c->lock_personality || c->protect_hostname; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269'], 'message': 'core: expose SUID/SGID restriction as new unit setting RestrictSUIDSGID='</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: compile_string_node(Node* node, regex_t* reg) { int r, len, prev_len, slen, ambig; OnigEncoding enc = reg->enc; UChar *p, *prev, *end; StrNode* sn; sn = NSTR(node); if (sn->end <= sn->s) return 0; end = sn->end; ambig = NSTRING_IS_AMBIG(node); p = prev = sn->s; prev_len = enclen(enc, p); p += prev_len; slen = 1; for (; p < end; ) { len = enclen(enc, p); if (len == prev_len) { slen++; } else { r = add_compile_string(prev, prev_len, slen, reg, ambig); if (r) return r; prev = p; slen = 1; prev_len = len; } p += len; } return add_compile_string(prev, prev_len, slen, reg, ambig); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #77371 (heap buffer overflow in mb regex functions - compile_string_node)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: jio_snprintf(char * str, int n, const char * format, ...) { va_list args; int result; Trc_SC_snprintf_Entry(); va_start(args, format); #if defined(WIN32) && !defined(WIN32_IBMC) result = _vsnprintf( str, n, format, args ); #else result = vsprintf( str, format, args ); #endif va_end(args); Trc_SC_snprintf_Exit(result); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Clean up jio_snprintf and jio_vfprintf Fixes https://bugs.eclipse.org/bugs/show_bug.cgi?id=543659 Signed-off-by: Peter Bain <peter_bain@ca.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static gboolean DecodeHeader(unsigned char *BFH, unsigned char *BIH, struct bmp_progressive_state *State, GError **error) { gint clrUsed; /* First check for the two first bytes content. A sane BMP file must start with bytes 0x42 0x4D. */ if (*BFH != 0x42 || *(BFH + 1) != 0x4D) { g_set_error_literal (error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE, _("BMP image has bogus header data")); State->read_state = READ_STATE_ERROR; return FALSE; } /* FIXME this is totally unrobust against bogus image data. */ if (State->BufferSize < lsb_32 (&BIH[0]) + 14) { State->BufferSize = lsb_32 (&BIH[0]) + 14; if (!grow_buffer (State, error)) return FALSE; return TRUE; } #if DUMPBIH DumpBIH(BIH); #endif State->Header.size = lsb_32 (&BIH[0]); if (State->Header.size == 124) { /* BMP v5 */ State->Header.width = lsb_32 (&BIH[4]); State->Header.height = lsb_32 (&BIH[8]); State->Header.depth = lsb_16 (&BIH[14]); State->Compressed = lsb_32 (&BIH[16]); } else if (State->Header.size == 108) { /* BMP v4 */ State->Header.width = lsb_32 (&BIH[4]); State->Header.height = lsb_32 (&BIH[8]); State->Header.depth = lsb_16 (&BIH[14]); State->Compressed = lsb_32 (&BIH[16]); } else if (State->Header.size == 64) { /* BMP OS/2 v2 */ State->Header.width = lsb_32 (&BIH[4]); State->Header.height = lsb_32 (&BIH[8]); State->Header.depth = lsb_16 (&BIH[14]); State->Compressed = lsb_32 (&BIH[16]); } else if (State->Header.size == 40) { /* BMP v3 */ State->Header.width = lsb_32 (&BIH[4]); State->Header.height = lsb_32 (&BIH[8]); State->Header.depth = lsb_16 (&BIH[14]); State->Compressed = lsb_32 (&BIH[16]); } else if (State->Header.size == 12) { /* BMP OS/2 */ State->Header.width = lsb_16 (&BIH[4]); State->Header.height = lsb_16 (&BIH[6]); State->Header.depth = lsb_16 (&BIH[10]); State->Compressed = BI_RGB; } else { g_set_error_literal (error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE, _("BMP image has unsupported header size")); State->read_state = READ_STATE_ERROR; return FALSE; } if (State->Header.depth > 32) { g_set_error_literal (error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE, _("BMP image has unsupported depth")); State->read_state = READ_STATE_ERROR; } if (State->Header.size == 12) clrUsed = 1 << State->Header.depth; else clrUsed = (int) (BIH[35] << 24) + (BIH[34] << 16) + (BIH[33] << 8) + (BIH[32]); if (clrUsed != 0) State->Header.n_colors = clrUsed; else State->Header.n_colors = (1 << State->Header.depth); State->Type = State->Header.depth; /* This may be less trivial someday */ /* Negative heights indicates bottom-down pixelorder */ if (State->Header.height < 0) { State->Header.height = -State->Header.height; State->Header.Negative = 1; } if (State->Header.Negative && (State->Compressed != BI_RGB && State->Compressed != BI_BITFIELDS)) { g_set_error_literal (error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE, _("Topdown BMP images cannot be compressed")); State->read_state = READ_STATE_ERROR; return FALSE; } if (State->Header.width <= 0 || State->Header.height == 0 || (State->Compressed == BI_RLE4 && State->Type != 4) || (State->Compressed == BI_RLE8 && State->Type != 8) || (State->Compressed == BI_BITFIELDS && !(State->Type == 16 || State->Type == 32)) || (State->Compressed > BI_BITFIELDS)) { g_set_error_literal (error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE, _("BMP image has bogus header data")); State->read_state = READ_STATE_ERROR; return FALSE; } if (State->Type == 32) State->LineWidth = State->Header.width * 4; else if (State->Type == 24) State->LineWidth = State->Header.width * 3; else if (State->Type == 16) State->LineWidth = State->Header.width * 2; else if (State->Type == 8) State->LineWidth = State->Header.width * 1; else if (State->Type == 4) State->LineWidth = (State->Header.width + 1) / 2; else if (State->Type == 1) { State->LineWidth = State->Header.width / 8; if ((State->Header.width & 7) != 0) State->LineWidth++; } else { g_set_error_literal (error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE, _("BMP image has bogus header data")); State->read_state = READ_STATE_ERROR; return FALSE; } /* Pad to a 32 bit boundary */ if (((State->LineWidth % 4) > 0) && (State->Compressed == BI_RGB || State->Compressed == BI_BITFIELDS)) State->LineWidth = (State->LineWidth / 4) * 4 + 4; if (State->pixbuf == NULL) { if (State->size_func) { gint width = State->Header.width; gint height = State->Header.height; (*State->size_func) (&width, &height, State->user_data); if (width == 0 || height == 0) { State->read_state = READ_STATE_DONE; State->BufferSize = 0; return TRUE; } } if (State->Type == 32 || State->Compressed == BI_RLE4 || State->Compressed == BI_RLE8) State->pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8, (gint) State->Header.width, (gint) State->Header.height); else State->pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, (gint) State->Header.width, (gint) State->Header.height); if (State->pixbuf == NULL) { g_set_error_literal (error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY, _("Not enough memory to load bitmap image")); State->read_state = READ_STATE_ERROR; return FALSE; } if (State->prepared_func != NULL) /* Notify the client that we are ready to go */ (*State->prepared_func) (State->pixbuf, NULL, State->user_data); /* make all pixels initially transparent */ if (State->Compressed == BI_RLE4 || State->Compressed == BI_RLE8) { memset (State->pixbuf->pixels, 0, State->pixbuf->rowstride * State->Header.height); State->compr.p = State->pixbuf->pixels + State->pixbuf->rowstride * (State->Header.height- 1); } } State->BufferDone = 0; if (State->Type <= 8) { gint samples; State->read_state = READ_STATE_PALETTE; /* Allocate enough to hold the palette */ samples = (State->Header.size == 12 ? 3 : 4); State->BufferSize = State->Header.n_colors * samples; /* Skip over everything between the palette and the data. This protects us against a malicious BFH[10] value. */ State->BufferPadding = (lsb_32 (&BFH[10]) - 14 - State->Header.size) - State->BufferSize; } else if (State->Compressed == BI_RGB) { if (State->BufferSize < lsb_32 (&BFH[10])) { /* skip over padding between headers and image data */ State->read_state = READ_STATE_HEADERS; State->BufferDone = State->BufferSize; State->BufferSize = lsb_32 (&BFH[10]); } else { State->read_state = READ_STATE_DATA; State->BufferSize = State->LineWidth; } } else if (State->Compressed == BI_BITFIELDS) { if (State->Header.size == 108 || State->Header.size == 124) { /* v4 and v5 have the bitmasks in the header */ if (!decode_bitmasks (&BIH[40], State, error)) { State->read_state = READ_STATE_ERROR; return FALSE; } } else { State->read_state = READ_STATE_BITMASKS; State->BufferSize = 12; } } else { g_set_error_literal (error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE, _("BMP image has bogus header data")); State->read_state = READ_STATE_ERROR; return FALSE; } if (!grow_buffer (State, error)) return FALSE; return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'bmp: Reject impossible palette size bmp headers contain separate fields for the number of colors, and the bit depth. Catch the impossible n_colors > 1 << depth and error early, before it causes a out-of-bounds memory access when decoding the colormap. https://bugzilla.gnome.org/show_bug.cgi?id=758991'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: * Elliptic Curve Key Exchange */ static int curve25519_sha256(LIBSSH2_SESSION *session, unsigned char *data, size_t data_len, unsigned char public_key[LIBSSH2_ED25519_KEY_LEN], unsigned char private_key[LIBSSH2_ED25519_KEY_LEN], kmdhgGPshakex_state_t *exchange_state) { int ret = 0; int rc; int public_key_len = LIBSSH2_ED25519_KEY_LEN; if(data_len < 5) { return _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_INIT, "Data is too short"); } if(exchange_state->state == libssh2_NB_state_idle) { /* Setup initial values */ exchange_state->k = _libssh2_bn_init(); exchange_state->state = libssh2_NB_state_created; } if( exchange_state->state == libssh2_NB_state_created) { /* parse INIT reply data */ /*host key K_S*/ unsigned char *s = data + 1; //advance past packet type unsigned char *server_public_key; size_t server_public_key_len; size_t host_sig_len; session->server_hostkey_len = _libssh2_ntohu32((const unsigned char*)s); s += 4; session->server_hostkey = LIBSSH2_ALLOC(session, session->server_hostkey_len); if(!session->server_hostkey) { ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate memory for a copy " "of the host key"); goto clean_exit; } memcpy(session->server_hostkey, s, session->server_hostkey_len); s += session->server_hostkey_len; #if LIBSSH2_MD5 { libssh2_md5_ctx fingerprint_ctx; if(libssh2_md5_init(&fingerprint_ctx)) { libssh2_md5_update(fingerprint_ctx, session->server_hostkey, session->server_hostkey_len); libssh2_md5_final(fingerprint_ctx, session->server_hostkey_md5); session->server_hostkey_md5_valid = TRUE; } else { session->server_hostkey_md5_valid = FALSE; } } #ifdef LIBSSH2DEBUG { char fingerprint[50], *fprint = fingerprint; int i; for(i = 0; i < 16; i++, fprint += 3) { snprintf(fprint, 4, "%02x:", session->server_hostkey_md5[i]); } *(--fprint) = '\0'; _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Server's MD5 Fingerprint: %s", fingerprint); } #endif /* LIBSSH2DEBUG */ #endif /* ! LIBSSH2_MD5 */ { libssh2_sha1_ctx fingerprint_ctx; if(libssh2_sha1_init(&fingerprint_ctx)) { libssh2_sha1_update(fingerprint_ctx, session->server_hostkey, session->server_hostkey_len); libssh2_sha1_final(fingerprint_ctx, session->server_hostkey_sha1); session->server_hostkey_sha1_valid = TRUE; } else { session->server_hostkey_sha1_valid = FALSE; } } #ifdef LIBSSH2DEBUG { char fingerprint[64], *fprint = fingerprint; int i; for(i = 0; i < 20; i++, fprint += 3) { snprintf(fprint, 4, "%02x:", session->server_hostkey_sha1[i]); } *(--fprint) = '\0'; _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Server's SHA1 Fingerprint: %s", fingerprint); } #endif /* LIBSSH2DEBUG */ /* SHA256 */ { libssh2_sha256_ctx fingerprint_ctx; if(libssh2_sha256_init(&fingerprint_ctx)) { libssh2_sha256_update(fingerprint_ctx, session->server_hostkey, session->server_hostkey_len); libssh2_sha256_final(fingerprint_ctx, session->server_hostkey_sha256); session->server_hostkey_sha256_valid = TRUE; } else { session->server_hostkey_sha256_valid = FALSE; } } #ifdef LIBSSH2DEBUG { char *base64Fingerprint = NULL; _libssh2_base64_encode(session, (const char*)session->server_hostkey_sha256, SHA256_DIGEST_LENGTH, &base64Fingerprint); if( base64Fingerprint != NULL) { _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Server's SHA256 Fingerprint: %s", base64Fingerprint); LIBSSH2_FREE(session, base64Fingerprint); } } #endif /* LIBSSH2DEBUG */ if(session->hostkey->init(session, session->server_hostkey, session->server_hostkey_len, &session->server_hostkey_abstract)) { ret = _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_INIT, "Unable to initialize hostkey importer"); goto clean_exit; } /* server public key Q_S */ server_public_key_len = _libssh2_ntohu32((const unsigned char*)s); s += 4; if( server_public_key_len != LIBSSH2_ED25519_KEY_LEN) { ret = _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_INIT, "Unexpected curve25519 server public key length"); goto clean_exit; } server_public_key = s; s += server_public_key_len; /* server signature */ host_sig_len = _libssh2_ntohu32((const unsigned char*)s); s += 4; exchange_state->h_sig = s; exchange_state->h_sig_len = host_sig_len; s += host_sig_len; // Compute the shared secret K rc = _libssh2_curve25519_gen_k(&exchange_state->k, private_key, server_public_key); if( rc != 0) { ret = _libssh2_error(session, LIBSSH2_ERROR_KEX_FAILURE, "Unable to create ECDH shared secret"); goto clean_exit; } exchange_state->k_value_len = _libssh2_bn_bytes(exchange_state->k) + 5; if(_libssh2_bn_bits(exchange_state->k) % 8) { // don't need leading 00 exchange_state->k_value_len--; } exchange_state->k_value = LIBSSH2_ALLOC(session, exchange_state->k_value_len); if(!exchange_state->k_value) { ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate buffer for K"); goto clean_exit; } _libssh2_htonu32(exchange_state->k_value, exchange_state->k_value_len - 4); if(_libssh2_bn_bits(exchange_state->k) % 8) { _libssh2_bn_to_bin(exchange_state->k, exchange_state->k_value + 4); } else { exchange_state->k_value[4] = 0; _libssh2_bn_to_bin(exchange_state->k, exchange_state->k_value + 5); } // verify hash LIBSSH2_KEX_METHOD_EC_SHA_HASH_CREATE_VERIFY(256); if( rc != 0) { ret = _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_SIGN, "Unable to verify hostkey signature"); goto clean_exit; } exchange_state->c = SSH_MSG_NEWKEYS; exchange_state->state = libssh2_NB_state_sent; } if(exchange_state->state == libssh2_NB_state_sent) { rc = _libssh2_transport_send(session, &exchange_state->c, 1, NULL, 0); if(rc == LIBSSH2_ERROR_EAGAIN) { return rc; } else if(rc) { ret = _libssh2_error(session, rc, "Unable to send NEWKEYS message"); goto clean_exit; } exchange_state->state = libssh2_NB_state_sent2; } if(exchange_state->state == libssh2_NB_state_sent2) { rc = _libssh2_packet_require(session, SSH_MSG_NEWKEYS, &exchange_state->tmp, &exchange_state->tmp_len, 0, NULL, 0, &exchange_state->req_state); if(rc == LIBSSH2_ERROR_EAGAIN) { return rc; } else if(rc) { ret = _libssh2_error(session, rc, "Timed out waiting for NEWKEYS"); goto clean_exit; } // The first key exchange has been performed, switch to active crypt/comp/mac mode session->state |= LIBSSH2_STATE_NEWKEYS; _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Received NEWKEYS message"); // This will actually end up being just packet_type(1) for this packet type anyway LIBSSH2_FREE(session, exchange_state->tmp); if(!session->session_id) { size_t digest_length = SHA256_DIGEST_LENGTH; session->session_id = LIBSSH2_ALLOC(session, digest_length); if(!session->session_id) { ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate buffer for SHA digest"); goto clean_exit; } memcpy(session->session_id, exchange_state->h_sig_comp, digest_length); session->session_id_len = digest_length; _libssh2_debug(session, LIBSSH2_TRACE_KEX, "session_id calculated"); } // Cleanup any existing cipher if(session->local.crypt->dtor) { session->local.crypt->dtor(session, &session->local.crypt_abstract); } // Calculate IV/Secret/Key for each direction if(session->local.crypt->init) { unsigned char *iv = NULL, *secret = NULL; int free_iv = 0, free_secret = 0; LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, iv, session->local.crypt-> iv_len, "A"); if(!iv) { ret = -1; goto clean_exit; } LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, secret, session->local.crypt-> secret_len, "C"); if(!secret) { LIBSSH2_FREE(session, iv); ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } if(session->local.crypt-> init(session, session->local.crypt, iv, &free_iv, secret, &free_secret, 1, &session->local.crypt_abstract)) { LIBSSH2_FREE(session, iv); LIBSSH2_FREE(session, secret); ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } if(free_iv) { _libssh2_explicit_zero(iv, session->local.crypt->iv_len); LIBSSH2_FREE(session, iv); } if(free_secret) { _libssh2_explicit_zero(secret, session->local.crypt->secret_len); LIBSSH2_FREE(session, secret); } } _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Client to Server IV and Key calculated"); if(session->remote.crypt->dtor) { // Cleanup any existing cipher session->remote.crypt->dtor(session, &session->remote.crypt_abstract); } if(session->remote.crypt->init) { unsigned char *iv = NULL, *secret = NULL; int free_iv = 0, free_secret = 0; LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, iv, session->remote.crypt-> iv_len, "B"); if(!iv) { ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, secret, session->remote.crypt-> secret_len, "D"); if(!secret) { LIBSSH2_FREE(session, iv); ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } if(session->remote.crypt-> init(session, session->remote.crypt, iv, &free_iv, secret, &free_secret, 0, &session->remote.crypt_abstract)) { LIBSSH2_FREE(session, iv); LIBSSH2_FREE(session, secret); ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } if(free_iv) { _libssh2_explicit_zero(iv, session->remote.crypt->iv_len); LIBSSH2_FREE(session, iv); } if(free_secret) { _libssh2_explicit_zero(secret, session->remote.crypt->secret_len); LIBSSH2_FREE(session, secret); } } _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Server to Client IV and Key calculated"); if(session->local.mac->dtor) { session->local.mac->dtor(session, &session->local.mac_abstract); } if(session->local.mac->init) { unsigned char *key = NULL; int free_key = 0; LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, key, session->local.mac-> key_len, "E"); if(!key) { ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } session->local.mac->init(session, key, &free_key, &session->local.mac_abstract); if(free_key) { _libssh2_explicit_zero(key, session->local.mac->key_len); LIBSSH2_FREE(session, key); } } _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Client to Server HMAC Key calculated"); if(session->remote.mac->dtor) { session->remote.mac->dtor(session, &session->remote.mac_abstract); } if(session->remote.mac->init) { unsigned char *key = NULL; int free_key = 0; LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, key, session->remote.mac-> key_len, "F"); if(!key) { ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } session->remote.mac->init(session, key, &free_key, &session->remote.mac_abstract); if(free_key) { _libssh2_explicit_zero(key, session->remote.mac->key_len); LIBSSH2_FREE(session, key); } } _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Server to Client HMAC Key calculated"); // Initialize compression for each direction // Cleanup any existing compression if(session->local.comp && session->local.comp->dtor) { session->local.comp->dtor(session, 1, &session->local.comp_abstract); } if(session->local.comp && session->local.comp->init) { if(session->local.comp->init(session, 1, &session->local.comp_abstract)) { ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } } _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Client to Server compression initialized"); if(session->remote.comp && session->remote.comp->dtor) { session->remote.comp->dtor(session, 0, &session->remote.comp_abstract); } if(session->remote.comp && session->remote.comp->init) { if(session->remote.comp->init(session, 0, &session->remote.comp_abstract)) { ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } } _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Server to Client compression initialized"); } clean_exit: _libssh2_bn_free(exchange_state->k); exchange_state->k = NULL; if(exchange_state->k_value) { LIBSSH2_FREE(session, exchange_state->k_value); exchange_state->k_value = NULL; } exchange_state->state = libssh2_NB_state_idle; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315) * Bounds checks Fixes for CVEs https://www.libssh2.org/CVE-2019-3863.html https://www.libssh2.org/CVE-2019-3856.html * Packet length bounds check CVE https://www.libssh2.org/CVE-2019-3855.html * Response length check CVE https://www.libssh2.org/CVE-2019-3859.html * Bounds check CVE https://www.libssh2.org/CVE-2019-3857.html * Bounds checking CVE https://www.libssh2.org/CVE-2019-3859.html and additional data validation * Check bounds before reading into buffers * Bounds checking CVE https://www.libssh2.org/CVE-2019-3859.html * declare SIZE_MAX and UINT_MAX if needed'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _libssh2_channel_packet_data_len(LIBSSH2_CHANNEL * channel, int stream_id) { LIBSSH2_SESSION *session = channel->session; LIBSSH2_PACKET *read_packet; uint32_t read_local_id; read_packet = _libssh2_list_first(&session->packets); if(read_packet == NULL) return 0; while(read_packet) { read_local_id = _libssh2_ntohu32(read_packet->data + 1); /* * Either we asked for a specific extended data stream * (and data was available), * or the standard stream (and data was available), * or the standard stream with extended_data_merge * enabled and data was available */ if((stream_id && (read_packet->data[0] == SSH_MSG_CHANNEL_EXTENDED_DATA) && (channel->local.id == read_local_id) && (stream_id == (int) _libssh2_ntohu32(read_packet->data + 5))) || (!stream_id && (read_packet->data[0] == SSH_MSG_CHANNEL_DATA) && (channel->local.id == read_local_id)) || (!stream_id && (read_packet->data[0] == SSH_MSG_CHANNEL_EXTENDED_DATA) && (channel->local.id == read_local_id) && (channel->remote.extended_data_ignore_mode == LIBSSH2_CHANNEL_EXTENDED_DATA_MERGE))) { return (read_packet->data_len - read_packet->data_head); } read_packet = _libssh2_list_next(&read_packet->node); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315) * Bounds checks Fixes for CVEs https://www.libssh2.org/CVE-2019-3863.html https://www.libssh2.org/CVE-2019-3856.html * Packet length bounds check CVE https://www.libssh2.org/CVE-2019-3855.html * Response length check CVE https://www.libssh2.org/CVE-2019-3859.html * Bounds check CVE https://www.libssh2.org/CVE-2019-3857.html * Bounds checking CVE https://www.libssh2.org/CVE-2019-3859.html and additional data validation * Check bounds before reading into buffers * Bounds checking CVE https://www.libssh2.org/CVE-2019-3859.html * declare SIZE_MAX and UINT_MAX if needed'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: * Diffie Hellman Key Exchange, Group Agnostic */ static int diffie_hellman_sha1(LIBSSH2_SESSION *session, _libssh2_bn *g, _libssh2_bn *p, int group_order, unsigned char packet_type_init, unsigned char packet_type_reply, unsigned char *midhash, unsigned long midhash_len, kmdhgGPshakex_state_t *exchange_state) { int ret = 0; int rc; libssh2_sha1_ctx exchange_hash_ctx; if(exchange_state->state == libssh2_NB_state_idle) { /* Setup initial values */ exchange_state->e_packet = NULL; exchange_state->s_packet = NULL; exchange_state->k_value = NULL; exchange_state->ctx = _libssh2_bn_ctx_new(); libssh2_dh_init(&exchange_state->x); exchange_state->e = _libssh2_bn_init(); /* g^x mod p */ exchange_state->f = _libssh2_bn_init_from_bin(); /* g^(Random from server) mod p */ exchange_state->k = _libssh2_bn_init(); /* The shared secret: f^x mod p */ /* Zero the whole thing out */ memset(&exchange_state->req_state, 0, sizeof(packet_require_state_t)); /* Generate x and e */ rc = libssh2_dh_key_pair(&exchange_state->x, exchange_state->e, g, p, group_order, exchange_state->ctx); if(rc) goto clean_exit; /* Send KEX init */ /* packet_type(1) + String Length(4) + leading 0(1) */ exchange_state->e_packet_len = _libssh2_bn_bytes(exchange_state->e) + 6; if(_libssh2_bn_bits(exchange_state->e) % 8) { /* Leading 00 not needed */ exchange_state->e_packet_len--; } exchange_state->e_packet = LIBSSH2_ALLOC(session, exchange_state->e_packet_len); if(!exchange_state->e_packet) { ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Out of memory error"); goto clean_exit; } exchange_state->e_packet[0] = packet_type_init; _libssh2_htonu32(exchange_state->e_packet + 1, exchange_state->e_packet_len - 5); if(_libssh2_bn_bits(exchange_state->e) % 8) { _libssh2_bn_to_bin(exchange_state->e, exchange_state->e_packet + 5); } else { exchange_state->e_packet[5] = 0; _libssh2_bn_to_bin(exchange_state->e, exchange_state->e_packet + 6); } _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Sending KEX packet %d", (int) packet_type_init); exchange_state->state = libssh2_NB_state_created; } if(exchange_state->state == libssh2_NB_state_created) { rc = _libssh2_transport_send(session, exchange_state->e_packet, exchange_state->e_packet_len, NULL, 0); if(rc == LIBSSH2_ERROR_EAGAIN) { return rc; } else if(rc) { ret = _libssh2_error(session, rc, "Unable to send KEX init message"); goto clean_exit; } exchange_state->state = libssh2_NB_state_sent; } if(exchange_state->state == libssh2_NB_state_sent) { if(session->burn_optimistic_kexinit) { /* The first KEX packet to come along will be the guess initially * sent by the server. That guess turned out to be wrong so we * need to silently ignore it */ int burn_type; _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Waiting for badly guessed KEX packet (to be ignored)"); burn_type = _libssh2_packet_burn(session, &exchange_state->burn_state); if(burn_type == LIBSSH2_ERROR_EAGAIN) { return burn_type; } else if(burn_type <= 0) { /* Failed to receive a packet */ ret = burn_type; goto clean_exit; } session->burn_optimistic_kexinit = 0; _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Burnt packet of type: %02x", (unsigned int) burn_type); } exchange_state->state = libssh2_NB_state_sent1; } if(exchange_state->state == libssh2_NB_state_sent1) { /* Wait for KEX reply */ rc = _libssh2_packet_require(session, packet_type_reply, &exchange_state->s_packet, &exchange_state->s_packet_len, 0, NULL, 0, &exchange_state->req_state); if(rc == LIBSSH2_ERROR_EAGAIN) { return rc; } if(rc) { ret = _libssh2_error(session, LIBSSH2_ERROR_TIMEOUT, "Timed out waiting for KEX reply"); goto clean_exit; } /* Parse KEXDH_REPLY */ exchange_state->s = exchange_state->s_packet + 1; session->server_hostkey_len = _libssh2_ntohu32(exchange_state->s); exchange_state->s += 4; if(session->server_hostkey) LIBSSH2_FREE(session, session->server_hostkey); session->server_hostkey = LIBSSH2_ALLOC(session, session->server_hostkey_len); if(!session->server_hostkey) { ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate memory for a copy " "of the host key"); goto clean_exit; } memcpy(session->server_hostkey, exchange_state->s, session->server_hostkey_len); exchange_state->s += session->server_hostkey_len; #if LIBSSH2_MD5 { libssh2_md5_ctx fingerprint_ctx; if(libssh2_md5_init(&fingerprint_ctx)) { libssh2_md5_update(fingerprint_ctx, session->server_hostkey, session->server_hostkey_len); libssh2_md5_final(fingerprint_ctx, session->server_hostkey_md5); session->server_hostkey_md5_valid = TRUE; } else { session->server_hostkey_md5_valid = FALSE; } } #ifdef LIBSSH2DEBUG { char fingerprint[50], *fprint = fingerprint; int i; for(i = 0; i < 16; i++, fprint += 3) { snprintf(fprint, 4, "%02x:", session->server_hostkey_md5[i]); } *(--fprint) = '\0'; _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Server's MD5 Fingerprint: %s", fingerprint); } #endif /* LIBSSH2DEBUG */ #endif /* ! LIBSSH2_MD5 */ { libssh2_sha1_ctx fingerprint_ctx; if(libssh2_sha1_init(&fingerprint_ctx)) { libssh2_sha1_update(fingerprint_ctx, session->server_hostkey, session->server_hostkey_len); libssh2_sha1_final(fingerprint_ctx, session->server_hostkey_sha1); session->server_hostkey_sha1_valid = TRUE; } else { session->server_hostkey_sha1_valid = FALSE; } } #ifdef LIBSSH2DEBUG { char fingerprint[64], *fprint = fingerprint; int i; for(i = 0; i < 20; i++, fprint += 3) { snprintf(fprint, 4, "%02x:", session->server_hostkey_sha1[i]); } *(--fprint) = '\0'; _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Server's SHA1 Fingerprint: %s", fingerprint); } #endif /* LIBSSH2DEBUG */ { libssh2_sha256_ctx fingerprint_ctx; if(libssh2_sha256_init(&fingerprint_ctx)) { libssh2_sha256_update(fingerprint_ctx, session->server_hostkey, session->server_hostkey_len); libssh2_sha256_final(fingerprint_ctx, session->server_hostkey_sha256); session->server_hostkey_sha256_valid = TRUE; } else { session->server_hostkey_sha256_valid = FALSE; } } #ifdef LIBSSH2DEBUG { char *base64Fingerprint = NULL; _libssh2_base64_encode(session, (const char *)session->server_hostkey_sha256, SHA256_DIGEST_LENGTH, &base64Fingerprint); if(base64Fingerprint != NULL) { _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Server's SHA256 Fingerprint: %s", base64Fingerprint); LIBSSH2_FREE(session, base64Fingerprint); } } #endif /* LIBSSH2DEBUG */ if(session->hostkey->init(session, session->server_hostkey, session->server_hostkey_len, &session->server_hostkey_abstract)) { ret = _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_INIT, "Unable to initialize hostkey importer"); goto clean_exit; } exchange_state->f_value_len = _libssh2_ntohu32(exchange_state->s); exchange_state->s += 4; exchange_state->f_value = exchange_state->s; exchange_state->s += exchange_state->f_value_len; _libssh2_bn_from_bin(exchange_state->f, exchange_state->f_value_len, exchange_state->f_value); exchange_state->h_sig_len = _libssh2_ntohu32(exchange_state->s); exchange_state->s += 4; exchange_state->h_sig = exchange_state->s; /* Compute the shared secret */ libssh2_dh_secret(&exchange_state->x, exchange_state->k, exchange_state->f, p, exchange_state->ctx); exchange_state->k_value_len = _libssh2_bn_bytes(exchange_state->k) + 5; if(_libssh2_bn_bits(exchange_state->k) % 8) { /* don't need leading 00 */ exchange_state->k_value_len--; } exchange_state->k_value = LIBSSH2_ALLOC(session, exchange_state->k_value_len); if(!exchange_state->k_value) { ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate buffer for K"); goto clean_exit; } _libssh2_htonu32(exchange_state->k_value, exchange_state->k_value_len - 4); if(_libssh2_bn_bits(exchange_state->k) % 8) { _libssh2_bn_to_bin(exchange_state->k, exchange_state->k_value + 4); } else { exchange_state->k_value[4] = 0; _libssh2_bn_to_bin(exchange_state->k, exchange_state->k_value + 5); } exchange_state->exchange_hash = (void *)&exchange_hash_ctx; libssh2_sha1_init(&exchange_hash_ctx); if(session->local.banner) { _libssh2_htonu32(exchange_state->h_sig_comp, strlen((char *) session->local.banner) - 2); libssh2_sha1_update(exchange_hash_ctx, exchange_state->h_sig_comp, 4); libssh2_sha1_update(exchange_hash_ctx, session->local.banner, strlen((char *) session->local.banner) - 2); } else { _libssh2_htonu32(exchange_state->h_sig_comp, sizeof(LIBSSH2_SSH_DEFAULT_BANNER) - 1); libssh2_sha1_update(exchange_hash_ctx, exchange_state->h_sig_comp, 4); libssh2_sha1_update(exchange_hash_ctx, (const unsigned char *)LIBSSH2_SSH_DEFAULT_BANNER, sizeof(LIBSSH2_SSH_DEFAULT_BANNER) - 1); } _libssh2_htonu32(exchange_state->h_sig_comp, strlen((char *) session->remote.banner)); libssh2_sha1_update(exchange_hash_ctx, exchange_state->h_sig_comp, 4); libssh2_sha1_update(exchange_hash_ctx, session->remote.banner, strlen((char *) session->remote.banner)); _libssh2_htonu32(exchange_state->h_sig_comp, session->local.kexinit_len); libssh2_sha1_update(exchange_hash_ctx, exchange_state->h_sig_comp, 4); libssh2_sha1_update(exchange_hash_ctx, session->local.kexinit, session->local.kexinit_len); _libssh2_htonu32(exchange_state->h_sig_comp, session->remote.kexinit_len); libssh2_sha1_update(exchange_hash_ctx, exchange_state->h_sig_comp, 4); libssh2_sha1_update(exchange_hash_ctx, session->remote.kexinit, session->remote.kexinit_len); _libssh2_htonu32(exchange_state->h_sig_comp, session->server_hostkey_len); libssh2_sha1_update(exchange_hash_ctx, exchange_state->h_sig_comp, 4); libssh2_sha1_update(exchange_hash_ctx, session->server_hostkey, session->server_hostkey_len); if(packet_type_init == SSH_MSG_KEX_DH_GEX_INIT) { /* diffie-hellman-group-exchange hashes additional fields */ #ifdef LIBSSH2_DH_GEX_NEW _libssh2_htonu32(exchange_state->h_sig_comp, LIBSSH2_DH_GEX_MINGROUP); _libssh2_htonu32(exchange_state->h_sig_comp + 4, LIBSSH2_DH_GEX_OPTGROUP); _libssh2_htonu32(exchange_state->h_sig_comp + 8, LIBSSH2_DH_GEX_MAXGROUP); libssh2_sha1_update(exchange_hash_ctx, exchange_state->h_sig_comp, 12); #else _libssh2_htonu32(exchange_state->h_sig_comp, LIBSSH2_DH_GEX_OPTGROUP); libssh2_sha1_update(exchange_hash_ctx, exchange_state->h_sig_comp, 4); #endif } if(midhash) { libssh2_sha1_update(exchange_hash_ctx, midhash, midhash_len); } libssh2_sha1_update(exchange_hash_ctx, exchange_state->e_packet + 1, exchange_state->e_packet_len - 1); _libssh2_htonu32(exchange_state->h_sig_comp, exchange_state->f_value_len); libssh2_sha1_update(exchange_hash_ctx, exchange_state->h_sig_comp, 4); libssh2_sha1_update(exchange_hash_ctx, exchange_state->f_value, exchange_state->f_value_len); libssh2_sha1_update(exchange_hash_ctx, exchange_state->k_value, exchange_state->k_value_len); libssh2_sha1_final(exchange_hash_ctx, exchange_state->h_sig_comp); if(session->hostkey-> sig_verify(session, exchange_state->h_sig, exchange_state->h_sig_len, exchange_state->h_sig_comp, 20, &session->server_hostkey_abstract)) { ret = _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_SIGN, "Unable to verify hostkey signature"); goto clean_exit; } _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Sending NEWKEYS message"); exchange_state->c = SSH_MSG_NEWKEYS; exchange_state->state = libssh2_NB_state_sent2; } if(exchange_state->state == libssh2_NB_state_sent2) { rc = _libssh2_transport_send(session, &exchange_state->c, 1, NULL, 0); if(rc == LIBSSH2_ERROR_EAGAIN) { return rc; } else if(rc) { ret = _libssh2_error(session, rc, "Unable to send NEWKEYS message"); goto clean_exit; } exchange_state->state = libssh2_NB_state_sent3; } if(exchange_state->state == libssh2_NB_state_sent3) { rc = _libssh2_packet_require(session, SSH_MSG_NEWKEYS, &exchange_state->tmp, &exchange_state->tmp_len, 0, NULL, 0, &exchange_state->req_state); if(rc == LIBSSH2_ERROR_EAGAIN) { return rc; } else if(rc) { ret = _libssh2_error(session, rc, "Timed out waiting for NEWKEYS"); goto clean_exit; } /* The first key exchange has been performed, switch to active crypt/comp/mac mode */ session->state |= LIBSSH2_STATE_NEWKEYS; _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Received NEWKEYS message"); /* This will actually end up being just packet_type(1) for this packet type anyway */ LIBSSH2_FREE(session, exchange_state->tmp); if(!session->session_id) { session->session_id = LIBSSH2_ALLOC(session, SHA_DIGEST_LENGTH); if(!session->session_id) { ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate buffer for SHA digest"); goto clean_exit; } memcpy(session->session_id, exchange_state->h_sig_comp, SHA_DIGEST_LENGTH); session->session_id_len = SHA_DIGEST_LENGTH; _libssh2_debug(session, LIBSSH2_TRACE_KEX, "session_id calculated"); } /* Cleanup any existing cipher */ if(session->local.crypt->dtor) { session->local.crypt->dtor(session, &session->local.crypt_abstract); } /* Calculate IV/Secret/Key for each direction */ if(session->local.crypt->init) { unsigned char *iv = NULL, *secret = NULL; int free_iv = 0, free_secret = 0; LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(iv, session->local.crypt-> iv_len, (const unsigned char *)"A"); if(!iv) { ret = -1; goto clean_exit; } LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(secret, session->local.crypt-> secret_len, (const unsigned char *)"C"); if(!secret) { LIBSSH2_FREE(session, iv); ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } if(session->local.crypt-> init(session, session->local.crypt, iv, &free_iv, secret, &free_secret, 1, &session->local.crypt_abstract)) { LIBSSH2_FREE(session, iv); LIBSSH2_FREE(session, secret); ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } if(free_iv) { _libssh2_explicit_zero(iv, session->local.crypt->iv_len); LIBSSH2_FREE(session, iv); } if(free_secret) { _libssh2_explicit_zero(secret, session->local.crypt->secret_len); LIBSSH2_FREE(session, secret); } } _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Client to Server IV and Key calculated"); if(session->remote.crypt->dtor) { /* Cleanup any existing cipher */ session->remote.crypt->dtor(session, &session->remote.crypt_abstract); } if(session->remote.crypt->init) { unsigned char *iv = NULL, *secret = NULL; int free_iv = 0, free_secret = 0; LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(iv, session->remote.crypt-> iv_len, (const unsigned char *)"B"); if(!iv) { ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(secret, session->remote.crypt-> secret_len, (const unsigned char *)"D"); if(!secret) { LIBSSH2_FREE(session, iv); ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } if(session->remote.crypt-> init(session, session->remote.crypt, iv, &free_iv, secret, &free_secret, 0, &session->remote.crypt_abstract)) { LIBSSH2_FREE(session, iv); LIBSSH2_FREE(session, secret); ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } if(free_iv) { _libssh2_explicit_zero(iv, session->remote.crypt->iv_len); LIBSSH2_FREE(session, iv); } if(free_secret) { _libssh2_explicit_zero(secret, session->remote.crypt->secret_len); LIBSSH2_FREE(session, secret); } } _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Server to Client IV and Key calculated"); if(session->local.mac->dtor) { session->local.mac->dtor(session, &session->local.mac_abstract); } if(session->local.mac->init) { unsigned char *key = NULL; int free_key = 0; LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(key, session->local.mac-> key_len, (const unsigned char *)"E"); if(!key) { ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } session->local.mac->init(session, key, &free_key, &session->local.mac_abstract); if(free_key) { _libssh2_explicit_zero(key, session->local.mac->key_len); LIBSSH2_FREE(session, key); } } _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Client to Server HMAC Key calculated"); if(session->remote.mac->dtor) { session->remote.mac->dtor(session, &session->remote.mac_abstract); } if(session->remote.mac->init) { unsigned char *key = NULL; int free_key = 0; LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(key, session->remote.mac-> key_len, (const unsigned char *)"F"); if(!key) { ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } session->remote.mac->init(session, key, &free_key, &session->remote.mac_abstract); if(free_key) { _libssh2_explicit_zero(key, session->remote.mac->key_len); LIBSSH2_FREE(session, key); } } _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Server to Client HMAC Key calculated"); /* Initialize compression for each direction */ /* Cleanup any existing compression */ if(session->local.comp && session->local.comp->dtor) { session->local.comp->dtor(session, 1, &session->local.comp_abstract); } if(session->local.comp && session->local.comp->init) { if(session->local.comp->init(session, 1, &session->local.comp_abstract)) { ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } } _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Client to Server compression initialized"); if(session->remote.comp && session->remote.comp->dtor) { session->remote.comp->dtor(session, 0, &session->remote.comp_abstract); } if(session->remote.comp && session->remote.comp->init) { if(session->remote.comp->init(session, 0, &session->remote.comp_abstract)) { ret = LIBSSH2_ERROR_KEX_FAILURE; goto clean_exit; } } _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Server to Client compression initialized"); } clean_exit: libssh2_dh_dtor(&exchange_state->x); _libssh2_bn_free(exchange_state->e); exchange_state->e = NULL; _libssh2_bn_free(exchange_state->f); exchange_state->f = NULL; _libssh2_bn_free(exchange_state->k); exchange_state->k = NULL; _libssh2_bn_ctx_free(exchange_state->ctx); exchange_state->ctx = NULL; if(exchange_state->e_packet) { LIBSSH2_FREE(session, exchange_state->e_packet); exchange_state->e_packet = NULL; } if(exchange_state->s_packet) { LIBSSH2_FREE(session, exchange_state->s_packet); exchange_state->s_packet = NULL; } if(exchange_state->k_value) { LIBSSH2_FREE(session, exchange_state->k_value); exchange_state->k_value = NULL; } exchange_state->state = libssh2_NB_state_idle; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315) * Bounds checks Fixes for CVEs https://www.libssh2.org/CVE-2019-3863.html https://www.libssh2.org/CVE-2019-3856.html * Packet length bounds check CVE https://www.libssh2.org/CVE-2019-3855.html * Response length check CVE https://www.libssh2.org/CVE-2019-3859.html * Bounds check CVE https://www.libssh2.org/CVE-2019-3857.html * Bounds checking CVE https://www.libssh2.org/CVE-2019-3859.html and additional data validation * Check bounds before reading into buffers * Bounds checking CVE https://www.libssh2.org/CVE-2019-3859.html * declare SIZE_MAX and UINT_MAX if needed'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: entry *load_entry(FILE * file, void (*error_func) (), struct passwd *pw, char **envp) { /* this function reads one crontab entry -- the next -- from a file. * it skips any leading blank lines, ignores comments, and returns * NULL if for any reason the entry can't be read and parsed. * * the entry is also parsed here. * * syntax: * user crontab: * minutes hours doms months dows cmd\n * system crontab (/etc/crontab): * minutes hours doms months dows USERNAME cmd\n */ ecode_e ecode = e_none; entry *e; int ch; char cmd[MAX_COMMAND]; char envstr[MAX_ENVSTR]; char **tenvp; char *p; struct passwd temppw; Debug(DPARS, ("load_entry()...about to eat comments\n")); skip_comments(file); ch = get_char(file); if (ch == EOF) return (NULL); /* ch is now the first useful character of a useful line. * it may be an @special or it may be the first character * of a list of minutes. */ e = (entry *) calloc(sizeof (entry), sizeof (char)); /* check for '-' as a first character, this option will disable * writing a syslog message about command getting executed */ if (ch == '-') { /* if we are editing system crontab or user uid is 0 (root) * we are allowed to disable logging */ if (pw == NULL || pw->pw_uid == 0) e->flags |= DONT_LOG; else { log_it("CRON", getpid(), "ERROR", "Only privileged user can disable logging", 0); ecode = e_option; goto eof; } ch = get_char(file); if (ch == EOF) { free(e); return NULL; } } if (ch == '@') { /* all of these should be flagged and load-limited; i.e., * instead of @hourly meaning "0 * * * *" it should mean * "close to the front of every hour but not 'til the * system load is low". Problems are: how do you know * what "low" means? (save me from /etc/cron.conf!) and: * how to guarantee low variance (how low is low?), which * means how to we run roughly every hour -- seems like * we need to keep a history or let the first hour set * the schedule, which means we aren't load-limited * anymore. too much for my overloaded brain. (vix, jan90) * HINT */ ch = get_string(cmd, MAX_COMMAND, file, " \t\n"); if (!strcmp("reboot", cmd)) { e->flags |= WHEN_REBOOT; } else if (!strcmp("yearly", cmd) || !strcmp("annually", cmd)) { bit_set(e->minute, 0); bit_set(e->hour, 0); bit_set(e->dom, 0); bit_set(e->month, 0); bit_nset(e->dow, 0, LAST_DOW - FIRST_DOW); e->flags |= DOW_STAR; } else if (!strcmp("monthly", cmd)) { bit_set(e->minute, 0); bit_set(e->hour, 0); bit_set(e->dom, 0); bit_nset(e->month, 0, LAST_MONTH - FIRST_MONTH); bit_nset(e->dow, 0, LAST_DOW - FIRST_DOW); e->flags |= DOW_STAR; } else if (!strcmp("weekly", cmd)) { bit_set(e->minute, 0); bit_set(e->hour, 0); bit_nset(e->dom, 0, LAST_DOM - FIRST_DOM); bit_nset(e->month, 0, LAST_MONTH - FIRST_MONTH); bit_set(e->dow, 0); e->flags |= DOW_STAR; } else if (!strcmp("daily", cmd) || !strcmp("midnight", cmd)) { bit_set(e->minute, 0); bit_set(e->hour, 0); bit_nset(e->dom, 0, LAST_DOM - FIRST_DOM); bit_nset(e->month, 0, LAST_MONTH - FIRST_MONTH); bit_nset(e->dow, 0, LAST_DOW - FIRST_DOW); } else if (!strcmp("hourly", cmd)) { bit_set(e->minute, 0); bit_nset(e->hour, 0, LAST_HOUR - FIRST_HOUR); bit_nset(e->dom, 0, LAST_DOM - FIRST_DOM); bit_nset(e->month, 0, LAST_MONTH - FIRST_MONTH); bit_nset(e->dow, 0, LAST_DOW - FIRST_DOW); e->flags |= HR_STAR; } else { ecode = e_timespec; goto eof; } /* Advance past whitespace between shortcut and * username/command. */ Skip_Blanks(ch, file); if (ch == EOF || ch == '\n') { ecode = e_cmd; goto eof; } } else { Debug(DPARS, ("load_entry()...about to parse numerics\n")); if (ch == '*') e->flags |= MIN_STAR; ch = get_list(e->minute, FIRST_MINUTE, LAST_MINUTE, PPC_NULL, ch, file); if (ch == EOF) { ecode = e_minute; goto eof; } /* hours */ if (ch == '*') e->flags |= HR_STAR; ch = get_list(e->hour, FIRST_HOUR, LAST_HOUR, PPC_NULL, ch, file); if (ch == EOF) { ecode = e_hour; goto eof; } /* DOM (days of month) */ if (ch == '*') e->flags |= DOM_STAR; ch = get_list(e->dom, FIRST_DOM, LAST_DOM, PPC_NULL, ch, file); if (ch == EOF) { ecode = e_dom; goto eof; } /* month */ ch = get_list(e->month, FIRST_MONTH, LAST_MONTH, MonthNames, ch, file); if (ch == EOF) { ecode = e_month; goto eof; } /* DOW (days of week) */ if (ch == '*') e->flags |= DOW_STAR; ch = get_list(e->dow, FIRST_DOW, LAST_DOW, DowNames, ch, file); if (ch == EOF) { ecode = e_dow; goto eof; } } /* make sundays equivalent */ if (bit_test(e->dow, 0) || bit_test(e->dow, 7)) { bit_set(e->dow, 0); bit_set(e->dow, 7); } /* check for permature EOL and catch a common typo */ if (ch == '\n' || ch == '*') { ecode = e_cmd; goto eof; } /* ch is the first character of a command, or a username */ unget_char(ch, file); if (!pw) { char *username = cmd; /* temp buffer */ Debug(DPARS, ("load_entry()...about to parse username\n")); ch = get_string(username, MAX_COMMAND, file, " \t\n"); Debug(DPARS, ("load_entry()...got %s\n", username)); if (ch == EOF || ch == '\n' || ch == '*') { ecode = e_cmd; goto eof; } pw = getpwnam(username); if (pw == NULL) { Debug(DPARS, ("load_entry()...unknown user entry\n")); memset(&temppw, 0, sizeof (temppw)); temppw.pw_name = username; temppw.pw_passwd = ""; pw = &temppw; } else { Debug(DPARS, ("load_entry()...uid %ld, gid %ld\n", (long) pw->pw_uid, (long) pw->pw_gid)); } } if ((e->pwd = pw_dup(pw)) == NULL) { ecode = e_memory; goto eof; } memset(e->pwd->pw_passwd, 0, strlen(e->pwd->pw_passwd)); p = env_get("RANDOM_DELAY", envp); if (p) { char *endptr; long val; errno = 0; /* To distinguish success/failure after call */ val = strtol(p, &endptr, 10); if (errno != 0 || val < 0 || val > 24*60) { log_it("CRON", getpid(), "ERROR", "bad value of RANDOM_DELAY", 0); } else { e->delay = (int)((double)val * RandomScale); } } /* copy and fix up environment. some variables are just defaults and * others are overrides. */ if ((e->envp = env_copy(envp)) == NULL) { ecode = e_memory; goto eof; } if (!env_get("SHELL", e->envp)) { if (glue_strings(envstr, sizeof envstr, "SHELL", _PATH_BSHELL, '=')) { if ((tenvp = env_set(e->envp, envstr)) == NULL) { ecode = e_memory; goto eof; } e->envp = tenvp; } else log_it("CRON", getpid(), "ERROR", "can't set SHELL", 0); } if ((tenvp = env_update_home(e->envp, pw->pw_dir)) == NULL) { ecode = e_memory; goto eof; } e->envp = tenvp; #ifndef LOGIN_CAP /* If login.conf is in used we will get the default PATH later. */ if (!env_get("PATH", e->envp)) { char *defpath; if (ChangePath) defpath = _PATH_DEFPATH; else { defpath = getenv("PATH"); if (defpath == NULL) defpath = _PATH_DEFPATH; } if (glue_strings(envstr, sizeof envstr, "PATH", defpath, '=')) { if ((tenvp = env_set(e->envp, envstr)) == NULL) { ecode = e_memory; goto eof; } e->envp = tenvp; } else log_it("CRON", getpid(), "ERROR", "can't set PATH", 0); } #endif /* LOGIN_CAP */ if (glue_strings(envstr, sizeof envstr, "LOGNAME", pw->pw_name, '=')) { if ((tenvp = env_set(e->envp, envstr)) == NULL) { ecode = e_memory; goto eof; } e->envp = tenvp; } else log_it("CRON", getpid(), "ERROR", "can't set LOGNAME", 0); #if defined(BSD) || defined(__linux) if (glue_strings(envstr, sizeof envstr, "USER", pw->pw_name, '=')) { if ((tenvp = env_set(e->envp, envstr)) == NULL) { ecode = e_memory; goto eof; } e->envp = tenvp; } else log_it("CRON", getpid(), "ERROR", "can't set USER", 0); #endif Debug(DPARS, ("load_entry()...about to parse command\n")); /* Everything up to the next \n or EOF is part of the command... * too bad we don't know in advance how long it will be, since we * need to malloc a string for it... so, we limit it to MAX_COMMAND. */ ch = get_string(cmd, MAX_COMMAND, file, "\n"); /* a file without a \n before the EOF is rude, so we'll complain... */ if (ch == EOF) { ecode = e_cmd; goto eof; } /* got the command in the 'cmd' string; save it in *e. */ if ((e->cmd = strdup(cmd)) == NULL) { ecode = e_memory; goto eof; } Debug(DPARS, ("load_entry()...returning successfully\n")); /* success, fini, return pointer to the entry we just created... */ return (e); eof: if (e->envp) env_free(e->envp); free(e->pwd); free(e->cmd); free(e); while (ch != '\n' && !feof(file)) ch = get_char(file); if (ecode != e_none && error_func) (*error_func) (ecodes[(int) ecode]); return (NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix CVE-2019-9704 and CVE-2019-9705 The users can cause DoS of the crond by loading huge crontab files. We now allow maximum 1000 environment variables and 1000 crontab entries. Also the comments and whitespace between the entries and variables are now limited to 32768 characters.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: g_socket_client_async_connect_data_free (GSocketClientAsyncConnectData *data) { g_clear_object (&data->connectable); g_clear_object (&data->enumerator); g_clear_object (&data->proxy_addr); g_clear_object (&data->socket); g_clear_object (&data->connection); g_slist_free_full (data->connection_attempts, connection_attempt_unref); g_clear_error (&data->last_error); g_slice_free (GSocketClientAsyncConnectData, data); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-754'], 'message': 'gsocketclient: Fix criticals This ensures the parent GTask is kept alive as long as an enumeration is running and trying to connect. Closes #1646 Closes #1649'</s>
<s>[INST] Given the following code containing errors, provide 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 phar_tar_writeheaders_int(phar_entry_info *entry, void *argument) /* {{{ */ { tar_header header; size_t pos; struct _phar_pass_tar_info *fp = (struct _phar_pass_tar_info *)argument; char padding[512]; if (entry->is_mounted) { return ZEND_HASH_APPLY_KEEP; } if (entry->is_deleted) { if (entry->fp_refcount <= 0) { return ZEND_HASH_APPLY_REMOVE; } else { /* we can't delete this in-memory until it is closed */ return ZEND_HASH_APPLY_KEEP; } } phar_add_virtual_dirs(entry->phar, entry->filename, entry->filename_len); memset((char *) &header, 0, sizeof(header)); if (entry->filename_len > 100) { char *boundary; if (entry->filename_len > 256) { if (fp->error) { spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, filename \"%s\" is too long for tar file format", entry->phar->fname, entry->filename); } return ZEND_HASH_APPLY_STOP; } boundary = entry->filename + entry->filename_len - 101; while (*boundary && *boundary != '/') { ++boundary; } if (!*boundary || ((boundary - entry->filename) > 155)) { if (fp->error) { spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, filename \"%s\" is too long for tar file format", entry->phar->fname, entry->filename); } return ZEND_HASH_APPLY_STOP; } memcpy(header.prefix, entry->filename, boundary - entry->filename); memcpy(header.name, boundary + 1, entry->filename_len - (boundary + 1 - entry->filename)); } else { memcpy(header.name, entry->filename, entry->filename_len); } phar_tar_octal(header.mode, entry->flags & PHAR_ENT_PERM_MASK, sizeof(header.mode)-1); if (FAILURE == phar_tar_octal(header.size, entry->uncompressed_filesize, sizeof(header.size)-1)) { if (fp->error) { spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, filename \"%s\" is too large for tar file format", entry->phar->fname, entry->filename); } return ZEND_HASH_APPLY_STOP; } if (FAILURE == phar_tar_octal(header.mtime, entry->timestamp, sizeof(header.mtime)-1)) { if (fp->error) { spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, file modification time of file \"%s\" is too large for tar file format", entry->phar->fname, entry->filename); } return ZEND_HASH_APPLY_STOP; } /* calc checksum */ header.typeflag = entry->tar_type; if (entry->link) { strncpy(header.linkname, entry->link, strlen(entry->link)); } strncpy(header.magic, "ustar", sizeof("ustar")-1); strncpy(header.version, "00", sizeof("00")-1); strncpy(header.checksum, " ", sizeof(" ")-1); entry->crc32 = phar_tar_checksum((char *)&header, sizeof(header)); if (FAILURE == phar_tar_octal(header.checksum, entry->crc32, sizeof(header.checksum)-1)) { if (fp->error) { spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, checksum of file \"%s\" is too large for tar file format", entry->phar->fname, entry->filename); } return ZEND_HASH_APPLY_STOP; } /* write header */ entry->header_offset = php_stream_tell(fp->new); if (sizeof(header) != php_stream_write(fp->new, (char *) &header, sizeof(header))) { if (fp->error) { spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, header for file \"%s\" could not be written", entry->phar->fname, entry->filename); } return ZEND_HASH_APPLY_STOP; } pos = php_stream_tell(fp->new); /* save start of file within tar */ /* write contents */ if (entry->uncompressed_filesize) { if (FAILURE == phar_open_entry_fp(entry, fp->error, 0)) { return ZEND_HASH_APPLY_STOP; } if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0)) { if (fp->error) { spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, contents of file \"%s\" could not be written, seek failed", entry->phar->fname, entry->filename); } return ZEND_HASH_APPLY_STOP; } if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(entry, 0), fp->new, entry->uncompressed_filesize, NULL)) { if (fp->error) { spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, contents of file \"%s\" could not be written", entry->phar->fname, entry->filename); } return ZEND_HASH_APPLY_STOP; } memset(padding, 0, 512); php_stream_write(fp->new, padding, ((entry->uncompressed_filesize +511)&~511) - entry->uncompressed_filesize); } if (!entry->is_modified && entry->fp_refcount) { /* open file pointers refer to this fp, do not free the stream */ switch (entry->fp_type) { case PHAR_FP: fp->free_fp = 0; break; case PHAR_UFP: fp->free_ufp = 0; default: break; } } entry->is_modified = 0; if (entry->fp_type == PHAR_MOD && entry->fp != entry->phar->fp && entry->fp != entry->phar->ufp) { if (!entry->fp_refcount) { php_stream_close(entry->fp); } entry->fp = NULL; } entry->fp_type = PHAR_FP; /* note new location within tar */ entry->offset = entry->offset_abs = pos; return ZEND_HASH_APPLY_KEEP; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #77586 - phar_tar_writeheaders_int() buffer overflow'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType WritePSImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { #define WriteRunlengthPacket(image,pixel,length,p) \ { \ if ((image->alpha_trait != UndefinedPixelTrait) && (length != 0) && \ (GetPixelAlpha(image,p) == (Quantum) TransparentAlpha)) \ { \ q=PopHexPixel(hex_digits,0xff,q); \ q=PopHexPixel(hex_digits,0xff,q); \ q=PopHexPixel(hex_digits,0xff,q); \ } \ else \ { \ q=PopHexPixel(hex_digits,ScaleQuantumToChar(ClampToQuantum(pixel.red)),q); \ q=PopHexPixel(hex_digits,ScaleQuantumToChar(ClampToQuantum(pixel.green)),q); \ q=PopHexPixel(hex_digits,ScaleQuantumToChar(ClampToQuantum(pixel.blue)),q); \ } \ q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); \ } static const char *const hex_digits[] = { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF", (const char *) NULL }, *const PostscriptProlog[]= { "%%BeginProlog", "%", "% Display a color image. The image is displayed in color on", "% Postscript viewers or printers that support color, otherwise", "% it is displayed as grayscale.", "%", "/DirectClassPacket", "{", " %", " % Get a DirectClass packet.", " %", " % Parameters:", " % red.", " % green.", " % blue.", " % length: number of pixels minus one of this color (optional).", " %", " currentfile color_packet readhexstring pop pop", " compression 0 eq", " {", " /number_pixels 3 def", " }", " {", " currentfile byte readhexstring pop 0 get", " /number_pixels exch 1 add 3 mul def", " } ifelse", " 0 3 number_pixels 1 sub", " {", " pixels exch color_packet putinterval", " } for", " pixels 0 number_pixels getinterval", "} bind def", "", "/DirectClassImage", "{", " %", " % Display a DirectClass image.", " %", " systemdict /colorimage known", " {", " columns rows 8", " [", " columns 0 0", " rows neg 0 rows", " ]", " { DirectClassPacket } false 3 colorimage", " }", " {", " %", " % No colorimage operator; convert to grayscale.", " %", " columns rows 8", " [", " columns 0 0", " rows neg 0 rows", " ]", " { GrayDirectClassPacket } image", " } ifelse", "} bind def", "", "/GrayDirectClassPacket", "{", " %", " % Get a DirectClass packet; convert to grayscale.", " %", " % Parameters:", " % red", " % green", " % blue", " % length: number of pixels minus one of this color (optional).", " %", " currentfile color_packet readhexstring pop pop", " color_packet 0 get 0.299 mul", " color_packet 1 get 0.587 mul add", " color_packet 2 get 0.114 mul add", " cvi", " /gray_packet exch def", " compression 0 eq", " {", " /number_pixels 1 def", " }", " {", " currentfile byte readhexstring pop 0 get", " /number_pixels exch 1 add def", " } ifelse", " 0 1 number_pixels 1 sub", " {", " pixels exch gray_packet put", " } for", " pixels 0 number_pixels getinterval", "} bind def", "", "/GrayPseudoClassPacket", "{", " %", " % Get a PseudoClass packet; convert to grayscale.", " %", " % Parameters:", " % index: index into the colormap.", " % length: number of pixels minus one of this color (optional).", " %", " currentfile byte readhexstring pop 0 get", " /offset exch 3 mul def", " /color_packet colormap offset 3 getinterval def", " color_packet 0 get 0.299 mul", " color_packet 1 get 0.587 mul add", " color_packet 2 get 0.114 mul add", " cvi", " /gray_packet exch def", " compression 0 eq", " {", " /number_pixels 1 def", " }", " {", " currentfile byte readhexstring pop 0 get", " /number_pixels exch 1 add def", " } ifelse", " 0 1 number_pixels 1 sub", " {", " pixels exch gray_packet put", " } for", " pixels 0 number_pixels getinterval", "} bind def", "", "/PseudoClassPacket", "{", " %", " % Get a PseudoClass packet.", " %", " % Parameters:", " % index: index into the colormap.", " % length: number of pixels minus one of this color (optional).", " %", " currentfile byte readhexstring pop 0 get", " /offset exch 3 mul def", " /color_packet colormap offset 3 getinterval def", " compression 0 eq", " {", " /number_pixels 3 def", " }", " {", " currentfile byte readhexstring pop 0 get", " /number_pixels exch 1 add 3 mul def", " } ifelse", " 0 3 number_pixels 1 sub", " {", " pixels exch color_packet putinterval", " } for", " pixels 0 number_pixels getinterval", "} bind def", "", "/PseudoClassImage", "{", " %", " % Display a PseudoClass image.", " %", " % Parameters:", " % class: 0-PseudoClass or 1-Grayscale.", " %", " currentfile buffer readline pop", " token pop /class exch def pop", " class 0 gt", " {", " currentfile buffer readline pop", " token pop /depth exch def pop", " /grays columns 8 add depth sub depth mul 8 idiv string def", " columns rows depth", " [", " columns 0 0", " rows neg 0 rows", " ]", " { currentfile grays readhexstring pop } image", " }", " {", " %", " % Parameters:", " % colors: number of colors in the colormap.", " % colormap: red, green, blue color packets.", " %", " currentfile buffer readline pop", " token pop /colors exch def pop", " /colors colors 3 mul def", " /colormap colors string def", " currentfile colormap readhexstring pop pop", " systemdict /colorimage known", " {", " columns rows 8", " [", " columns 0 0", " rows neg 0 rows", " ]", " { PseudoClassPacket } false 3 colorimage", " }", " {", " %", " % No colorimage operator; convert to grayscale.", " %", " columns rows 8", " [", " columns 0 0", " rows neg 0 rows", " ]", " { GrayPseudoClassPacket } image", " } ifelse", " } ifelse", "} bind def", "", "/DisplayImage", "{", " %", " % Display a DirectClass or PseudoClass image.", " %", " % Parameters:", " % x & y translation.", " % x & y scale.", " % label pointsize.", " % image label.", " % image columns & rows.", " % class: 0-DirectClass or 1-PseudoClass.", " % compression: 0-none or 1-RunlengthEncoded.", " % hex color packets.", " %", " gsave", " /buffer 512 string def", " /byte 1 string def", " /color_packet 3 string def", " /pixels 768 string def", "", " currentfile buffer readline pop", " token pop /x exch def", " token pop /y exch def pop", " x y translate", " currentfile buffer readline pop", " token pop /x exch def", " token pop /y exch def pop", " currentfile buffer readline pop", " token pop /pointsize exch def pop", (const char *) NULL }, *const PostscriptEpilog[]= { " x y scale", " currentfile buffer readline pop", " token pop /columns exch def", " token pop /rows exch def pop", " currentfile buffer readline pop", " token pop /class exch def pop", " currentfile buffer readline pop", " token pop /compression exch def pop", " class 0 gt { PseudoClassImage } { DirectClassImage } ifelse", " grestore", (const char *) NULL }; char buffer[MagickPathExtent], date[MagickPathExtent], **labels, page_geometry[MagickPathExtent]; CompressionType compression; const char *const *s, *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType scene; MagickStatusType flags; PixelInfo pixel; PointInfo delta, resolution, scale; Quantum index; RectangleInfo geometry, media_info, page_info; register const Quantum *p; register ssize_t i, x; register unsigned char *q; SegmentInfo bounds; size_t bit, byte, imageListLength, length, page, text_size; ssize_t j, y; time_t timer; unsigned char pixels[2048]; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) memset(&bounds,0,sizeof(bounds)); compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; page=1; scene=0; imageListLength=GetImageListLength(image); do { /* Scale relative to dots-per-inch. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->resolution.x; resolution.y=image->resolution.y; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MagickPathExtent,"%.20gx%.20g", (double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,"PS") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry,MagickPathExtent); (void) ConcatenateMagickString(page_geometry,">",MagickPathExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info,exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); if (page == 1) { /* Output Postscript header. */ if (LocaleCompare(image_info->magick,"PS") == 0) (void) CopyMagickString(buffer,"%!PS-Adobe-3.0\n",MagickPathExtent); else (void) CopyMagickString(buffer,"%!PS-Adobe-3.0 EPSF-3.0\n", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"%%Creator: (ImageMagick)\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"%%%%Title: (%s)\n", image->filename); (void) WriteBlobString(image,buffer); timer=time((time_t *) NULL); (void) FormatMagickTime(timer,MagickPathExtent,date); (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%CreationDate: (%s)\n",date); (void) WriteBlobString(image,buffer); bounds.x1=(double) geometry.x; bounds.y1=(double) geometry.y; bounds.x2=(double) geometry.x+scale.x; bounds.y2=(double) geometry.y+(geometry.height+text_size); if ((image_info->adjoin != MagickFalse) && (GetNextImageInList(image) != (Image *) NULL)) (void) CopyMagickString(buffer,"%%%%BoundingBox: (atend)\n", MagickPathExtent); else { (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%BoundingBox: %.20g %.20g %.20g %.20g\n",ceil(bounds.x1-0.5), ceil(bounds.y1-0.5),floor(bounds.x2+0.5),floor(bounds.y2+0.5)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1, bounds.y1,bounds.x2,bounds.y2); } (void) WriteBlobString(image,buffer); profile=GetImageProfile(image,"8bim"); if (profile != (StringInfo *) NULL) { /* Embed Photoshop profile. */ (void) FormatLocaleString(buffer,MagickPathExtent, "%%BeginPhotoshop: %.20g",(double) GetStringInfoLength(profile)); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) { if ((i % 32) == 0) (void) WriteBlobString(image,"\n% "); (void) FormatLocaleString(buffer,MagickPathExtent,"%02X", (unsigned int) (GetStringInfoDatum(profile)[i] & 0xff)); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"\n%EndPhotoshop\n"); } profile=GetImageProfile(image,"xmp"); DisableMSCWarning(4127) if (0 && (profile != (StringInfo *) NULL)) RestoreMSCWarning { /* Embed XML profile. */ (void) WriteBlobString(image,"\n%begin_xml_code\n"); (void) FormatLocaleString(buffer,MagickPathExtent, "\n%%begin_xml_packet: %.20g\n",(double) GetStringInfoLength(profile)); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) (void) WriteBlobByte(image,GetStringInfoDatum(profile)[i]); (void) WriteBlobString(image,"\n%end_xml_packet\n%end_xml_code\n"); } value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) (void) WriteBlobString(image, "%%DocumentNeededResources: font Times-Roman\n"); (void) WriteBlobString(image,"%%DocumentData: Clean7Bit\n"); (void) WriteBlobString(image,"%%LanguageLevel: 1\n"); if (LocaleCompare(image_info->magick,"PS") != 0) (void) WriteBlobString(image,"%%Pages: 1\n"); else { /* Compute the number of pages. */ (void) WriteBlobString(image,"%%Orientation: Portrait\n"); (void) WriteBlobString(image,"%%PageOrder: Ascend\n"); (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%Pages: %.20g\n",image_info->adjoin != MagickFalse ? (double) imageListLength : 1.0); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"%%EndComments\n"); (void) WriteBlobString(image,"\n%%BeginDefaults\n"); (void) WriteBlobString(image,"%%EndDefaults\n\n"); if ((LocaleCompare(image_info->magick,"EPI") == 0) || (LocaleCompare(image_info->magick,"EPSI") == 0) || (LocaleCompare(image_info->magick,"EPT") == 0)) { Image *preview_image; Quantum pixel; register ssize_t x; ssize_t y; /* Create preview image. */ preview_image=CloneImage(image,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Dump image as bitmap. */ (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%BeginPreview: %.20g %.20g %.20g %.20g\n%% ",(double) preview_image->columns,(double) preview_image->rows,1.0, (double) ((((preview_image->columns+7) >> 3)*preview_image->rows+ 35)/36)); (void) WriteBlobString(image,buffer); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(preview_image,0,y,preview_image->columns,1, exception); if (p == (const Quantum *) NULL) break; bit=0; byte=0; for (x=0; x < (ssize_t) preview_image->columns; x++) { byte<<=1; pixel=ClampToQuantum(GetPixelLuma(preview_image,p)); if (pixel >= (Quantum) (QuantumRange/2)) byte|=0x01; bit++; if (bit == 8) { q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+8) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; (void) WriteBlobString(image,"% "); }; bit=0; byte=0; } } if (bit != 0) { byte<<=(8-bit); q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+8) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; (void) WriteBlobString(image,"% "); }; }; } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } (void) WriteBlobString(image,"\n%%EndPreview\n"); preview_image=DestroyImage(preview_image); } /* Output Postscript commands. */ for (s=PostscriptProlog; *s != (char *) NULL; s++) { (void) FormatLocaleString(buffer,MagickPathExtent,"%s\n",*s); (void) WriteBlobString(image,buffer); } value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) { (void) WriteBlobString(image, " /Times-Roman findfont pointsize scalefont setfont\n"); for (j=(ssize_t) MultilineCensus(value)-1; j >= 0; j--) { (void) WriteBlobString(image," /label 512 string def\n"); (void) WriteBlobString(image, " currentfile label readline pop\n"); (void) FormatLocaleString(buffer,MagickPathExtent, " 0 y %g add moveto label show pop\n",j*pointsize+12); (void) WriteBlobString(image,buffer); } } for (s=PostscriptEpilog; *s != (char *) NULL; s++) { (void) FormatLocaleString(buffer,MagickPathExtent,"%s\n",*s); (void) WriteBlobString(image,buffer); } if (LocaleCompare(image_info->magick,"PS") == 0) (void) WriteBlobString(image," showpage\n"); (void) WriteBlobString(image,"} bind def\n"); (void) WriteBlobString(image,"%%EndProlog\n"); } (void) FormatLocaleString(buffer,MagickPathExtent,"%%%%Page: 1 %.20g\n", (double) (page++)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%PageBoundingBox: %.20g %.20g %.20g %.20g\n",(double) geometry.x, (double) geometry.y,geometry.x+(double) geometry.width,geometry.y+(double) (geometry.height+text_size)); (void) WriteBlobString(image,buffer); if ((double) geometry.x < bounds.x1) bounds.x1=(double) geometry.x; if ((double) geometry.y < bounds.y1) bounds.y1=(double) geometry.y; if ((double) (geometry.x+geometry.width-1) > bounds.x2) bounds.x2=(double) geometry.x+geometry.width-1; if ((double) (geometry.y+(geometry.height+text_size)-1) > bounds.y2) bounds.y2=(double) geometry.y+(geometry.height+text_size)-1; value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) (void) WriteBlobString(image,"%%%%PageResources: font Times-Roman\n"); if (LocaleCompare(image_info->magick,"PS") != 0) (void) WriteBlobString(image,"userdict begin\n"); (void) WriteBlobString(image,"DisplayImage\n"); /* Output image data. */ (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n%g %g\n%g\n", (double) geometry.x,(double) geometry.y,scale.x,scale.y,pointsize); (void) WriteBlobString(image,buffer); labels=(char **) NULL; value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { for (i=0; labels[i] != (char *) NULL; i++) { (void) FormatLocaleString(buffer,MagickPathExtent,"%s \n", labels[i]); (void) WriteBlobString(image,buffer); labels[i]=DestroyString(labels[i]); } labels=(char **) RelinquishMagickMemory(labels); } (void) memset(&pixel,0,sizeof(pixel)); pixel.alpha=(MagickRealType) TransparentAlpha; index=0; x=0; if ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse)) { if (SetImageMonochrome(image,exception) == MagickFalse) { Quantum pixel; /* Dump image as grayscale. */ (void) FormatLocaleString(buffer,MagickPathExtent, "%.20g %.20g\n1\n1\n1\n8\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(Quantum) ScaleQuantumToChar(ClampToQuantum(GetPixelLuma( image,p))); q=PopHexPixel(hex_digits,(size_t) pixel,q); if ((q-pixels+8) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } } else { ssize_t y; Quantum pixel; /* Dump image as bitmap. */ (void) FormatLocaleString(buffer,MagickPathExtent, "%.20g %.20g\n1\n1\n1\n1\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; pixel=ClampToQuantum(GetPixelLuma(image,p)); if (pixel >= (Quantum) (QuantumRange/2)) byte|=0x01; bit++; if (bit == 8) { q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+2) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; }; bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { byte<<=(8-bit); q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+2) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } }; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (image->alpha_trait != UndefinedPixelTrait)) { /* Dump DirectClass image. */ (void) FormatLocaleString(buffer,MagickPathExtent, "%.20g %.20g\n0\n%d\n",(double) image->columns,(double) image->rows, compression == RLECompression ? 1 : 0); (void) WriteBlobString(image,buffer); switch (compression) { case RLECompression: { /* Dump runlength-encoded DirectColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; GetPixelInfoPixel(image,p,&pixel); length=255; for (x=0; x < (ssize_t) image->columns; x++) { if ((GetPixelRed(image,p) == ClampToQuantum(pixel.red)) && (GetPixelGreen(image,p) == ClampToQuantum(pixel.green)) && (GetPixelBlue(image,p) == ClampToQuantum(pixel.blue)) && (GetPixelAlpha(image,p) == ClampToQuantum(pixel.alpha)) && (length < 255) && (x < (ssize_t) (image->columns-1))) length++; else { if (x > 0) { WriteRunlengthPacket(image,pixel,length,p); if ((q-pixels+10) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } } length=0; } GetPixelInfoPixel(image,p,&pixel); p+=GetPixelChannels(image); } WriteRunlengthPacket(image,pixel,length,p); if ((q-pixels+10) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case NoCompression: default: { /* Dump uncompressed DirectColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if ((image->alpha_trait != UndefinedPixelTrait) && (GetPixelAlpha(image,p) == (Quantum) TransparentAlpha)) { q=PopHexPixel(hex_digits,0xff,q); q=PopHexPixel(hex_digits,0xff,q); q=PopHexPixel(hex_digits,0xff,q); } else { q=PopHexPixel(hex_digits,ScaleQuantumToChar( GetPixelRed(image,p)),q); q=PopHexPixel(hex_digits,ScaleQuantumToChar( GetPixelGreen(image,p)),q); q=PopHexPixel(hex_digits,ScaleQuantumToChar( GetPixelBlue(image,p)),q); } if ((q-pixels+6) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } } (void) WriteBlobByte(image,'\n'); } else { /* Dump PseudoClass image. */ (void) FormatLocaleString(buffer,MagickPathExtent, "%.20g %.20g\n%d\n%d\n0\n",(double) image->columns,(double) image->rows,image->storage_class == PseudoClass ? 1 : 0, compression == RLECompression ? 1 : 0); (void) WriteBlobString(image,buffer); /* Dump number of colors and colormap. */ (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) image->colors); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) image->colors; i++) { (void) FormatLocaleString(buffer,MagickPathExtent,"%02X%02X%02X\n", ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red)), ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green)), ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue))); (void) WriteBlobString(image,buffer); } switch (compression) { case RLECompression: { /* Dump runlength-encoded PseudoColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; index=GetPixelIndex(image,p); length=255; for (x=0; x < (ssize_t) image->columns; x++) { if ((index == GetPixelIndex(image,p)) && (length < 255) && (x < ((ssize_t) image->columns-1))) length++; else { if (x > 0) { q=PopHexPixel(hex_digits,(size_t) index,q); q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); i++; if ((q-pixels+6) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } } length=0; } index=GetPixelIndex(image,p); pixel.red=(MagickRealType) GetPixelRed(image,p); pixel.green=(MagickRealType) GetPixelGreen(image,p); pixel.blue=(MagickRealType) GetPixelBlue(image,p); pixel.alpha=(MagickRealType) GetPixelAlpha(image,p); p+=GetPixelChannels(image); } q=PopHexPixel(hex_digits,(size_t) index,q); q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case NoCompression: default: { /* Dump uncompressed PseudoColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { q=PopHexPixel(hex_digits,(size_t) GetPixelIndex(image,p),q); if ((q-pixels+4) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } } (void) WriteBlobByte(image,'\n'); } if (LocaleCompare(image_info->magick,"PS") != 0) (void) WriteBlobString(image,"end\n"); (void) WriteBlobString(image,"%%PageTrailer\n"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) WriteBlobString(image,"%%Trailer\n"); if (page > 2) { (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%BoundingBox: %.20g %.20g %.20g %.20g\n",ceil(bounds.x1-0.5), ceil(bounds.y1-0.5),floor(bounds.x2-0.5),floor(bounds.y2-0.5)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1,bounds.x2, bounds.y2); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"%%EOF\n"); (void) CloseBlob(image); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1523'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: UsbHubReadDesc ( IN USB_DEVICE *HubDev, OUT EFI_USB_HUB_DESCRIPTOR *HubDesc ) { EFI_STATUS Status; if (HubDev->Speed == EFI_USB_SPEED_SUPER) { // // Get the super speed hub descriptor // Status = UsbHubCtrlGetSuperSpeedHubDesc (HubDev, HubDesc); } else { // // First get the hub descriptor length // Status = UsbHubCtrlGetHubDesc (HubDev, HubDesc, 2); if (EFI_ERROR (Status)) { return Status; } // // Get the whole hub descriptor // Status = UsbHubCtrlGetHubDesc (HubDev, HubDesc, HubDesc->Length); } return Status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg UsbBusDxe: Fix wrong buffer length used to read hub desc REF: https://bugzilla.tianocore.org/show_bug.cgi?id=973 HUB descriptor has variable length. But the code uses stack (HubDesc in UsbHubInit) with fixed length sizeof(EFI_USB_HUB_DESCRIPTOR) to hold HUB descriptor data. It uses hard code length value (32 that is greater than sizeof(EFI_USB_HUB_DESCRIPTOR)) for SuperSpeed path, then there will be stack overflow when IOMMU is enabled because the Unmap operation will copy the data from device buffer to host buffer. And it uses HubDesc->Length for none SuperSpeed path, then there will be stack overflow when HubDesc->Length is greater than sizeof(EFI_USB_HUB_DESCRIPTOR). The patch updates the code to use a big enough buffer to hold the descriptor data. The definition EFI_USB_SUPER_SPEED_HUB_DESCRIPTOR is wrong (HubDelay field should be UINT16 type) and no code is using it, the patch removes it. Cc: Jiewen Yao <jiewen.yao@intel.com> Cc: Ruiyu Ni <ruiyu.ni@intel.com> Cc: Bret Barkelew <bret.barkelew@microsoft.com> Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Star Zeng <star.zeng@intel.com> Reviewed-by: Bret Barkelew <bret.barkelew@microsoft.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: request_rec *h2_request_create_rec(const h2_request *req, conn_rec *c) { int access_status = HTTP_OK; const char *rpath; const char *s; #if AP_MODULE_MAGIC_AT_LEAST(20150222, 13) request_rec *r = ap_create_request(c); #else request_rec *r = my_ap_create_request(c); #endif r->headers_in = apr_table_clone(r->pool, req->headers); ap_run_pre_read_request(r, c); /* Time to populate r with the data we have. */ r->request_time = req->request_time; r->method = req->method; /* Provide quick information about the request method as soon as known */ r->method_number = ap_method_number_of(r->method); if (r->method_number == M_GET && r->method[0] == 'H') { r->header_only = 1; } rpath = (req->path ? req->path : ""); ap_parse_uri(r, rpath); r->protocol = (char*)"HTTP/2.0"; r->proto_num = HTTP_VERSION(2, 0); r->the_request = apr_psprintf(r->pool, "%s %s %s", r->method, rpath, r->protocol); /* update what we think the virtual host is based on the headers we've * now read. may update status. * Leave r->hostname empty, vhost will parse if form our Host: header, * otherwise we get complains about port numbers. */ r->hostname = NULL; ap_update_vhost_from_headers(r); /* we may have switched to another server */ r->per_dir_config = r->server->lookup_defaults; s = apr_table_get(r->headers_in, "Expect"); if (s && s[0]) { if (ap_cstr_casecmp(s, "100-continue") == 0) { r->expecting_100 = 1; } else { r->status = HTTP_EXPECTATION_FAILED; ap_send_error_response(r, 0); } } /* * Add the HTTP_IN filter here to ensure that ap_discard_request_body * called by ap_die and by ap_send_error_response works correctly on * status codes that do not cause the connection to be dropped and * in situations where the connection should be kept alive. */ ap_add_input_filter_handle(ap_http_input_filter_handle, NULL, r, r->connection); if (access_status != HTTP_OK || (access_status = ap_run_post_read_request(r))) { /* Request check post hooks failed. An example of this would be a * request for a vhost where h2 is disabled --> 421. */ ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(03367) "h2_request: access_status=%d, request_create failed", access_status); ap_die(access_status, r); ap_update_child_status(c->sbh, SERVER_BUSY_LOG, r); ap_run_log_transaction(r); r = NULL; goto traceout; } AP_READ_REQUEST_SUCCESS((uintptr_t)r, (char *)r->method, (char *)r->uri, (char *)r->server->defn_name, r->status); return r; traceout: AP_READ_REQUEST_FAILURE((uintptr_t)r); return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': '* Integrated a forgotten request init fix from Apache subversion'</s>
<s>[INST] Given the following code containing errors, provide 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 aio_complete_rw(struct kiocb *kiocb, long res, long res2) { struct aio_kiocb *iocb = container_of(kiocb, struct aio_kiocb, rw); if (!list_empty_careful(&iocb->ki_list)) aio_remove_iocb(iocb); if (kiocb->ki_flags & IOCB_WRITE) { struct inode *inode = file_inode(kiocb->ki_filp); /* * Tell lockdep we inherited freeze protection from submission * thread. */ if (S_ISREG(inode->i_mode)) __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE); file_end_write(kiocb->ki_filp); } fput(kiocb->ki_filp); aio_complete(iocb, res, res2); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'aio: simplify - and fix - fget/fput for io_submit() Al Viro root-caused a race where the IOCB_CMD_POLL handling of fget/fput() could cause us to access the file pointer after it had already been freed: "In more details - normally IOCB_CMD_POLL handling looks so: 1) io_submit(2) allocates aio_kiocb instance and passes it to aio_poll() 2) aio_poll() resolves the descriptor to struct file by req->file = fget(iocb->aio_fildes) 3) aio_poll() sets ->woken to false and raises ->ki_refcnt of that aio_kiocb to 2 (bumps by 1, that is). 4) aio_poll() calls vfs_poll(). After sanity checks (basically, "poll_wait() had been called and only once") it locks the queue. That's what the extra reference to iocb had been for - we know we can safely access it. 5) With queue locked, we check if ->woken has already been set to true (by aio_poll_wake()) and, if it had been, we unlock the queue, drop a reference to aio_kiocb and bugger off - at that point it's a responsibility to aio_poll_wake() and the stuff called/scheduled by it. That code will drop the reference to file in req->file, along with the other reference to our aio_kiocb. 6) otherwise, we see whether we need to wait. If we do, we unlock the queue, drop one reference to aio_kiocb and go away - eventual wakeup (or cancel) will deal with the reference to file and with the other reference to aio_kiocb 7) otherwise we remove ourselves from waitqueue (still under the queue lock), so that wakeup won't get us. No async activity will be happening, so we can safely drop req->file and iocb ourselves. If wakeup happens while we are in vfs_poll(), we are fine - aio_kiocb won't get freed under us, so we can do all the checks and locking safely. And we don't touch ->file if we detect that case. However, vfs_poll() most certainly *does* touch the file it had been given. So wakeup coming while we are still in ->poll() might end up doing fput() on that file. That case is not too rare, and usually we are saved by the still present reference from descriptor table - that fput() is not the final one. But if another thread closes that descriptor right after our fget() and wakeup does happen before ->poll() returns, we are in trouble - final fput() done while we are in the middle of a method: Al also wrote a patch to take an extra reference to the file descriptor to fix this, but I instead suggested we just streamline the whole file pointer handling by submit_io() so that the generic aio submission code simply keeps the file pointer around until the aio has completed. Fixes: bfe4037e722e ("aio: implement IOCB_CMD_POLL") Acked-by: Al Viro <viro@zeniv.linux.org.uk> Reported-by: syzbot+503d4cc169fcec1cb18c@syzkaller.appspotmail.com Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int process_peer_commit (pwd_session_t *session, uint8_t *in, size_t in_len, BN_CTX *bnctx) { uint8_t *ptr; size_t data_len; BIGNUM *x = NULL, *y = NULL, *cofactor = NULL; EC_POINT *K = NULL, *point = NULL; int res = 1; if (((session->peer_scalar = BN_new()) == NULL) || ((session->k = BN_new()) == NULL) || ((cofactor = BN_new()) == NULL) || ((x = BN_new()) == NULL) || ((y = BN_new()) == NULL) || ((point = EC_POINT_new(session->group)) == NULL) || ((K = EC_POINT_new(session->group)) == NULL) || ((session->peer_element = EC_POINT_new(session->group)) == NULL)) { DEBUG2("pwd: failed to allocate room to process peer's commit"); goto finish; } if (!EC_GROUP_get_cofactor(session->group, cofactor, NULL)) { DEBUG2("pwd: unable to get group co-factor"); goto finish; } /* element, x then y, followed by scalar */ ptr = (uint8_t *)in; data_len = BN_num_bytes(session->prime); /* * Did the peer send enough data? */ if (in_len < (2 * data_len + BN_num_bytes(session->order))) { DEBUG("pwd: Invalid commit packet"); goto finish; } BN_bin2bn(ptr, data_len, x); ptr += data_len; BN_bin2bn(ptr, data_len, y); ptr += data_len; data_len = BN_num_bytes(session->order); BN_bin2bn(ptr, data_len, session->peer_scalar); if (!EC_POINT_set_affine_coordinates_GFp(session->group, session->peer_element, x, y, bnctx)) { DEBUG2("pwd: unable to get coordinates of peer's element"); goto finish; } /* check to ensure peer's element is not in a small sub-group */ if (BN_cmp(cofactor, BN_value_one())) { if (!EC_POINT_mul(session->group, point, NULL, session->peer_element, cofactor, NULL)) { DEBUG2("pwd: unable to multiply element by co-factor"); goto finish; } if (EC_POINT_is_at_infinity(session->group, point)) { DEBUG2("pwd: peer's element is in small sub-group"); goto finish; } } /* compute the shared key, k */ if ((!EC_POINT_mul(session->group, K, NULL, session->pwe, session->peer_scalar, bnctx)) || (!EC_POINT_add(session->group, K, K, session->peer_element, bnctx)) || (!EC_POINT_mul(session->group, K, NULL, K, session->private_value, bnctx))) { DEBUG2("pwd: unable to compute shared key, k"); goto finish; } /* ensure that the shared key isn't in a small sub-group */ if (BN_cmp(cofactor, BN_value_one())) { if (!EC_POINT_mul(session->group, K, NULL, K, cofactor, NULL)) { DEBUG2("pwd: unable to multiply k by co-factor"); goto finish; } } /* * This check is strictly speaking just for the case above where * co-factor > 1 but it was suggested that even though this is probably * never going to happen it is a simple and safe check "just to be * sure" so let's be safe. */ if (EC_POINT_is_at_infinity(session->group, K)) { DEBUG2("pwd: k is point-at-infinity!"); goto finish; } if (!EC_POINT_get_affine_coordinates_GFp(session->group, K, session->k, NULL, bnctx)) { DEBUG2("pwd: unable to get shared secret from K"); goto finish; } res = 0; finish: EC_POINT_clear_free(K); EC_POINT_clear_free(point); BN_clear_free(cofactor); BN_clear_free(x); BN_clear_free(y); return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-345'], 'message': 'When processing an EAP-pwd Commit frame, the peer's scalar and elliptic curve point were not validated. This allowed an adversary to bypass authentication, and impersonate any user. Fix this vulnerability by assuring the received scalar lies within the valid range, and by checking that the received element is not the point at infinity and lies on the elliptic curve being used.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: main (int argc, char **argv) { mode_t old_umask; cleanup_free char *base_path = NULL; int clone_flags; char *old_cwd = NULL; pid_t pid; int event_fd = -1; int child_wait_fd = -1; int setup_finished_pipe[] = {-1, -1}; const char *new_cwd; uid_t ns_uid; gid_t ns_gid; struct stat sbuf; uint64_t val; int res UNUSED; cleanup_free char *seccomp_data = NULL; size_t seccomp_len; struct sock_fprog seccomp_prog; cleanup_free char *args_data = NULL; /* Handle --version early on before we try to acquire/drop * any capabilities so it works in a build environment; * right now flatpak's build runs bubblewrap --version. * https://github.com/projectatomic/bubblewrap/issues/185 */ if (argc == 2 && (strcmp (argv[1], "--version") == 0)) print_version_and_exit (); real_uid = getuid (); real_gid = getgid (); /* Get the (optional) privileges we need */ acquire_privs (); /* Never gain any more privs during exec */ if (prctl (PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) die_with_error ("prctl(PR_SET_NO_NEW_CAPS) failed"); /* The initial code is run with high permissions (i.e. CAP_SYS_ADMIN), so take lots of care. */ read_overflowids (); argv0 = argv[0]; if (isatty (1)) host_tty_dev = ttyname (1); argv++; argc--; if (argc == 0) usage (EXIT_FAILURE, stderr); parse_args (&argc, (const char ***) &argv); /* suck the args into a cleanup_free variable to control their lifecycle */ args_data = opt_args_data; opt_args_data = NULL; if ((requested_caps[0] || requested_caps[1]) && is_privileged) die ("--cap-add in setuid mode can be used only by root"); if (opt_userns_block_fd != -1 && !opt_unshare_user) die ("--userns-block-fd requires --unshare-user"); if (opt_userns_block_fd != -1 && opt_info_fd == -1) die ("--userns-block-fd requires --info-fd"); /* We have to do this if we weren't installed setuid (and we're not * root), so let's just DWIM */ if (!is_privileged && getuid () != 0) opt_unshare_user = TRUE; #ifdef ENABLE_REQUIRE_USERNS /* In this build option, we require userns. */ if (is_privileged && getuid () != 0) opt_unshare_user = TRUE; #endif if (opt_unshare_user_try && stat ("/proc/self/ns/user", &sbuf) == 0) { bool disabled = FALSE; /* RHEL7 has a kernel module parameter that lets you enable user namespaces */ if (stat ("/sys/module/user_namespace/parameters/enable", &sbuf) == 0) { cleanup_free char *enable = NULL; enable = load_file_at (AT_FDCWD, "/sys/module/user_namespace/parameters/enable"); if (enable != NULL && enable[0] == 'N') disabled = TRUE; } /* Check for max_user_namespaces */ if (stat ("/proc/sys/user/max_user_namespaces", &sbuf) == 0) { cleanup_free char *max_user_ns = NULL; max_user_ns = load_file_at (AT_FDCWD, "/proc/sys/user/max_user_namespaces"); if (max_user_ns != NULL && strcmp(max_user_ns, "0\n") == 0) disabled = TRUE; } /* Debian lets you disable *unprivileged* user namespaces. However this is not a problem if we're privileged, and if we're not opt_unshare_user is TRUE already, and there is not much we can do, its just a non-working setup. */ if (!disabled) opt_unshare_user = TRUE; } if (argc == 0) usage (EXIT_FAILURE, stderr); __debug__ (("Creating root mount point\n")); if (opt_sandbox_uid == -1) opt_sandbox_uid = real_uid; if (opt_sandbox_gid == -1) opt_sandbox_gid = real_gid; if (!opt_unshare_user && opt_sandbox_uid != real_uid) die ("Specifying --uid requires --unshare-user"); if (!opt_unshare_user && opt_sandbox_gid != real_gid) die ("Specifying --gid requires --unshare-user"); if (!opt_unshare_uts && opt_sandbox_hostname != NULL) die ("Specifying --hostname requires --unshare-uts"); if (opt_as_pid_1 && !opt_unshare_pid) die ("Specifying --as-pid-1 requires --unshare-pid"); if (opt_as_pid_1 && lock_files != NULL) die ("Specifying --as-pid-1 and --lock-file is not permitted"); /* We need to read stuff from proc during the pivot_root dance, etc. Lets keep a fd to it open */ proc_fd = open ("/proc", O_PATH); if (proc_fd == -1) die_with_error ("Can't open /proc"); /* We need *some* mountpoint where we can mount the root tmpfs. We first try in /run, and if that fails, try in /tmp. */ base_path = xasprintf ("/run/user/%d/.bubblewrap", real_uid); if (ensure_dir (base_path, 0755)) { free (base_path); base_path = xasprintf ("/tmp/.bubblewrap-%d", real_uid); if (ensure_dir (base_path, 0755)) die_with_error ("Creating root mountpoint failed"); } __debug__ (("creating new namespace\n")); if (opt_unshare_pid && !opt_as_pid_1) { event_fd = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK); if (event_fd == -1) die_with_error ("eventfd()"); } /* We block sigchild here so that we can use signalfd in the monitor. */ block_sigchild (); clone_flags = SIGCHLD | CLONE_NEWNS; if (opt_unshare_user) clone_flags |= CLONE_NEWUSER; if (opt_unshare_pid) clone_flags |= CLONE_NEWPID; if (opt_unshare_net) clone_flags |= CLONE_NEWNET; if (opt_unshare_ipc) clone_flags |= CLONE_NEWIPC; if (opt_unshare_uts) clone_flags |= CLONE_NEWUTS; if (opt_unshare_cgroup) { if (stat ("/proc/self/ns/cgroup", &sbuf)) { if (errno == ENOENT) die ("Cannot create new cgroup namespace because the kernel does not support it"); else die_with_error ("stat on /proc/self/ns/cgroup failed"); } clone_flags |= CLONE_NEWCGROUP; } if (opt_unshare_cgroup_try) if (!stat ("/proc/self/ns/cgroup", &sbuf)) clone_flags |= CLONE_NEWCGROUP; child_wait_fd = eventfd (0, EFD_CLOEXEC); if (child_wait_fd == -1) die_with_error ("eventfd()"); /* Track whether pre-exec setup finished if we're reporting process exit */ if (opt_json_status_fd != -1) { int ret; ret = pipe2 (setup_finished_pipe, O_CLOEXEC); if (ret == -1) die_with_error ("pipe2()"); } pid = raw_clone (clone_flags, NULL); if (pid == -1) { if (opt_unshare_user) { if (errno == EINVAL) die ("Creating new namespace failed, likely because the kernel does not support user namespaces. bwrap must be installed setuid on such systems."); else if (errno == EPERM && !is_privileged) die ("No permissions to creating new namespace, likely because the kernel does not allow non-privileged user namespaces. On e.g. debian this can be enabled with 'sysctl kernel.unprivileged_userns_clone=1'."); } die_with_error ("Creating new namespace failed"); } ns_uid = opt_sandbox_uid; ns_gid = opt_sandbox_gid; if (pid != 0) { /* Parent, outside sandbox, privileged (initially) */ if (is_privileged && opt_unshare_user && opt_userns_block_fd == -1) { /* We're running as euid 0, but the uid we want to map is * not 0. This means we're not allowed to write this from * the child user namespace, so we do it from the parent. * * Also, we map uid/gid 0 in the namespace (to overflowuid) * if opt_needs_devpts is true, because otherwise the mount * of devpts fails due to root not being mapped. */ write_uid_gid_map (ns_uid, real_uid, ns_gid, real_gid, pid, TRUE, opt_needs_devpts); } /* Initial launched process, wait for exec:ed command to exit */ /* We don't need any privileges in the launcher, drop them immediately. */ drop_privs (FALSE); /* Optionally bind our lifecycle to that of the parent */ handle_die_with_parent (); if (opt_info_fd != -1) { cleanup_free char *output = xasprintf ("{\n \"child-pid\": %i\n}\n", pid); dump_info (opt_info_fd, output, TRUE); close (opt_info_fd); } if (opt_json_status_fd != -1) { cleanup_free char *output = xasprintf ("{ \"child-pid\": %i }\n", pid); dump_info (opt_json_status_fd, output, TRUE); } if (opt_userns_block_fd != -1) { char b[1]; (void) TEMP_FAILURE_RETRY (read (opt_userns_block_fd, b, 1)); close (opt_userns_block_fd); } /* Let child run now that the uid maps are set up */ val = 1; res = write (child_wait_fd, &val, 8); /* Ignore res, if e.g. the child died and closed child_wait_fd we don't want to error out here */ close (child_wait_fd); return monitor_child (event_fd, pid, setup_finished_pipe[0]); } /* Child, in sandbox, privileged in the parent or in the user namespace (if --unshare-user). * * Note that for user namespaces we run as euid 0 during clone(), so * the child user namespace is owned by euid 0., This means that the * regular user namespace parent (with uid != 0) doesn't have any * capabilities in it, which is nice as we can't exploit those. In * particular the parent user namespace doesn't have CAP_PTRACE * which would otherwise allow the parent to hijack of the child * after this point. * * Unfortunately this also means you can't ptrace the final * sandboxed process from outside the sandbox either. */ if (opt_info_fd != -1) close (opt_info_fd); if (opt_json_status_fd != -1) close (opt_json_status_fd); /* Wait for the parent to init uid/gid maps and drop caps */ res = read (child_wait_fd, &val, 8); close (child_wait_fd); /* At this point we can completely drop root uid, but retain the * required permitted caps. This allow us to do full setup as * the user uid, which makes e.g. fuse access work. */ switch_to_user_with_privs (); if (opt_unshare_net) loopback_setup (); /* Will exit if unsuccessful */ ns_uid = opt_sandbox_uid; ns_gid = opt_sandbox_gid; if (!is_privileged && opt_unshare_user && opt_userns_block_fd == -1) { /* In the unprivileged case we have to write the uid/gid maps in * the child, because we have no caps in the parent */ if (opt_needs_devpts) { /* This is a bit hacky, but we need to first map the real uid/gid to 0, otherwise we can't mount the devpts filesystem because root is not mapped. Later we will create another child user namespace and map back to the real uid */ ns_uid = 0; ns_gid = 0; } write_uid_gid_map (ns_uid, real_uid, ns_gid, real_gid, -1, TRUE, FALSE); } old_umask = umask (0); /* Need to do this before the chroot, but after we're the real uid */ resolve_symlinks_in_ops (); /* Mark everything as slave, so that we still * receive mounts from the real root, but don't * propagate mounts to the real root. */ if (mount (NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) die_with_error ("Failed to make / slave"); /* Create a tmpfs which we will use as / in the namespace */ if (mount ("tmpfs", base_path, "tmpfs", MS_NODEV | MS_NOSUID, NULL) != 0) die_with_error ("Failed to mount tmpfs"); old_cwd = get_current_dir_name (); /* Chdir to the new root tmpfs mount. This will be the CWD during the entire setup. Access old or new root via "oldroot" and "newroot". */ if (chdir (base_path) != 0) die_with_error ("chdir base_path"); /* We create a subdir "$base_path/newroot" for the new root, that * way we can pivot_root to base_path, and put the old root at * "$base_path/oldroot". This avoids problems accessing the oldroot * dir if the user requested to bind mount something over / */ if (mkdir ("newroot", 0755)) die_with_error ("Creating newroot failed"); if (mount ("newroot", "newroot", NULL, MS_MGC_VAL | MS_BIND | MS_REC, NULL) < 0) die_with_error ("setting up newroot bind"); if (mkdir ("oldroot", 0755)) die_with_error ("Creating oldroot failed"); if (pivot_root (base_path, "oldroot")) die_with_error ("pivot_root"); if (chdir ("/") != 0) die_with_error ("chdir / (base path)"); if (is_privileged) { pid_t child; int privsep_sockets[2]; if (socketpair (AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, privsep_sockets) != 0) die_with_error ("Can't create privsep socket"); child = fork (); if (child == -1) die_with_error ("Can't fork unprivileged helper"); if (child == 0) { /* Unprivileged setup process */ drop_privs (FALSE); close (privsep_sockets[0]); setup_newroot (opt_unshare_pid, privsep_sockets[1]); exit (0); } else { int status; uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */ uint32_t op, flags; const char *arg1, *arg2; cleanup_fd int unpriv_socket = -1; unpriv_socket = privsep_sockets[0]; close (privsep_sockets[1]); do { op = read_priv_sec_op (unpriv_socket, buffer, sizeof (buffer), &flags, &arg1, &arg2); privileged_op (-1, op, flags, arg1, arg2); if (write (unpriv_socket, buffer, 1) != 1) die ("Can't write to op_socket"); } while (op != PRIV_SEP_OP_DONE); waitpid (child, &status, 0); /* Continue post setup */ } } else { setup_newroot (opt_unshare_pid, -1); } close_ops_fd (); /* The old root better be rprivate or we will send unmount events to the parent namespace */ if (mount ("oldroot", "oldroot", NULL, MS_REC | MS_PRIVATE, NULL) != 0) die_with_error ("Failed to make old root rprivate"); if (umount2 ("oldroot", MNT_DETACH)) die_with_error ("unmount old root"); /* This is our second pivot. It's like we're a Silicon Valley startup flush * with cash but short on ideas! * * We're aiming to make /newroot the real root, and get rid of /oldroot. To do * that we need a temporary place to store it before we can unmount it. */ { cleanup_fd int oldrootfd = open ("/", O_DIRECTORY | O_RDONLY); if (oldrootfd < 0) die_with_error ("can't open /"); if (chdir ("/newroot") != 0) die_with_error ("chdir /newroot"); /* While the documentation claims that put_old must be underneath * new_root, it is perfectly fine to use the same directory as the * kernel checks only if old_root is accessible from new_root. * * Both runc and LXC are using this "alternative" method for * setting up the root of the container: * * https://github.com/opencontainers/runc/blob/master/libcontainer/rootfs_linux.go#L671 * https://github.com/lxc/lxc/blob/master/src/lxc/conf.c#L1121 */ if (pivot_root (".", ".") != 0) die_with_error ("pivot_root(/newroot)"); if (fchdir (oldrootfd) < 0) die_with_error ("fchdir to oldroot"); if (umount2 (".", MNT_DETACH) < 0) die_with_error ("umount old root"); if (chdir ("/") != 0) die_with_error ("chdir /"); } if (opt_unshare_user && (ns_uid != opt_sandbox_uid || ns_gid != opt_sandbox_gid) && opt_userns_block_fd == -1) { /* Now that devpts is mounted and we've no need for mount permissions we can create a new userspace and map our uid 1:1 */ if (unshare (CLONE_NEWUSER)) die_with_error ("unshare user ns"); write_uid_gid_map (opt_sandbox_uid, ns_uid, opt_sandbox_gid, ns_gid, -1, FALSE, FALSE); } /* All privileged ops are done now, so drop caps we don't need */ drop_privs (!is_privileged); if (opt_block_fd != -1) { char b[1]; (void) TEMP_FAILURE_RETRY (read (opt_block_fd, b, 1)); close (opt_block_fd); } if (opt_seccomp_fd != -1) { seccomp_data = load_file_data (opt_seccomp_fd, &seccomp_len); if (seccomp_data == NULL) die_with_error ("Can't read seccomp data"); if (seccomp_len % 8 != 0) die ("Invalid seccomp data, must be multiple of 8"); seccomp_prog.len = seccomp_len / 8; seccomp_prog.filter = (struct sock_filter *) seccomp_data; close (opt_seccomp_fd); } umask (old_umask); new_cwd = "/"; if (opt_chdir_path) { if (chdir (opt_chdir_path)) die_with_error ("Can't chdir to %s", opt_chdir_path); new_cwd = opt_chdir_path; } else if (chdir (old_cwd) == 0) { /* If the old cwd is mapped in the sandbox, go there */ new_cwd = old_cwd; } else { /* If the old cwd is not mapped, go to home */ const char *home = getenv ("HOME"); if (home != NULL && chdir (home) == 0) new_cwd = home; } xsetenv ("PWD", new_cwd, 1); free (old_cwd); if (opt_new_session && setsid () == (pid_t) -1) die_with_error ("setsid"); if (label_exec (opt_exec_label) == -1) die_with_error ("label_exec %s", argv[0]); __debug__ (("forking for child\n")); if (!opt_as_pid_1 && (opt_unshare_pid || lock_files != NULL || opt_sync_fd != -1)) { /* We have to have a pid 1 in the pid namespace, because * otherwise we'll get a bunch of zombies as nothing reaps * them. Alternatively if we're using sync_fd or lock_files we * need some process to own these. */ pid = fork (); if (pid == -1) die_with_error ("Can't fork for pid 1"); if (pid != 0) { drop_all_caps (FALSE); /* Close fds in pid 1, except stdio and optionally event_fd (for syncing pid 2 lifetime with monitor_child) and opt_sync_fd (for syncing sandbox lifetime with outside process). Any other fds will been passed on to the child though. */ { int dont_close[3]; int j = 0; if (event_fd != -1) dont_close[j++] = event_fd; if (opt_sync_fd != -1) dont_close[j++] = opt_sync_fd; dont_close[j++] = -1; fdwalk (proc_fd, close_extra_fds, dont_close); } return do_init (event_fd, pid, seccomp_data != NULL ? &seccomp_prog : NULL); } } __debug__ (("launch executable %s\n", argv[0])); if (proc_fd != -1) close (proc_fd); /* If we are using --as-pid-1 leak the sync fd into the sandbox. --sync-fd will still work unless the container process doesn't close this file. */ if (!opt_as_pid_1) { if (opt_sync_fd != -1) close (opt_sync_fd); } /* We want sigchild in the child */ unblock_sigchild (); /* Optionally bind our lifecycle */ handle_die_with_parent (); if (!is_privileged) set_ambient_capabilities (); /* Should be the last thing before execve() so that filters don't * need to handle anything above */ if (seccomp_data != NULL && prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &seccomp_prog) != 0) die_with_error ("prctl(PR_SET_SECCOMP)"); if (setup_finished_pipe[1] != -1) { char data = 0; res = write_to_fd (setup_finished_pipe[1], &data, 1); /* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0] we don't want to error out here */ } if (execvp (argv[0], argv) == -1) { if (setup_finished_pipe[1] != -1) { int saved_errno = errno; char data = 0; res = write_to_fd (setup_finished_pipe[1], &data, 1); errno = saved_errno; /* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0] we don't want to error out here */ } die_with_error ("execvp %s", argv[0]); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-269'], 'message': 'Don't create our own temporary mount point for pivot_root An attacker could pre-create /tmp/.bubblewrap-$UID and make it a non-directory, non-symlink (in which case mounting our tmpfs would fail, causing denial of service), or make it a symlink under their control (potentially allowing bad things if the protected_symlinks sysctl is not enabled). Instead, temporarily mount the tmpfs on a directory that we are sure exists and is not attacker-controlled. /tmp (the directory itself, not a subdirectory) will do. Fixes: #304 Bug-Debian: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=923557 Signed-off-by: Simon McVittie <smcv@debian.org> Closes: #305 Approved by: cgwalters'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: find_lively_task_by_vpid(pid_t vpid) { struct task_struct *task; int err; rcu_read_lock(); if (!vpid) task = current; else task = find_task_by_vpid(vpid); if (task) get_task_struct(task); rcu_read_unlock(); if (!task) return ERR_PTR(-ESRCH); /* Reuse ptrace permission checks for now. */ err = -EACCES; if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) goto errout; return task; errout: put_task_struct(task); return ERR_PTR(err); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-667'], 'message': 'perf/core: Fix perf_event_open() vs. execve() race Jann reported that the ptrace_may_access() check in find_lively_task_by_vpid() is racy against exec(). Specifically: perf_event_open() execve() ptrace_may_access() commit_creds() ... if (get_dumpable() != SUID_DUMP_USER) perf_event_exit_task(); perf_install_in_context() would result in installing a counter across the creds boundary. Fix this by wrapping lots of perf_event_open() in cred_guard_mutex. This should be fine as perf_event_exit_task() is already called with cred_guard_mutex held, so all perf locks already nest inside it. Reported-by: Jann Horn <jannh@google.com> Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org> Cc: Alexander Shishkin <alexander.shishkin@linux.intel.com> Cc: Arnaldo Carvalho de Melo <acme@redhat.com> Cc: Jiri Olsa <jolsa@redhat.com> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Stephane Eranian <eranian@google.com> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: Vince Weaver <vincent.weaver@maine.edu> Signed-off-by: Ingo Molnar <mingo@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void exif_process_CME (image_info_type *image_info, char *value, size_t length) { if (length>3) { switch(value[2]) { case 0: exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_UNDEFINED, length, value); break; case 1: exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length, value); break; default: php_error_docref(NULL, E_NOTICE, "Undefined JPEG2000 comment encoding"); break; } } else { exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_UNDEFINED, 0, NULL); php_error_docref(NULL, E_NOTICE, "JPEG2000 comment section too small"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed bug #77831 - Heap-buffer-overflow in exif_iif_add_value in EXIF'</s>
<s>[INST] Given the following code containing errors, provide 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 setup_private_mount(const char *snap_name) { uid_t uid = getuid(); gid_t gid = getgid(); char tmpdir[MAX_BUF] = { 0 }; // Create a 0700 base directory, this is the base dir that is // protected from other users. // // Under that basedir, we put a 1777 /tmp dir that is then bind // mounted for the applications to use sc_must_snprintf(tmpdir, sizeof(tmpdir), "/tmp/snap.%s_XXXXXX", snap_name); if (mkdtemp(tmpdir) == NULL) { die("cannot create temporary directory essential for private /tmp"); } // now we create a 1777 /tmp inside our private dir mode_t old_mask = umask(0); char *d = sc_strdup(tmpdir); sc_must_snprintf(tmpdir, sizeof(tmpdir), "%s/tmp", d); free(d); if (mkdir(tmpdir, 01777) != 0) { die("cannot create temporary directory for private /tmp"); } umask(old_mask); // chdir to '/' since the mount won't apply to the current directory char *pwd = get_current_dir_name(); if (pwd == NULL) die("cannot get current working directory"); if (chdir("/") != 0) die("cannot change directory to '/'"); // MS_BIND is there from linux 2.4 sc_do_mount(tmpdir, "/tmp", NULL, MS_BIND, NULL); // MS_PRIVATE needs linux > 2.6.11 sc_do_mount("none", "/tmp", NULL, MS_PRIVATE, NULL); // do the chown after the bind mount to avoid potential shenanigans if (chown("/tmp/", uid, gid) < 0) { die("cannot change ownership of /tmp"); } // chdir to original directory if (chdir(pwd) != 0) die("cannot change current working directory to the original directory"); free(pwd); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-703'], 'message': 'cmd/snap-confine: chown private /tmp parent to root.root When snap-confine creates a private /tmp directory for a given snap it first creates a temporary directory in /tmp/ named after the snap, along with a random name. Inside that directory it creates a /tmp directory with permissions appropriate for a future /tmp, namely 1777. Up until recently the that directory was owned by the user who first invoked snap-confine. Since the directory is reused by all the users on the system this logic makes no sense. This patch changes the related logic so that the private /tmp directory is owned by root, just like the real one. Signed-off-by: Zygmunt Krynicki <zygmunt.krynicki@canonical.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: find_extend_vma(struct mm_struct *mm, unsigned long addr) { struct vm_area_struct *vma; unsigned long start; addr &= PAGE_MASK; vma = find_vma(mm, addr); if (!vma) return NULL; if (vma->vm_start <= addr) return vma; if (!(vma->vm_flags & VM_GROWSDOWN)) return NULL; start = vma->vm_start; if (expand_stack(vma, addr)) return NULL; if (vma->vm_flags & VM_LOCKED) populate_vma_page_range(vma, addr, start, NULL); return vma; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-703', 'CWE-667'], 'message': 'coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping The core dumping code has always run without holding the mmap_sem for writing, despite that is the only way to ensure that the entire vma layout will not change from under it. Only using some signal serialization on the processes belonging to the mm is not nearly enough. This was pointed out earlier. For example in Hugh's post from Jul 2017: https://lkml.kernel.org/r/alpine.LSU.2.11.1707191716030.2055@eggly.anvils "Not strictly relevant here, but a related note: I was very surprised to discover, only quite recently, how handle_mm_fault() may be called without down_read(mmap_sem) - when core dumping. That seems a misguided optimization to me, which would also be nice to correct" In particular because the growsdown and growsup can move the vm_start/vm_end the various loops the core dump does around the vma will not be consistent if page faults can happen concurrently. Pretty much all users calling mmget_not_zero()/get_task_mm() and then taking the mmap_sem had the potential to introduce unexpected side effects in the core dumping code. Adding mmap_sem for writing around the ->core_dump invocation is a viable long term fix, but it requires removing all copy user and page faults and to replace them with get_dump_page() for all binary formats which is not suitable as a short term fix. For the time being this solution manually covers the places that can confuse the core dump either by altering the vma layout or the vma flags while it runs. Once ->core_dump runs under mmap_sem for writing the function mmget_still_valid() can be dropped. Allowing mmap_sem protected sections to run in parallel with the coredump provides some minor parallelism advantage to the swapoff code (which seems to be safe enough by never mangling any vma field and can keep doing swapins in parallel to the core dumping) and to some other corner case. In order to facilitate the backporting I added "Fixes: 86039bd3b4e6" however the side effect of this same race condition in /proc/pid/mem should be reproducible since before 2.6.12-rc2 so I couldn't add any other "Fixes:" because there's no hash beyond the git genesis commit. Because find_extend_vma() is the only location outside of the process context that could modify the "mm" structures under mmap_sem for reading, by adding the mmget_still_valid() check to it, all other cases that take the mmap_sem for reading don't need the new check after mmget_not_zero()/get_task_mm(). The expand_stack() in page fault context also doesn't need the new check, because all tasks under core dumping are frozen. Link: http://lkml.kernel.org/r/20190325224949.11068-1-aarcange@redhat.com Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization") Signed-off-by: Andrea Arcangeli <aarcange@redhat.com> Reported-by: Jann Horn <jannh@google.com> Suggested-by: Oleg Nesterov <oleg@redhat.com> Acked-by: Peter Xu <peterx@redhat.com> Reviewed-by: Mike Rapoport <rppt@linux.ibm.com> Reviewed-by: Oleg Nesterov <oleg@redhat.com> Reviewed-by: Jann Horn <jannh@google.com> Acked-by: Jason Gunthorpe <jgg@mellanox.com> Acked-by: Michal Hocko <mhocko@suse.com> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadXWDImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CheckOverflowException(length,width,height) \ (((height) != 0) && ((length)/((size_t) height) != ((size_t) width))) char *comment; Image *image; IndexPacket index; int x_status; MagickBooleanType authentic_colormap; MagickStatusType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register size_t pixel; size_t length; ssize_t count, y; unsigned long lsb_first; XColor *colors; XImage *ximage; XWDFileHeader header; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read in header information. */ count=ReadBlob(image,sz_XWDheader,(unsigned char *) &header); if (count != sz_XWDheader) ThrowReaderException(CorruptImageError,"UnableToReadImageHeader"); /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) MSBOrderLong((unsigned char *) &header,sz_XWDheader); /* Check to see if the dump file is in the proper format. */ if (header.file_version != XWD_FILE_VERSION) ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch"); if (header.header_size < sz_XWDheader) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((header.bits_per_pixel == 0) || (header.bits_per_pixel > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (header.bitmap_unit > 32) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (header.ncolors > 256) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); switch (header.visual_class) { case StaticGray: case GrayScale: case StaticColor: case PseudoColor: case TrueColor: case DirectColor: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.pixmap_format) { case XYBitmap: case XYPixmap: case ZPixmap: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } length=(size_t) (header.header_size-sz_XWDheader); if ((length+1) != ((size_t) ((CARD32) (length+1)))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); comment=(char *) AcquireQuantumMemory(length+1,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length,(unsigned char *) comment); comment[length]='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); /* Initialize the X image. */ ximage=(XImage *) AcquireMagickMemory(sizeof(*ximage)); if (ximage == (XImage *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ximage->depth=(int) header.pixmap_depth; ximage->format=(int) header.pixmap_format; ximage->xoffset=(int) header.xoffset; ximage->data=(char *) NULL; ximage->width=(int) header.pixmap_width; ximage->height=(int) header.pixmap_height; ximage->bitmap_pad=(int) header.bitmap_pad; ximage->bytes_per_line=(int) header.bytes_per_line; ximage->byte_order=(int) header.byte_order; ximage->bitmap_unit=(int) header.bitmap_unit; ximage->bitmap_bit_order=(int) header.bitmap_bit_order; ximage->bits_per_pixel=(int) header.bits_per_pixel; ximage->red_mask=header.red_mask; ximage->green_mask=header.green_mask; ximage->blue_mask=header.blue_mask; if ((ximage->width < 0) || (ximage->height < 0) || (ximage->depth < 0) || (ximage->format < 0) || (ximage->byte_order < 0) || (ximage->bitmap_bit_order < 0) || (ximage->bitmap_pad < 0) || (ximage->bytes_per_line < 0)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->width > 65535) || (ximage->height > 65535)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->bits_per_pixel > 32) || (ximage->bitmap_unit > 32)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } x_status=XInitImage(ximage); if (x_status == 0) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } /* Read colormap. */ authentic_colormap=MagickFalse; colors=(XColor *) NULL; if (header.ncolors != 0) { XWDColor color; length=(size_t) header.ncolors; if (length > ((~0UL)/sizeof(*colors))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); colors=(XColor *) AcquireQuantumMemory(length,sizeof(*colors)); if (colors == (XColor *) NULL) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) header.ncolors; i++) { count=ReadBlob(image,sz_XWDColor,(unsigned char *) &color); if (count != sz_XWDColor) { colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } colors[i].pixel=color.pixel; colors[i].red=color.red; colors[i].green=color.green; colors[i].blue=color.blue; colors[i].flags=(char) color.flags; if (color.flags != 0) authentic_colormap=MagickTrue; } /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) for (i=0; i < (ssize_t) header.ncolors; i++) { MSBOrderLong((unsigned char *) &colors[i].pixel, sizeof(colors[i].pixel)); MSBOrderShort((unsigned char *) &colors[i].red,3* sizeof(colors[i].red)); } } /* Allocate the pixel buffer. */ length=(size_t) ximage->bytes_per_line*ximage->height; if (CheckOverflowException(length,ximage->bytes_per_line,ximage->height)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (ximage->format != ZPixmap) { size_t extent; extent=length; length*=ximage->depth; if (CheckOverflowException(length,extent,ximage->depth)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } ximage->data=(char *) AcquireQuantumMemory(length,sizeof(*ximage->data)); if (ximage->data == (char *) NULL) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } count=ReadBlob(image,length,(unsigned char *) ximage->data); if (count != (ssize_t) length) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } /* Convert image to MIFF format. */ image->columns=(size_t) ximage->width; image->rows=(size_t) ximage->height; image->depth=8; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((header.ncolors == 0U) || (ximage->red_mask != 0) || (ximage->green_mask != 0) || (ximage->blue_mask != 0)) image->storage_class=DirectClass; else image->storage_class=PseudoClass; image->colors=header.ncolors; if (image_info->ping == MagickFalse) switch (image->storage_class) { case DirectClass: default: { register size_t color; size_t blue_mask, blue_shift, green_mask, green_shift, red_mask, red_shift; /* Determine shift and mask for red, green, and blue. */ red_mask=ximage->red_mask; red_shift=0; while ((red_mask != 0) && ((red_mask & 0x01) == 0)) { red_mask>>=1; red_shift++; } green_mask=ximage->green_mask; green_shift=0; while ((green_mask != 0) && ((green_mask & 0x01) == 0)) { green_mask>>=1; green_shift++; } blue_mask=ximage->blue_mask; blue_shift=0; while ((blue_mask != 0) && ((blue_mask & 0x01) == 0)) { blue_mask>>=1; blue_shift++; } /* Convert X image to DirectClass packets. */ if ((image->colors != 0) && (authentic_colormap != MagickFalse)) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> red_shift) & red_mask); SetPixelRed(q,ScaleShortToQuantum(colors[(ssize_t) index].red)); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> green_shift) & green_mask); SetPixelGreen(q,ScaleShortToQuantum(colors[(ssize_t) index].green)); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> blue_shift) & blue_mask); SetPixelBlue(q,ScaleShortToQuantum(colors[(ssize_t) index].blue)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); color=(pixel >> red_shift) & red_mask; if (red_mask != 0) color=(color*65535UL)/red_mask; SetPixelRed(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> green_shift) & green_mask; if (green_mask != 0) color=(color*65535UL)/green_mask; SetPixelGreen(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> blue_shift) & blue_mask; if (blue_mask != 0) color=(color*65535UL)/blue_mask; SetPixelBlue(q,ScaleShortToQuantum((unsigned short) color)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } case PseudoClass: { /* Convert X image to PseudoClass packets. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleShortToQuantum(colors[i].red); image->colormap[i].green=ScaleShortToQuantum(colors[i].green); image->colormap[i].blue=ScaleShortToQuantum(colors[i].blue); } for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,(ssize_t) XGetPixel(ximage,(int) x,(int) y)); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } } /* Free image and colormap. */ if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1546'</s>
<s>[INST] Given the following code containing errors, provide 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 rds_tcp_kill_sock(struct net *net) { struct rds_tcp_connection *tc, *_tc; LIST_HEAD(tmp_list); struct rds_tcp_net *rtn = net_generic(net, rds_tcp_netid); struct socket *lsock = rtn->rds_tcp_listen_sock; rtn->rds_tcp_listen_sock = NULL; rds_tcp_listen_stop(lsock, &rtn->rds_tcp_accept_w); spin_lock_irq(&rds_tcp_conn_lock); list_for_each_entry_safe(tc, _tc, &rds_tcp_conn_list, t_tcp_node) { struct net *c_net = read_pnet(&tc->t_cpath->cp_conn->c_net); if (net != c_net || !tc->t_sock) continue; if (!list_has_conn(&tmp_list, tc->t_cpath->cp_conn)) { list_move_tail(&tc->t_tcp_node, &tmp_list); } else { list_del(&tc->t_tcp_node); tc->t_tcp_node_detached = true; } } spin_unlock_irq(&rds_tcp_conn_lock); list_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node) rds_conn_destroy(tc->t_cpath->cp_conn); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'net: rds: force to destroy connection if t_sock is NULL in rds_tcp_kill_sock(). When it is to cleanup net namespace, rds_tcp_exit_net() will call rds_tcp_kill_sock(), if t_sock is NULL, it will not call rds_conn_destroy(), rds_conn_path_destroy() and rds_tcp_conn_free() to free connection, and the worker cp_conn_w is not stopped, afterwards the net is freed in net_drop_ns(); While cp_conn_w rds_connect_worker() will call rds_tcp_conn_path_connect() and reference 'net' which has already been freed. In rds_tcp_conn_path_connect(), rds_tcp_set_callbacks() will set t_sock = sock before sock->ops->connect, but if connect() is failed, it will call rds_tcp_restore_callbacks() and set t_sock = NULL, if connect is always failed, rds_connect_worker() will try to reconnect all the time, so rds_tcp_kill_sock() will never to cancel worker cp_conn_w and free the connections. Therefore, the condition !tc->t_sock is not needed if it is going to do cleanup_net->rds_tcp_exit_net->rds_tcp_kill_sock, because tc->t_sock is always NULL, and there is on other path to cancel cp_conn_w and free connection. So this patch is to fix this. rds_tcp_kill_sock(): ... if (net != c_net || !tc->t_sock) ... Acked-by: Santosh Shilimkar <santosh.shilimkar@oracle.com> ================================================================== BUG: KASAN: use-after-free in inet_create+0xbcc/0xd28 net/ipv4/af_inet.c:340 Read of size 4 at addr ffff8003496a4684 by task kworker/u8:4/3721 CPU: 3 PID: 3721 Comm: kworker/u8:4 Not tainted 5.1.0 #11 Hardware name: linux,dummy-virt (DT) Workqueue: krdsd rds_connect_worker Call trace: dump_backtrace+0x0/0x3c0 arch/arm64/kernel/time.c:53 show_stack+0x28/0x38 arch/arm64/kernel/traps.c:152 __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0x120/0x188 lib/dump_stack.c:113 print_address_description+0x68/0x278 mm/kasan/report.c:253 kasan_report_error mm/kasan/report.c:351 [inline] kasan_report+0x21c/0x348 mm/kasan/report.c:409 __asan_report_load4_noabort+0x30/0x40 mm/kasan/report.c:429 inet_create+0xbcc/0xd28 net/ipv4/af_inet.c:340 __sock_create+0x4f8/0x770 net/socket.c:1276 sock_create_kern+0x50/0x68 net/socket.c:1322 rds_tcp_conn_path_connect+0x2b4/0x690 net/rds/tcp_connect.c:114 rds_connect_worker+0x108/0x1d0 net/rds/threads.c:175 process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153 worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296 kthread+0x2f0/0x378 kernel/kthread.c:255 ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117 Allocated by task 687: save_stack mm/kasan/kasan.c:448 [inline] set_track mm/kasan/kasan.c:460 [inline] kasan_kmalloc+0xd4/0x180 mm/kasan/kasan.c:553 kasan_slab_alloc+0x14/0x20 mm/kasan/kasan.c:490 slab_post_alloc_hook mm/slab.h:444 [inline] slab_alloc_node mm/slub.c:2705 [inline] slab_alloc mm/slub.c:2713 [inline] kmem_cache_alloc+0x14c/0x388 mm/slub.c:2718 kmem_cache_zalloc include/linux/slab.h:697 [inline] net_alloc net/core/net_namespace.c:384 [inline] copy_net_ns+0xc4/0x2d0 net/core/net_namespace.c:424 create_new_namespaces+0x300/0x658 kernel/nsproxy.c:107 unshare_nsproxy_namespaces+0xa0/0x198 kernel/nsproxy.c:206 ksys_unshare+0x340/0x628 kernel/fork.c:2577 __do_sys_unshare kernel/fork.c:2645 [inline] __se_sys_unshare kernel/fork.c:2643 [inline] __arm64_sys_unshare+0x38/0x58 kernel/fork.c:2643 __invoke_syscall arch/arm64/kernel/syscall.c:35 [inline] invoke_syscall arch/arm64/kernel/syscall.c:47 [inline] el0_svc_common+0x168/0x390 arch/arm64/kernel/syscall.c:83 el0_svc_handler+0x60/0xd0 arch/arm64/kernel/syscall.c:129 el0_svc+0x8/0xc arch/arm64/kernel/entry.S:960 Freed by task 264: save_stack mm/kasan/kasan.c:448 [inline] set_track mm/kasan/kasan.c:460 [inline] __kasan_slab_free+0x114/0x220 mm/kasan/kasan.c:521 kasan_slab_free+0x10/0x18 mm/kasan/kasan.c:528 slab_free_hook mm/slub.c:1370 [inline] slab_free_freelist_hook mm/slub.c:1397 [inline] slab_free mm/slub.c:2952 [inline] kmem_cache_free+0xb8/0x3a8 mm/slub.c:2968 net_free net/core/net_namespace.c:400 [inline] net_drop_ns.part.6+0x78/0x90 net/core/net_namespace.c:407 net_drop_ns net/core/net_namespace.c:406 [inline] cleanup_net+0x53c/0x6d8 net/core/net_namespace.c:569 process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153 worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296 kthread+0x2f0/0x378 kernel/kthread.c:255 ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117 The buggy address belongs to the object at ffff8003496a3f80 which belongs to the cache net_namespace of size 7872 The buggy address is located 1796 bytes inside of 7872-byte region [ffff8003496a3f80, ffff8003496a5e40) The buggy address belongs to the page: page:ffff7e000d25a800 count:1 mapcount:0 mapping:ffff80036ce4b000 index:0x0 compound_mapcount: 0 flags: 0xffffe0000008100(slab|head) raw: 0ffffe0000008100 dead000000000100 dead000000000200 ffff80036ce4b000 raw: 0000000000000000 0000000080040004 00000001ffffffff 0000000000000000 page dumped because: kasan: bad access detected Memory state around the buggy address: ffff8003496a4580: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8003496a4600: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb >ffff8003496a4680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ^ ffff8003496a4700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8003496a4780: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ================================================================== Fixes: 467fa15356ac("RDS-TCP: Support multiple RDS-TCP listen endpoints, one per netns.") Reported-by: Hulk Robot <hulkci@huawei.com> Signed-off-by: Mao Wenan <maowenan@huawei.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ipmi_si_port_setup(struct si_sm_io *io) { unsigned int addr = io->addr_data; int idx; if (!addr) return -ENODEV; io->io_cleanup = port_cleanup; /* * Figure out the actual inb/inw/inl/etc routine to use based * upon the register size. */ switch (io->regsize) { case 1: io->inputb = port_inb; io->outputb = port_outb; break; case 2: io->inputb = port_inw; io->outputb = port_outw; break; case 4: io->inputb = port_inl; io->outputb = port_outl; break; default: dev_warn(io->dev, "Invalid register size: %d\n", io->regsize); return -EINVAL; } /* * Some BIOSes reserve disjoint I/O regions in their ACPI * tables. This causes problems when trying to register the * entire I/O region. Therefore we must register each I/O * port separately. */ for (idx = 0; idx < io->io_size; idx++) { if (request_region(addr + idx * io->regspacing, io->regsize, DEVICE_NAME) == NULL) { /* Undo allocations */ while (idx--) release_region(addr + idx * io->regspacing, io->regsize); return -EIO; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'ipmi_si: fix use-after-free of resource->name When we excute the following commands, we got oops rmmod ipmi_si cat /proc/ioports [ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478 [ 1623.482382] Mem abort info: [ 1623.482383] ESR = 0x96000007 [ 1623.482385] Exception class = DABT (current EL), IL = 32 bits [ 1623.482386] SET = 0, FnV = 0 [ 1623.482387] EA = 0, S1PTW = 0 [ 1623.482388] Data abort info: [ 1623.482389] ISV = 0, ISS = 0x00000007 [ 1623.482390] CM = 0, WnR = 0 [ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66 [ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000 [ 1623.482399] Internal error: Oops: 96000007 [#1] SMP [ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si] [ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168 [ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017 [ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO) [ 1623.553684] pc : string+0x28/0x98 [ 1623.557040] lr : vsnprintf+0x368/0x5e8 [ 1623.560837] sp : ffff000013213a80 [ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5 [ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049 [ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5 [ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000 [ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000 [ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff [ 1623.596505] x17: 0000000000000200 x16: 0000000000000000 [ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000 [ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000 [ 1623.612661] x11: 0000000000000000 x10: 0000000000000000 [ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f [ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe [ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478 [ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000 [ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff [ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10) [ 1623.651592] Call trace: [ 1623.654068] string+0x28/0x98 [ 1623.657071] vsnprintf+0x368/0x5e8 [ 1623.660517] seq_vprintf+0x70/0x98 [ 1623.668009] seq_printf+0x7c/0xa0 [ 1623.675530] r_show+0xc8/0xf8 [ 1623.682558] seq_read+0x330/0x440 [ 1623.689877] proc_reg_read+0x78/0xd0 [ 1623.697346] __vfs_read+0x60/0x1a0 [ 1623.704564] vfs_read+0x94/0x150 [ 1623.711339] ksys_read+0x6c/0xd8 [ 1623.717939] __arm64_sys_read+0x24/0x30 [ 1623.725077] el0_svc_common+0x120/0x148 [ 1623.732035] el0_svc_handler+0x30/0x40 [ 1623.738757] el0_svc+0x8/0xc [ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085) [ 1623.753441] ---[ end trace f91b6a4937de9835 ]--- [ 1623.760871] Kernel panic - not syncing: Fatal exception [ 1623.768935] SMP: stopping secondary CPUs [ 1623.775718] Kernel Offset: disabled [ 1623.781998] CPU features: 0x002,21006008 [ 1623.788777] Memory Limit: none [ 1623.798329] Starting crashdump kernel... [ 1623.805202] Bye! If io_setup is called successful in try_smi_init() but try_smi_init() goes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi() will not be called while removing module. It leads to the resource that allocated in io_setup() can not be freed, but the name(DEVICE_NAME) of resource is freed while removing the module. It causes use-after-free when cat /proc/ioports. Fix this by calling io_cleanup() while try_smi_init() goes to out_err. and don't call io_cleanup() until io_setup() returns successful to avoid warning prints. Fixes: 93c303d2045b ("ipmi_si: Clean up shutdown a bit") Cc: stable@vger.kernel.org Reported-by: NuoHan Qiao <qiaonuohan@huawei.com> Suggested-by: Corey Minyard <cminyard@mvista.com> Signed-off-by: Yang Yingliang <yangyingliang@huawei.com> Signed-off-by: Corey Minyard <cminyard@mvista.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: upnp_redirect(const char * rhost, unsigned short eport, const char * iaddr, unsigned short iport, const char * protocol, const char * desc, unsigned int leaseduration) { int proto, r; char iaddr_old[32]; char rhost_old[32]; unsigned short iport_old; struct in_addr address; unsigned int timestamp; proto = proto_atoi(protocol); if(inet_aton(iaddr, &address) <= 0) { syslog(LOG_ERR, "inet_aton(%s) FAILED", iaddr); return -1; } if(!check_upnp_rule_against_permissions(upnppermlist, num_upnpperm, eport, address, iport)) { syslog(LOG_INFO, "redirection permission check failed for " "%hu->%s:%hu %s", eport, iaddr, iport, protocol); return -3; } /* IGDv1 (WANIPConnection:1 Service Template Version 1.01 / Nov 12, 2001) * - 2.2.20.PortMappingDescription : * Overwriting Previous / Existing Port Mappings: * If the RemoteHost, ExternalPort, PortMappingProtocol and InternalClient * are exactly the same as an existing mapping, the existing mapping values * for InternalPort, PortMappingDescription, PortMappingEnabled and * PortMappingLeaseDuration are overwritten. * Rejecting a New Port Mapping: * In cases where the RemoteHost, ExternalPort and PortMappingProtocol * are the same as an existing mapping, but the InternalClient is * different, the action is rejected with an appropriate error. * Add or Reject New Port Mapping behavior based on vendor implementation: * In cases where the ExternalPort, PortMappingProtocol and InternalClient * are the same, but RemoteHost is different, the vendor can choose to * support both mappings simultaneously, or reject the second mapping * with an appropriate error. * * - 2.4.16.AddPortMapping * This action creates a new port mapping or overwrites an existing * mapping with the same internal client. If the ExternalPort and * PortMappingProtocol pair is already mapped to another internal client, * an error is returned. * * IGDv2 (WANIPConnection:2 Service Standardized DCP (SDCP) Sep 10, 2010) * Protocol ExternalPort RemoteHost InternalClient Result * = = ≠ ≠ Failure * = = ≠ = Failure or success * (vendor specific) * = = = ≠ Failure * = = = = Success (overwrite) */ rhost_old[0] = '\0'; r = get_redirect_rule(ext_if_name, eport, proto, iaddr_old, sizeof(iaddr_old), &iport_old, 0, 0, rhost_old, sizeof(rhost_old), &timestamp, 0, 0); if(r == 0) { if(strcmp(iaddr, iaddr_old)==0 && ((rhost == NULL && rhost_old[0]=='\0') || (rhost && (strcmp(rhost, "*") == 0) && rhost_old[0]=='\0') || (rhost && (strcmp(rhost, rhost_old) == 0)))) { syslog(LOG_INFO, "updating existing port mapping %hu %s (rhost '%s') => %s:%hu", eport, protocol, rhost_old, iaddr_old, iport_old); timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0; if(iport != iport_old) { r = update_portmapping(ext_if_name, eport, proto, iport, desc, timestamp); } else { r = update_portmapping_desc_timestamp(ext_if_name, eport, proto, desc, timestamp); } #ifdef ENABLE_LEASEFILE if(r == 0) { lease_file_remove(eport, proto); lease_file_add(eport, iaddr, iport, proto, desc, timestamp); } #endif /* ENABLE_LEASEFILE */ return r; } else { syslog(LOG_INFO, "port %hu %s (rhost '%s') already redirected to %s:%hu", eport, protocol, rhost_old, iaddr_old, iport_old); return -2; } #ifdef CHECK_PORTINUSE } else if (port_in_use(ext_if_name, eport, proto, iaddr, iport) > 0) { syslog(LOG_INFO, "port %hu protocol %s already in use", eport, protocol); return -4; #endif /* CHECK_PORTINUSE */ } else { timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0; syslog(LOG_INFO, "redirecting port %hu to %s:%hu protocol %s for: %s", eport, iaddr, iport, protocol, desc); return upnp_redirect_internal(rhost, eport, iaddr, iport, proto, desc, timestamp); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'upnp_redirect(): accept NULL desc argument'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: con_insert_unipair(struct uni_pagedir *p, u_short unicode, u_short fontpos) { int i, n; u16 **p1, *p2; p1 = p->uni_pgdir[n = unicode >> 11]; if (!p1) { p1 = p->uni_pgdir[n] = kmalloc_array(32, sizeof(u16 *), GFP_KERNEL); if (!p1) return -ENOMEM; for (i = 0; i < 32; i++) p1[i] = NULL; } p2 = p1[n = (unicode >> 6) & 0x1f]; if (!p2) { p2 = p1[n] = kmalloc_array(64, sizeof(u16), GFP_KERNEL); if (!p2) return -ENOMEM; memset(p2, 0xff, 64*sizeof(u16)); /* No glyphs for the characters (yet) */ } p2[unicode & 0x3f] = fontpos; p->sum += (fontpos << 20) + unicode; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'consolemap: Fix a memory leaking bug in drivers/tty/vt/consolemap.c In function con_insert_unipair(), when allocation for p2 and p1[n] fails, ENOMEM is returned, but previously allocated p1 is not freed, remains as leaking memory. Thus we should free p1 as well when this allocation fails. Signed-off-by: Gen Zhang <blackgod016574@gmail.com> Reviewed-by: Kees Cook <keescook@chromium.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: exsltDynMapFunction(xmlXPathParserContextPtr ctxt, int nargs) { xmlChar *str = NULL; xmlNodeSetPtr nodeset = NULL; xsltTransformContextPtr tctxt; xmlXPathCompExprPtr comp = NULL; xmlXPathObjectPtr ret = NULL; xmlDocPtr oldDoc, container = NULL; xmlNodePtr oldNode; int oldContextSize; int oldProximityPosition; int i, j; if (nargs != 2) { xmlXPathSetArityError(ctxt); return; } str = xmlXPathPopString(ctxt); if (xmlXPathCheckError(ctxt)) { xmlXPathSetTypeError(ctxt); return; } nodeset = xmlXPathPopNodeSet(ctxt); if (xmlXPathCheckError(ctxt)) { xmlXPathSetTypeError(ctxt); return; } if (str == NULL || !xmlStrlen(str) || !(comp = xmlXPathCompile(str))) { if (nodeset != NULL) xmlXPathFreeNodeSet(nodeset); if (str != NULL) xmlFree(str); valuePush(ctxt, xmlXPathNewNodeSet(NULL)); return; } ret = xmlXPathNewNodeSet(NULL); if (ret == NULL) { xsltGenericError(xsltGenericErrorContext, "exsltDynMapFunction: ret == NULL\n"); goto cleanup; } oldDoc = ctxt->context->doc; oldNode = ctxt->context->node; oldContextSize = ctxt->context->contextSize; oldProximityPosition = ctxt->context->proximityPosition; /** * since we really don't know we're going to be adding node(s) * down the road we create the RVT regardless */ tctxt = xsltXPathGetTransformContext(ctxt); if (tctxt == NULL) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "dyn:map : internal error tctxt == NULL\n"); goto cleanup; } container = xsltCreateRVT(tctxt); if (container == NULL) { xsltTransformError(tctxt, NULL, NULL, "dyn:map : internal error container == NULL\n"); goto cleanup; } xsltRegisterLocalRVT(tctxt, container); if (nodeset && nodeset->nodeNr > 0) { xmlXPathNodeSetSort(nodeset); ctxt->context->contextSize = nodeset->nodeNr; ctxt->context->proximityPosition = 0; for (i = 0; i < nodeset->nodeNr; i++) { xmlXPathObjectPtr subResult = NULL; ctxt->context->proximityPosition++; ctxt->context->node = nodeset->nodeTab[i]; ctxt->context->doc = nodeset->nodeTab[i]->doc; subResult = xmlXPathCompiledEval(comp, ctxt->context); if (subResult != NULL) { switch (subResult->type) { case XPATH_NODESET: if (subResult->nodesetval != NULL) for (j = 0; j < subResult->nodesetval->nodeNr; j++) xmlXPathNodeSetAdd(ret->nodesetval, subResult->nodesetval-> nodeTab[j]); break; case XPATH_BOOLEAN: if (container != NULL) { xmlNodePtr cur = xmlNewChild((xmlNodePtr) container, NULL, BAD_CAST "boolean", BAD_CAST (subResult-> boolval ? "true" : "")); if (cur != NULL) { cur->ns = xmlNewNs(cur, BAD_CAST "http://exslt.org/common", BAD_CAST "exsl"); xmlXPathNodeSetAddUnique(ret->nodesetval, cur); } xsltExtensionInstructionResultRegister(tctxt, ret); } break; case XPATH_NUMBER: if (container != NULL) { xmlChar *val = xmlXPathCastNumberToString(subResult-> floatval); xmlNodePtr cur = xmlNewChild((xmlNodePtr) container, NULL, BAD_CAST "number", val); if (val != NULL) xmlFree(val); if (cur != NULL) { cur->ns = xmlNewNs(cur, BAD_CAST "http://exslt.org/common", BAD_CAST "exsl"); xmlXPathNodeSetAddUnique(ret->nodesetval, cur); } xsltExtensionInstructionResultRegister(tctxt, ret); } break; case XPATH_STRING: if (container != NULL) { xmlNodePtr cur = xmlNewChild((xmlNodePtr) container, NULL, BAD_CAST "string", subResult->stringval); if (cur != NULL) { cur->ns = xmlNewNs(cur, BAD_CAST "http://exslt.org/common", BAD_CAST "exsl"); xmlXPathNodeSetAddUnique(ret->nodesetval, cur); } xsltExtensionInstructionResultRegister(tctxt, ret); } break; default: break; } xmlXPathFreeObject(subResult); } } } ctxt->context->doc = oldDoc; ctxt->context->node = oldNode; ctxt->context->contextSize = oldContextSize; ctxt->context->proximityPosition = oldProximityPosition; cleanup: /* restore the xpath context */ if (comp != NULL) xmlXPathFreeCompExpr(comp); if (nodeset != NULL) xmlXPathFreeNodeSet(nodeset); if (str != NULL) xmlFree(str); valuePush(ctxt, ret); return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix dyn:map with namespace nodes exsltDynMapFunction didn't handle namespace nodes correctly. Namespace nodes are actually an xmlNs, not an xmlNode and must be special-cased. The old code initialized the doc pointer in the XPath context struct with a value read from past the end of the xmlNs struct. Typically, this resulted in a segfault. Found with afl-fuzz and ASan.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: const char *get_icalcomponent_errstr(icalcomponent *ical) { icalcomponent *comp; for (comp = icalcomponent_get_first_component(ical, ICAL_ANY_COMPONENT); comp; comp = icalcomponent_get_next_component(ical, ICAL_ANY_COMPONENT)) { icalproperty *prop; for (prop = icalcomponent_get_first_property(comp, ICAL_ANY_PROPERTY); prop; prop = icalcomponent_get_next_property(comp, ICAL_ANY_PROPERTY)) { if (icalproperty_isa(prop) == ICAL_XLICERROR_PROPERTY) { icalparameter *param; const char *errstr = icalproperty_get_xlicerror(prop); if (!errstr) return "Unknown iCal parsing error"; param = icalproperty_get_first_parameter( prop, ICAL_XLICERRORTYPE_PARAMETER); if (icalparameter_get_xlicerrortype(param) == ICAL_XLICERRORTYPE_VALUEPARSEERROR) { /* Check if this is an empty property error */ char propname[256]; if (sscanf(errstr, "No value for %s property", propname) == 1) { /* Empty LOCATION is OK */ if (!strcasecmp(propname, "LOCATION")) continue; if (!strcasecmp(propname, "COMMENT")) continue; if (!strcasecmp(propname, "DESCRIPTION")) continue; } } } } } return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HTTP: don't overrun buffer when parsing strings with sscanf()'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool tcp_collapse_retrans(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *next_skb = skb_rb_next(skb); int next_skb_size; next_skb_size = next_skb->len; BUG_ON(tcp_skb_pcount(skb) != 1 || tcp_skb_pcount(next_skb) != 1); if (next_skb_size) { if (next_skb_size <= skb_availroom(skb)) skb_copy_bits(next_skb, 0, skb_put(skb, next_skb_size), next_skb_size); else if (!skb_shift(skb, next_skb, next_skb_size)) return false; } tcp_highest_sack_replace(sk, next_skb, skb); /* Update sequence range on original skb. */ TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(next_skb)->end_seq; /* Merge over control information. This moves PSH/FIN etc. over */ TCP_SKB_CB(skb)->tcp_flags |= TCP_SKB_CB(next_skb)->tcp_flags; /* All done, get rid of second SKB and account for it so * packet counting does not break. */ TCP_SKB_CB(skb)->sacked |= TCP_SKB_CB(next_skb)->sacked & TCPCB_EVER_RETRANS; TCP_SKB_CB(skb)->eor = TCP_SKB_CB(next_skb)->eor; /* changed transmit queue under us so clear hints */ tcp_clear_retrans_hints_partial(tp); if (next_skb == tp->retransmit_skb_hint) tp->retransmit_skb_hint = skb; tcp_adjust_pcount(sk, next_skb, tcp_skb_pcount(next_skb)); tcp_skb_collapse_tstamp(skb, next_skb); tcp_rtx_queue_unlink_and_free(next_skb, sk); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'tcp: limit payload size of sacked skbs Jonathan Looney reported that TCP can trigger the following crash in tcp_shifted_skb() : BUG_ON(tcp_skb_pcount(skb) < pcount); This can happen if the remote peer has advertized the smallest MSS that linux TCP accepts : 48 An skb can hold 17 fragments, and each fragment can hold 32KB on x86, or 64KB on PowerPC. This means that the 16bit witdh of TCP_SKB_CB(skb)->tcp_gso_segs can overflow. Note that tcp_sendmsg() builds skbs with less than 64KB of payload, so this problem needs SACK to be enabled. SACK blocks allow TCP to coalesce multiple skbs in the retransmit queue, thus filling the 17 fragments to maximal capacity. CVE-2019-11477 -- u16 overflow of TCP_SKB_CB(skb)->tcp_gso_segs Fixes: 832d11c5cd07 ("tcp: Try to restore large SKBs while SACK processing") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Jonathan Looney <jtl@netflix.com> Acked-by: Neal Cardwell <ncardwell@google.com> Reviewed-by: Tyler Hicks <tyhicks@canonical.com> Cc: Yuchung Cheng <ycheng@google.com> Cc: Bruce Curtis <brucec@netflix.com> Cc: Jonathan Lemon <jonathan.lemon@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int nfc_llcp_build_gb(struct nfc_llcp_local *local) { u8 *gb_cur, *version_tlv, version, version_length; u8 *lto_tlv, lto_length; u8 *wks_tlv, wks_length; u8 *miux_tlv, miux_length; __be16 wks = cpu_to_be16(local->local_wks); u8 gb_len = 0; int ret = 0; version = LLCP_VERSION_11; version_tlv = nfc_llcp_build_tlv(LLCP_TLV_VERSION, &version, 1, &version_length); gb_len += version_length; lto_tlv = nfc_llcp_build_tlv(LLCP_TLV_LTO, &local->lto, 1, &lto_length); gb_len += lto_length; pr_debug("Local wks 0x%lx\n", local->local_wks); wks_tlv = nfc_llcp_build_tlv(LLCP_TLV_WKS, (u8 *)&wks, 2, &wks_length); gb_len += wks_length; miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&local->miux, 0, &miux_length); gb_len += miux_length; gb_len += ARRAY_SIZE(llcp_magic); if (gb_len > NFC_MAX_GT_LEN) { ret = -EINVAL; goto out; } gb_cur = local->gb; memcpy(gb_cur, llcp_magic, ARRAY_SIZE(llcp_magic)); gb_cur += ARRAY_SIZE(llcp_magic); memcpy(gb_cur, version_tlv, version_length); gb_cur += version_length; memcpy(gb_cur, lto_tlv, lto_length); gb_cur += lto_length; memcpy(gb_cur, wks_tlv, wks_length); gb_cur += wks_length; memcpy(gb_cur, miux_tlv, miux_length); gb_cur += miux_length; local->gb_len = gb_len; out: kfree(version_tlv); kfree(lto_tlv); kfree(wks_tlv); kfree(miux_tlv); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'net: nfc: Fix NULL dereference on nfc_llcp_build_tlv fails KASAN report this: BUG: KASAN: null-ptr-deref in nfc_llcp_build_gb+0x37f/0x540 [nfc] Read of size 3 at addr 0000000000000000 by task syz-executor.0/5401 CPU: 0 PID: 5401 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 Call Trace: __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0xfa/0x1ce lib/dump_stack.c:113 kasan_report+0x171/0x18d mm/kasan/report.c:321 memcpy+0x1f/0x50 mm/kasan/common.c:130 nfc_llcp_build_gb+0x37f/0x540 [nfc] nfc_llcp_register_device+0x6eb/0xb50 [nfc] nfc_register_device+0x50/0x1d0 [nfc] nfcsim_device_new+0x394/0x67d [nfcsim] ? 0xffffffffc1080000 nfcsim_init+0x6b/0x1000 [nfcsim] do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f9cb79dcc58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000280 RDI: 0000000000000003 RBP: 00007f9cb79dcc70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f9cb79dd6bc R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004 nfc_llcp_build_tlv will return NULL on fails, caller should check it, otherwise will trigger a NULL dereference. Reported-by: Hulk Robot <hulkci@huawei.com> Fixes: eda21f16a5ed ("NFC: Set MIU and RW values from CONNECT and CC LLCP frames") Fixes: d646960f7986 ("NFC: Initial LLCP support") Signed-off-by: YueHaibing <yuehaibing@huawei.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gdImagePtr gdImageCreateFromXbm(FILE * fd) { char fline[MAX_XBM_LINE_SIZE]; char iname[MAX_XBM_LINE_SIZE]; char *type; int value; unsigned int width = 0, height = 0; int fail = 0; int max_bit = 0; gdImagePtr im; int bytes = 0, i; int bit, x = 0, y = 0; int ch; char h[8]; unsigned int b; rewind(fd); while (fgets(fline, MAX_XBM_LINE_SIZE, fd)) { fline[MAX_XBM_LINE_SIZE-1] = '\0'; if (strlen(fline) == MAX_XBM_LINE_SIZE-1) { return 0; } if (sscanf(fline, "#define %s %d", iname, &value) == 2) { if (!(type = strrchr(iname, '_'))) { type = iname; } else { type++; } if (!strcmp("width", type)) { width = (unsigned int) value; } if (!strcmp("height", type)) { height = (unsigned int) value; } } else { if ( sscanf(fline, "static unsigned char %s = {", iname) == 1 || sscanf(fline, "static char %s = {", iname) == 1) { max_bit = 128; } else if (sscanf(fline, "static unsigned short %s = {", iname) == 1 || sscanf(fline, "static short %s = {", iname) == 1) { max_bit = 32768; } if (max_bit) { bytes = (width + 7) / 8 * height; if (!bytes) { return 0; } if (!(type = strrchr(iname, '_'))) { type = iname; } else { type++; } if (!strcmp("bits[]", type)) { break; } } } } if (!bytes || !max_bit) { return 0; } if(!(im = gdImageCreate(width, height))) { return 0; } gdImageColorAllocate(im, 255, 255, 255); gdImageColorAllocate(im, 0, 0, 0); h[2] = '\0'; h[4] = '\0'; for (i = 0; i < bytes; i++) { while (1) { if ((ch=getc(fd)) == EOF) { fail = 1; break; } if (ch == 'x') { break; } } if (fail) { break; } /* Get hex value */ if ((ch=getc(fd)) == EOF) { break; } h[0] = ch; if ((ch=getc(fd)) == EOF) { break; } h[1] = ch; if (max_bit == 32768) { if ((ch=getc(fd)) == EOF) { break; } h[2] = ch; if ((ch=getc(fd)) == EOF) { break; } h[3] = ch; } sscanf(h, "%x", &b); for (bit = 1; bit <= max_bit; bit = bit << 1) { gdImageSetPixel(im, x++, y, (b & bit) ? 1 : 0); if (x == im->sx) { x = 0; y++; if (y == im->sy) { return im; } break; } } } php_gd_error("EOF before image was complete"); gdImageDestroy(im); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-908'], 'message': 'Fix #77973: Uninitialized read in gdImageCreateFromXbm We have to ensure that `sscanf()` does indeed read a hex value here, and bail out otherwise.'</s>
<s>[INST] Given the following code containing errors, provide 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 *url_decode_r(char *to, char *url, size_t size) { char *s = url, // source *d = to, // destination *e = &to[size - 1]; // destination end while(*s && d < e) { if(unlikely(*s == '%')) { if(likely(s[1] && s[2])) { *d++ = from_hex(s[1]) << 4 | from_hex(s[2]); s += 2; } } else if(unlikely(*s == '+')) *d++ = ' '; else *d++ = *s; s++; } *d = '\0'; return to; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-113', 'CWE-200', 'CWE-94', 'CWE-74'], 'message': 'fixed vulnerabilities identified by red4sec.com (#4521)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadVIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define VFF_CM_genericRGB 15 #define VFF_CM_ntscRGB 1 #define VFF_CM_NONE 0 #define VFF_DEP_DECORDER 0x4 #define VFF_DEP_NSORDER 0x8 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MAPTYP_2_BYTE 2 #define VFF_MAPTYP_4_BYTE 4 #define VFF_MAPTYP_FLOAT 5 #define VFF_MAPTYP_DOUBLE 7 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_MS_SHARED 3 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 #define VFF_TYP_2_BYTE 2 #define VFF_TYP_4_BYTE 4 #define VFF_TYP_FLOAT 5 #define VFF_TYP_DOUBLE 9 typedef struct _ViffInfo { unsigned char identifier, file_type, release, version, machine_dependency, reserve[3]; char comment[512]; unsigned int rows, columns, subrows; int x_offset, y_offset; float x_bits_per_pixel, y_bits_per_pixel; unsigned int location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; double min_value, scale_factor, value; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register ssize_t x; register Quantum *q; register ssize_t i; register unsigned char *p; size_t bytes_per_pixel, max_packets, quantum; ssize_t count, y; unsigned char *pixels; unsigned long lsb_first; ViffInfo viff_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read VIFF header (1024 bytes). */ count=ReadBlob(image,1,&viff_info.identifier); do { /* Verify VIFF identifier. */ if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab)) ThrowReaderException(CorruptImageError,"NotAVIFFImage"); /* Initialize VIFF image. */ (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type); (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release); (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version); (void) ReadBlob(image,sizeof(viff_info.machine_dependency), &viff_info.machine_dependency); (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve); count=ReadBlob(image,512,(unsigned char *) viff_info.comment); if (count != 512) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); viff_info.comment[511]='\0'; if (strlen(viff_info.comment) > 4) (void) SetImageProperty(image,"comment",viff_info.comment,exception); if ((viff_info.machine_dependency == VFF_DEP_DECORDER) || (viff_info.machine_dependency == VFF_DEP_NSORDER)) image->endian=LSBEndian; else image->endian=MSBEndian; viff_info.rows=ReadBlobLong(image); viff_info.columns=ReadBlobLong(image); viff_info.subrows=ReadBlobLong(image); viff_info.x_offset=ReadBlobSignedLong(image); viff_info.y_offset=ReadBlobSignedLong(image); viff_info.x_bits_per_pixel=(float) ReadBlobLong(image); viff_info.y_bits_per_pixel=(float) ReadBlobLong(image); viff_info.location_type=ReadBlobLong(image); viff_info.location_dimension=ReadBlobLong(image); viff_info.number_of_images=ReadBlobLong(image); viff_info.number_data_bands=ReadBlobLong(image); viff_info.data_storage_type=ReadBlobLong(image); viff_info.data_encode_scheme=ReadBlobLong(image); viff_info.map_scheme=ReadBlobLong(image); viff_info.map_storage_type=ReadBlobLong(image); viff_info.map_rows=ReadBlobLong(image); viff_info.map_columns=ReadBlobLong(image); viff_info.map_subrows=ReadBlobLong(image); viff_info.map_enable=ReadBlobLong(image); viff_info.maps_per_cycle=ReadBlobLong(image); viff_info.color_space_model=ReadBlobLong(image); for (i=0; i < 420; i++) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows; if (number_pixels > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (number_pixels == 0) ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported"); image->columns=viff_info.rows; image->rows=viff_info.columns; image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL : MAGICKCORE_QUANTUM_DEPTH; image->alpha_trait=viff_info.number_data_bands == 4 ? BlendPixelTrait : UndefinedPixelTrait; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); (void) SetImageBackgroundColor(image,exception); /* Verify that we can read this VIFF image. */ if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((viff_info.data_storage_type != VFF_TYP_BIT) && (viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.data_storage_type != VFF_TYP_2_BYTE) && (viff_info.data_storage_type != VFF_TYP_4_BYTE) && (viff_info.data_storage_type != VFF_TYP_FLOAT) && (viff_info.data_storage_type != VFF_TYP_DOUBLE)) ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported"); if (viff_info.data_encode_scheme != VFF_DES_RAW) ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) && (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) && (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE)) ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported"); if ((viff_info.color_space_model != VFF_CM_NONE) && (viff_info.color_space_model != VFF_CM_ntscRGB) && (viff_info.color_space_model != VFF_CM_genericRGB)) ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported"); if (viff_info.location_type != VFF_LOC_IMPLICIT) ThrowReaderException(CoderError,"LocationTypeIsNotSupported"); if (viff_info.number_of_images != 1) ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported"); if (viff_info.map_rows == 0) viff_info.map_scheme=VFF_MS_NONE; switch ((int) viff_info.map_scheme) { case VFF_MS_NONE: { if (viff_info.number_data_bands < 3) { /* Create linear color ramp. */ if (viff_info.data_storage_type == VFF_TYP_BIT) image->colors=2; else if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE) image->colors=256UL; else image->colors=image->depth <= 8 ? 256UL : 65536UL; status=AcquireImageColormap(image,image->colors,exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } break; } case VFF_MS_ONEPERBAND: case VFF_MS_SHARED: { unsigned char *viff_colormap; /* Allocate VIFF colormap. */ switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break; case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break; case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break; case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break; case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } image->colors=viff_info.map_columns; if ((MagickSizeType) (viff_info.map_rows*image->colors) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((MagickSizeType) viff_info.map_rows > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); if ((MagickSizeType) viff_info.map_rows > (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Read VIFF raster colormap. */ count=ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows, viff_colormap); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: { MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } case VFF_MAPTYP_4_BYTE: case VFF_MAPTYP_FLOAT: { MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } default: break; } for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++) { switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break; case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break; case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break; case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break; default: value=1.0*viff_colormap[i]; break; } if (i < (ssize_t) image->colors) { image->colormap[i].red=(MagickRealType) ScaleCharToQuantum((unsigned char) value); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum((unsigned char) value); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum((unsigned char) value); } else if (i < (ssize_t) (2*image->colors)) image->colormap[i % image->colors].green=(MagickRealType) ScaleCharToQuantum((unsigned char) value); else if (i < (ssize_t) (3*image->colors)) image->colormap[i % image->colors].blue=(MagickRealType) ScaleCharToQuantum((unsigned char) value); } viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Create bi-level colormap. */ image->colors=2; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image->colorspace=GRAYColorspace; } /* Allocate VIFF pixels. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: bytes_per_pixel=2; break; case VFF_TYP_4_BYTE: bytes_per_pixel=4; break; case VFF_TYP_FLOAT: bytes_per_pixel=4; break; case VFF_TYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } if (viff_info.data_storage_type == VFF_TYP_BIT) { if (HeapOverflowSanityCheck((image->columns+7UL) >> 3UL,image->rows) != MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); max_packets=((image->columns+7UL) >> 3UL)*image->rows; } else { if (HeapOverflowSanityCheck((size_t) number_pixels,viff_info.number_data_bands) != MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); max_packets=(size_t) (number_pixels*viff_info.number_data_bands); } if ((MagickSizeType) (bytes_per_pixel*max_packets) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); pixels=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax( number_pixels,max_packets),bytes_per_pixel*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(pixels,0,MagickMax(number_pixels,max_packets)* bytes_per_pixel*sizeof(*pixels)); count=ReadBlob(image,bytes_per_pixel*max_packets,pixels); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: { MSBOrderShort(pixels,bytes_per_pixel*max_packets); break; } case VFF_TYP_4_BYTE: case VFF_TYP_FLOAT: { MSBOrderLong(pixels,bytes_per_pixel*max_packets); break; } default: break; } min_value=0.0; scale_factor=1.0; if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.map_scheme == VFF_MS_NONE)) { double max_value; /* Determine scale factor. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break; default: value=1.0*pixels[0]; break; } max_value=value; min_value=value; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (value > max_value) max_value=value; else if (value < min_value) min_value=value; } if ((min_value == 0) && (max_value == 0)) scale_factor=0; else if (min_value == max_value) { scale_factor=(double) QuantumRange/min_value; min_value=0; } else scale_factor=(double) QuantumRange/(max_value-min_value); } /* Convert pixels to Quantum size. */ p=(unsigned char *) pixels; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (viff_info.map_scheme == VFF_MS_NONE) { value=(value-min_value)*scale_factor; if (value > QuantumRange) value=QuantumRange; else if (value < 0) value=0; } *p=(unsigned char) ((Quantum) value); p++; } /* Convert VIFF raster image to pixel packets. */ p=(unsigned char *) pixels; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Convert bitmap scanline. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) (image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q); SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q); SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q); if (image->storage_class == PseudoClass) SetPixelIndex(image,(Quantum) quantum,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (int) (image->columns % 8); bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q); SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q); SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q); if (image->storage_class == PseudoClass) SetPixelIndex(image,(Quantum) quantum,q); q+=GetPixelChannels(image); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->storage_class == PseudoClass) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { /* Convert DirectColor scanline. */ number_pixels=(MagickSizeType) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p),q); SetPixelGreen(image,ScaleCharToQuantum(*(p+number_pixels)),q); SetPixelBlue(image,ScaleCharToQuantum(*(p+2*number_pixels)),q); if (image->colors != 0) { ssize_t index; index=(ssize_t) GetPixelRed(image,q); SetPixelRed(image,ClampToQuantum(image->colormap[ ConstrainColormapIndex(image,index,exception)].red),q); index=(ssize_t) GetPixelGreen(image,q); SetPixelGreen(image,ClampToQuantum(image->colormap[ ConstrainColormapIndex(image,index,exception)].green),q); index=(ssize_t) GetPixelBlue(image,q); SetPixelBlue(image,ClampToQuantum(image->colormap[ ConstrainColormapIndex(image,index,exception)].blue),q); } SetPixelAlpha(image,image->alpha_trait != UndefinedPixelTrait ? ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueAlpha,q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (image->storage_class == PseudoClass) (void) SyncImage(image,exception); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; count=ReadBlob(image,1,&viff_info.identifier); if ((count == 1) && (viff_info.identifier == 0xab)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (viff_info.identifier == 0xab)); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1600'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadRGBImage(const ImageInfo *image_info,ExceptionInfo *exception) { const unsigned char *pixels; Image *canvas_image, *image; MagickBooleanType status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t length; ssize_t count, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); if (image_info->interlace != PartitionInterlace) { status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); } /* Create virtual canvas to support cropping (i.e. image.rgb[100x100+10+20]). */ canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse, exception); if (canvas_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod); quantum_info=AcquireQuantumInfo(image_info,canvas_image); if (quantum_info == (QuantumInfo *) NULL) { canvas_image=DestroyImage(canvas_image); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } quantum_type=RGBQuantum; if (LocaleCompare(image_info->magick,"RGBA") == 0) { quantum_type=RGBAQuantum; image->matte=MagickTrue; } if (LocaleCompare(image_info->magick,"RGBO") == 0) { quantum_type=RGBOQuantum; image->matte=MagickTrue; } pixels=(const unsigned char *) NULL; if (image_info->number_scenes != 0) while (image->scene < image_info->scene) { /* Skip to next image. */ image->scene++; length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) break; } } count=0; length=0; scene=0; status=MagickTrue; do { /* Read pixels to virtual canvas image then push to image. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) break; switch (image_info->interlace) { case NoInterlace: default: { /* No interlacing: RGBRGBRGBRGBRGBRGB... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=QueueAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); SetPixelGreen(q,GetPixelGreen(p)); SetPixelBlue(q,GetPixelBlue(p)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } break; } case LineInterlace: { static QuantumType quantum_types[4] = { RedQuantum, GreenQuantum, BlueQuantum, AlphaQuantum }; /* Line interlacing: RRR...GGG...BBB...RRR...GGG...BBB... */ if (LocaleCompare(image_info->magick,"RGBO") == 0) quantum_types[3]=OpacityQuantum; if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { for (i=0; i < (ssize_t) (image->matte != MagickFalse ? 4 : 3); i++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } quantum_type=quantum_types[i]; q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { switch (quantum_type) { case RedQuantum: { SetPixelRed(q,GetPixelRed(p)); break; } case GreenQuantum: { SetPixelGreen(q,GetPixelGreen(p)); break; } case BlueQuantum: { SetPixelBlue(q,GetPixelBlue(p)); break; } case OpacityQuantum: { SetPixelOpacity(q,GetPixelOpacity(p)); break; } case AlphaQuantum: { SetPixelAlpha(q,GetPixelAlpha(p)); break; } default: break; } p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,6); if (status == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,6); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image, canvas_image->extract_info.x,0,canvas_image->columns,1, exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,6); if (status == MagickFalse) break; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,6,6); if (status == MagickFalse) break; } break; } case PartitionInterlace: { /* Partition interlacing: RRRRRR..., GGGGGG..., BBBBBB... */ AppendImageFormat("R",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) break; if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse) { status=MagickFalse; ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); for (i=0; i < (ssize_t) scene; i++) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { (void) ReadBlobStream(image,length,GetQuantumPixels(quantum_info), &count); if (count != (ssize_t) length) break; } if (count != (ssize_t) length) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("G",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) break; length=GetQuantumExtent(canvas_image,quantum_info,GreenQuantum); for (i=0; i < (ssize_t) scene; i++) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { (void) ReadBlobStream(image,length,GetQuantumPixels(quantum_info), &count); if (count != (ssize_t) length) break; } if (count != (ssize_t) length) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("B",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) break; length=GetQuantumExtent(canvas_image,quantum_info,BlueQuantum); for (i=0; i < (ssize_t) scene; i++) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { (void) ReadBlobStream(image,length,GetQuantumPixels(quantum_info), &count); if (count != (ssize_t) length) break; } if (count != (ssize_t) length) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,5); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { (void) CloseBlob(image); AppendImageFormat("A",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) break; length=GetQuantumExtent(canvas_image,quantum_info,AlphaQuantum); for (i=0; i < (ssize_t) scene; i++) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { (void) ReadBlobStream(image,length,GetQuantumPixels( quantum_info),&count); if (count != (ssize_t) length) break; } if (count != (ssize_t) length) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,5); if (status == MagickFalse) break; } } (void) CloseBlob(image); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,5); if (status == MagickFalse) break; } break; } } if (status == MagickFalse) break; SetQuantumImageType(image,quantum_type); /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (count == (ssize_t) length) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } scene++; } while (count == (ssize_t) length); quantum_info=DestroyQuantumInfo(quantum_info); InheritException(&image->exception,&canvas_image->exception); canvas_image=DestroyImage(canvas_image); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadYUVImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *chroma_image, *image, *resize_image; InterlaceType interlace; MagickBooleanType status; register const PixelPacket *chroma_pixels; register ssize_t x; register PixelPacket *q; register unsigned char *p; ssize_t count, horizontal_factor, vertical_factor, y; size_t length, quantum; unsigned char *scanline; /* Allocate image structure. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } quantum=(size_t) (image->depth <= 8 ? 1 : 2); interlace=image_info->interlace; horizontal_factor=2; vertical_factor=2; if (image_info->sampling_factor != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(image_info->sampling_factor,&geometry_info); horizontal_factor=(ssize_t) geometry_info.rho; vertical_factor=(ssize_t) geometry_info.sigma; if ((flags & SigmaValue) == 0) vertical_factor=horizontal_factor; if ((horizontal_factor != 1) && (horizontal_factor != 2) && (vertical_factor != 1) && (vertical_factor != 2)) ThrowReaderException(CorruptImageError,"UnexpectedSamplingFactor"); } if ((interlace == UndefinedInterlace) || ((interlace == NoInterlace) && (vertical_factor == 2))) { interlace=NoInterlace; /* CCIR 4:2:2 */ if (vertical_factor == 2) interlace=PlaneInterlace; /* CCIR 4:1:1 */ } if (interlace != PartitionInterlace) { /* Open image file. */ status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); } /* Allocate memory for a scanline. */ if (interlace == NoInterlace) scanline=(unsigned char *) AcquireQuantumMemory((size_t) 2UL* image->columns+2UL,quantum*sizeof(*scanline)); else scanline=(unsigned char *) AcquireQuantumMemory(image->columns, quantum*sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); status=MagickTrue; do { chroma_image=CloneImage(image,(image->columns+horizontal_factor-1)/ horizontal_factor,(image->rows+vertical_factor-1)/vertical_factor, MagickTrue,exception); if (chroma_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Convert raster image to pixel packets. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) break; if (interlace == PartitionInterlace) { AppendImageFormat("Y",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } } for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *chroma_pixels; if (interlace == NoInterlace) { if ((y > 0) || (GetPreviousImageInList(image) == (Image *) NULL)) { length=2*quantum*image->columns; count=ReadBlob(image,length,scanline); if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } p=scanline; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; chroma_pixels=QueueAuthenticPixels(chroma_image,0,y, chroma_image->columns,1,exception); if (chroma_pixels == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=2) { SetPixelRed(chroma_pixels,0); if (quantum == 1) SetPixelGreen(chroma_pixels,ScaleCharToQuantum(*p++)); else { SetPixelGreen(chroma_pixels,ScaleShortToQuantum(((*p) << 8) | *(p+1))); p+=2; } if (quantum == 1) SetPixelRed(q,ScaleCharToQuantum(*p++)); else { SetPixelRed(q,ScaleShortToQuantum(((*p) << 8) | *(p+1))); p+=2; } SetPixelGreen(q,0); SetPixelBlue(q,0); q++; SetPixelGreen(q,0); SetPixelBlue(q,0); if (quantum == 1) SetPixelBlue(chroma_pixels,ScaleCharToQuantum(*p++)); else { SetPixelBlue(chroma_pixels,ScaleShortToQuantum(((*p) << 8) | *(p+1))); p+=2; } if (quantum == 1) SetPixelRed(q,ScaleCharToQuantum(*p++)); else { SetPixelRed(q,ScaleShortToQuantum(((*p) << 8) | *(p+1))); p+=2; } chroma_pixels++; q++; } } else { if ((y > 0) || (GetPreviousImageInList(image) == (Image *) NULL)) { length=quantum*image->columns; count=ReadBlob(image,length,scanline); if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } p=scanline; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (quantum == 1) SetPixelRed(q,ScaleCharToQuantum(*p++)); else { SetPixelRed(q,ScaleShortToQuantum(((*p) << 8) | *(p+1))); p+=2; } SetPixelGreen(q,0); SetPixelBlue(q,0); q++; } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (interlace == NoInterlace) if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (interlace == PartitionInterlace) { (void) CloseBlob(image); AppendImageFormat("U",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } } if (interlace != NoInterlace) { for (y=0; y < (ssize_t) chroma_image->rows; y++) { length=quantum*chroma_image->columns; count=ReadBlob(image,length,scanline); if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } p=scanline; q=QueueAuthenticPixels(chroma_image,0,y,chroma_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) chroma_image->columns; x++) { SetPixelRed(q,0); if (quantum == 1) SetPixelGreen(q,ScaleCharToQuantum(*p++)); else { SetPixelGreen(q,ScaleShortToQuantum(((*p) << 8) | *(p+1))); p+=2; } SetPixelBlue(q,0); q++; } if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse) break; } if (interlace == PartitionInterlace) { (void) CloseBlob(image); AppendImageFormat("V",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } } for (y=0; y < (ssize_t) chroma_image->rows; y++) { length=quantum*chroma_image->columns; count=ReadBlob(image,length,scanline); if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } p=scanline; q=GetAuthenticPixels(chroma_image,0,y,chroma_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) chroma_image->columns; x++) { if (quantum == 1) SetPixelBlue(q,ScaleCharToQuantum(*p++)); else { SetPixelBlue(q,ScaleShortToQuantum(((*p) << 8) | *(p+1))); p+=2; } q++; } if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse) break; } } /* Scale image. */ resize_image=ResizeImage(chroma_image,image->columns,image->rows, TriangleFilter,1.0,exception); chroma_image=DestroyImage(chroma_image); if (resize_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); chroma_pixels=GetVirtualPixels(resize_image,0,y,resize_image->columns,1, &resize_image->exception); if ((q == (PixelPacket *) NULL) || (chroma_pixels == (const PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(chroma_pixels)); SetPixelBlue(q,GetPixelBlue(chroma_pixels)); chroma_pixels++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } resize_image=DestroyImage(resize_image); if (SetImageColorspace(image,YCbCrColorspace) == MagickFalse) break; if (interlace == PartitionInterlace) (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (interlace == NoInterlace) count=ReadBlob(image,(size_t) (2*quantum*image->columns),scanline); else count=ReadBlob(image,(size_t) quantum*image->columns,scanline); if (count != 0) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (count != 0); scanline=(unsigned char *) RelinquishMagickMemory(scanline); InheritException(exception,&image->exception); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception) { char colorspace[MaxTextExtent], text[MaxTextExtent]; double x_offset, y_offset; Image *image; IndexPacket *indexes; MagickBooleanType status; MagickPixelPacket pixel; QuantumAny range; register ssize_t i, x; register PixelPacket *q; ssize_t count, type, y; unsigned long depth, height, max_value, width; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) memset(text,0,sizeof(text)); (void) ReadBlobString(image,text); if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); x_offset=(-1.0); y_offset=(-1.0); do { width=0; height=0; max_value=0; *colorspace='\0'; count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%32s",&width,&height,&max_value, colorspace); if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->columns=width; image->rows=height; if ((max_value == 0) || (max_value > 4294967295U)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ; image->depth=depth; status=SetImageExtent(image,image->columns,image->rows); if (status != MagickFalse) status=ResetImagePixels(image,&image->exception); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } LocaleLower(colorspace); i=(ssize_t) strlen(colorspace)-1; image->matte=MagickFalse; if ((i > 0) && (colorspace[i] == 'a')) { colorspace[i]='\0'; image->matte=MagickTrue; } type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace); if (type < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->colorspace=(ColorspaceType) type; (void) memset(&pixel,0,sizeof(pixel)); (void) SetImageBackgroundColor(image); range=GetQuantumRange(image->depth); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { double blue, green, index, opacity, red; if (status == MagickFalse) break; red=0.0; green=0.0; blue=0.0; index=0.0; opacity=0.0; for (x=0; x < (ssize_t) image->columns; x++) { if (ReadBlobString(image,text) == (char *) NULL) { status=MagickFalse; break; } switch (image->colorspace) { case LinearGRAYColorspace: case GRAYColorspace: { if (image->matte != MagickFalse) { (void) sscanf(text,"%lf,%lf: (%lf%*[%,]%lf%*[%,]",&x_offset, &y_offset,&red,&opacity); green=red; blue=red; break; } (void) sscanf(text,"%lf,%lf: (%lf%*[%,]",&x_offset,&y_offset,&red); green=red; blue=red; break; } case CMYKColorspace: { if (image->matte != MagickFalse) { (void) sscanf(text, "%lf,%lf: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue,&index,&opacity); break; } (void) sscanf(text, "%lf,%lf: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset, &y_offset,&red,&green,&blue,&index); break; } default: { if (image->matte != MagickFalse) { (void) sscanf(text, "%lf,%lf: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue,&opacity); break; } (void) sscanf(text,"%lf,%lf: (%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue); break; } } if (strchr(text,'%') != (char *) NULL) { red*=0.01*range; green*=0.01*range; blue*=0.01*range; index*=0.01*range; opacity*=0.01*range; } if (image->colorspace == LabColorspace) { green+=(range+1)/2.0; blue+=(range+1)/2.0; } pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5), range); pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5), range); pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5), range); pixel.index=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (index+0.5), range); pixel.opacity=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (opacity+ 0.5),range); q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1, exception); if (q == (PixelPacket *) NULL) continue; SetPixelRed(q,pixel.red); SetPixelGreen(q,pixel.green); SetPixelBlue(q,pixel.blue); if (image->colorspace == CMYKColorspace) { indexes=GetAuthenticIndexQueue(image); SetPixelIndex(indexes,pixel.index); } if (image->matte != MagickFalse) SetPixelAlpha(q,pixel.opacity); if (SyncAuthenticPixels(image,exception) == MagickFalse) { status=MagickFalse; break; } } } if (status == MagickFalse) break; *text='\0'; (void) ReadBlobString(image,text); if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: uint64_t hllCount(struct hllhdr *hdr, int *invalid) { double m = HLL_REGISTERS; double E; int j; int reghisto[HLL_Q+2] = {0}; /* Compute register histogram */ if (hdr->encoding == HLL_DENSE) { hllDenseRegHisto(hdr->registers,reghisto); } else if (hdr->encoding == HLL_SPARSE) { hllSparseRegHisto(hdr->registers, sdslen((sds)hdr)-HLL_HDR_SIZE,invalid,reghisto); } else if (hdr->encoding == HLL_RAW) { hllRawRegHisto(hdr->registers,reghisto); } else { serverPanic("Unknown HyperLogLog encoding in hllCount()"); } /* Estimate cardinality form register histogram. See: * "New cardinality estimation algorithms for HyperLogLog sketches" * Otmar Ertl, arXiv:1702.01284 */ double z = m * hllTau((m-reghisto[HLL_Q+1])/(double)m); for (j = HLL_Q; j >= 1; --j) { z += reghisto[j]; z *= 0.5; } z += m * hllSigma(reghisto[0]/(double)m); E = llroundl(HLL_ALPHA_INF*m*m/z); return (uint64_t) E; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HyperLogLog: enlarge reghisto variable for safety.'</s>
<s>[INST] Given the following code containing errors, provide 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 extract_or_test_files(__G) /* return PK-type error code */ __GDEF { unsigned i, j; zoff_t cd_bufstart; uch *cd_inptr; int cd_incnt; ulg filnum=0L, blknum=0L; int reached_end; #ifndef SFX int no_endsig_found; #endif int error, error_in_archive=PK_COOL; int *fn_matched=NULL, *xn_matched=NULL; zucn_t members_processed; ulg num_skipped=0L, num_bad_pwd=0L; zoff_t old_extra_bytes = 0L; #ifdef SET_DIR_ATTRIB unsigned num_dirs=0; direntry *dirlist=(direntry *)NULL, **sorted_dirlist=(direntry **)NULL; #endif /* * First, two general initializations are applied. These have been moved * here from process_zipfiles() because they are only needed for accessing * and/or extracting the data content of the zip archive. */ /* a) initialize the CRC table pointer (once) */ if (CRC_32_TAB == NULL) { if ((CRC_32_TAB = get_crc_table()) == NULL) { return PK_MEM; } } #if (!defined(SFX) || defined(SFX_EXDIR)) /* b) check out if specified extraction root directory exists */ if (uO.exdir != (char *)NULL && G.extract_flag) { G.create_dirs = !uO.fflag; if ((error = checkdir(__G__ uO.exdir, ROOT)) > MPN_INF_SKIP) { /* out of memory, or file in way */ return (error == MPN_NOMEM ? PK_MEM : PK_ERR); } } #endif /* !SFX || SFX_EXDIR */ /*--------------------------------------------------------------------------- The basic idea of this function is as follows. Since the central di- rectory lies at the end of the zipfile and the member files lie at the beginning or middle or wherever, it is not very desirable to simply read a central directory entry, jump to the member and extract it, and then jump back to the central directory. In the case of a large zipfile this would lead to a whole lot of disk-grinding, especially if each mem- ber file is small. Instead, we read from the central directory the per- tinent information for a block of files, then go extract/test the whole block. Thus this routine contains two small(er) loops within a very large outer loop: the first of the small ones reads a block of files from the central directory; the second extracts or tests each file; and the outer one loops over blocks. There's some file-pointer positioning stuff in between, but that's about it. Btw, it's because of this jump- ing around that we can afford to be lenient if an error occurs in one of the member files: we should still be able to go find the other members, since we know the offset of each from the beginning of the zipfile. ---------------------------------------------------------------------------*/ G.pInfo = G.info; #if CRYPT G.newzip = TRUE; #endif #ifndef SFX G.reported_backslash = FALSE; #endif /* malloc space for check on unmatched filespecs (OK if one or both NULL) */ if (G.filespecs > 0 && (fn_matched=(int *)malloc(G.filespecs*sizeof(int))) != (int *)NULL) for (i = 0; i < G.filespecs; ++i) fn_matched[i] = FALSE; if (G.xfilespecs > 0 && (xn_matched=(int *)malloc(G.xfilespecs*sizeof(int))) != (int *)NULL) for (i = 0; i < G.xfilespecs; ++i) xn_matched[i] = FALSE; /*--------------------------------------------------------------------------- Begin main loop over blocks of member files. We know the entire central directory is on this disk: we would not have any of this information un- less the end-of-central-directory record was on this disk, and we would not have gotten to this routine unless this is also the disk on which the central directory starts. In practice, this had better be the ONLY disk in the archive, but we'll add multi-disk support soon. ---------------------------------------------------------------------------*/ members_processed = 0; #ifndef SFX no_endsig_found = FALSE; #endif reached_end = FALSE; while (!reached_end) { j = 0; #ifdef AMIGA memzero(G.filenotes, DIR_BLKSIZ * sizeof(char *)); #endif /* * Loop through files in central directory, storing offsets, file * attributes, case-conversion and text-conversion flags until block * size is reached. */ while ((j < DIR_BLKSIZ)) { G.pInfo = &G.info[j]; if (readbuf(__G__ G.sig, 4) == 0) { error_in_archive = PK_EOF; reached_end = TRUE; /* ...so no more left to do */ break; } if (memcmp(G.sig, central_hdr_sig, 4)) { /* is it a new entry? */ /* no new central directory entry * -> is the number of processed entries compatible with the * number of entries as stored in the end_central record? */ if ((members_processed & (G.ecrec.have_ecr64 ? MASK_ZUCN64 : MASK_ZUCN16)) == G.ecrec.total_entries_central_dir) { #ifndef SFX /* yes, so look if we ARE back at the end_central record */ no_endsig_found = ( (memcmp(G.sig, (G.ecrec.have_ecr64 ? end_central64_sig : end_central_sig), 4) != 0) && (!G.ecrec.is_zip64_archive) && (memcmp(G.sig, end_central_sig, 4) != 0) ); #endif /* !SFX */ } else { /* no; we have found an error in the central directory * -> report it and stop searching for more Zip entries */ Info(slide, 0x401, ((char *)slide, LoadFarString(CentSigMsg), j + blknum*DIR_BLKSIZ + 1)); Info(slide, 0x401, ((char *)slide, LoadFarString(ReportMsg))); error_in_archive = PK_BADERR; } reached_end = TRUE; /* ...so no more left to do */ break; } /* process_cdir_file_hdr() sets pInfo->hostnum, pInfo->lcflag */ if ((error = process_cdir_file_hdr(__G)) != PK_COOL) { error_in_archive = error; /* only PK_EOF defined */ reached_end = TRUE; /* ...so no more left to do */ break; } if ((error = do_string(__G__ G.crec.filename_length, DS_FN)) != PK_COOL) { if (error > error_in_archive) error_in_archive = error; if (error > PK_WARN) { /* fatal: no more left to do */ Info(slide, 0x401, ((char *)slide, LoadFarString(FilNamMsg), FnFilter1(G.filename), "central")); reached_end = TRUE; break; } } if ((error = do_string(__G__ G.crec.extra_field_length, EXTRA_FIELD)) != 0) { if (error > error_in_archive) error_in_archive = error; if (error > PK_WARN) { /* fatal */ Info(slide, 0x401, ((char *)slide, LoadFarString(ExtFieldMsg), FnFilter1(G.filename), "central")); reached_end = TRUE; break; } } #ifdef AMIGA G.filenote_slot = j; if ((error = do_string(__G__ G.crec.file_comment_length, uO.N_flag ? FILENOTE : SKIP)) != PK_COOL) #else if ((error = do_string(__G__ G.crec.file_comment_length, SKIP)) != PK_COOL) #endif { if (error > error_in_archive) error_in_archive = error; if (error > PK_WARN) { /* fatal */ Info(slide, 0x421, ((char *)slide, LoadFarString(BadFileCommLength), FnFilter1(G.filename))); reached_end = TRUE; break; } } if (G.process_all_files) { if (store_info(__G)) ++j; /* file is OK; info[] stored; continue with next */ else ++num_skipped; } else { int do_this_file; if (G.filespecs == 0) do_this_file = TRUE; else { /* check if this entry matches an `include' argument */ do_this_file = FALSE; for (i = 0; i < G.filespecs; i++) if (match(G.filename, G.pfnames[i], uO.C_flag WISEP)) { do_this_file = TRUE; /* ^-- ignore case or not? */ if (fn_matched) fn_matched[i] = TRUE; break; /* found match, so stop looping */ } } if (do_this_file) { /* check if this is an excluded file */ for (i = 0; i < G.xfilespecs; i++) if (match(G.filename, G.pxnames[i], uO.C_flag WISEP)) { do_this_file = FALSE; /* ^-- ignore case or not? */ if (xn_matched) xn_matched[i] = TRUE; break; } } if (do_this_file) { if (store_info(__G)) ++j; /* file is OK */ else ++num_skipped; /* unsupp. compression or encryption */ } } /* end if (process_all_files) */ members_processed++; } /* end while-loop (adding files to current block) */ /* save position in central directory so can come back later */ cd_bufstart = G.cur_zipfile_bufstart; cd_inptr = G.inptr; cd_incnt = G.incnt; /*----------------------------------------------------------------------- Second loop: process files in current block, extracting or testing each one. -----------------------------------------------------------------------*/ error = extract_or_test_entrylist(__G__ j, &filnum, &num_bad_pwd, &old_extra_bytes, #ifdef SET_DIR_ATTRIB &num_dirs, &dirlist, #endif error_in_archive); if (error != PK_COOL) { if (error > error_in_archive) error_in_archive = error; /* ...and keep going (unless disk full or user break) */ if (G.disk_full > 1 || error_in_archive == IZ_CTRLC) { /* clear reached_end to signal premature stop ... */ reached_end = FALSE; /* ... and cancel scanning the central directory */ break; } } /* * Jump back to where we were in the central directory, then go and do * the next batch of files. */ #ifdef USE_STRM_INPUT zfseeko(G.zipfd, cd_bufstart, SEEK_SET); G.cur_zipfile_bufstart = zftello(G.zipfd); #else /* !USE_STRM_INPUT */ G.cur_zipfile_bufstart = zlseek(G.zipfd, cd_bufstart, SEEK_SET); #endif /* ?USE_STRM_INPUT */ read(G.zipfd, (char *)G.inbuf, INBUFSIZ); /* been here before... */ G.inptr = cd_inptr; G.incnt = cd_incnt; ++blknum; #ifdef TEST printf("\ncd_bufstart = %ld (%.8lXh)\n", cd_bufstart, cd_bufstart); printf("cur_zipfile_bufstart = %ld (%.8lXh)\n", cur_zipfile_bufstart, cur_zipfile_bufstart); printf("inptr-inbuf = %d\n", G.inptr-G.inbuf); printf("incnt = %d\n\n", G.incnt); #endif } /* end while-loop (blocks of files in central directory) */ /*--------------------------------------------------------------------------- Process the list of deferred symlink extractions and finish up the symbolic links. ---------------------------------------------------------------------------*/ #ifdef SYMLINKS if (G.slink_last != NULL) { if (QCOND2) Info(slide, 0, ((char *)slide, LoadFarString(SymLnkDeferred))); while (G.slink_head != NULL) { set_deferred_symlink(__G__ G.slink_head); /* remove the processed entry from the chain and free its memory */ G.slink_last = G.slink_head; G.slink_head = G.slink_last->next; free(G.slink_last); } G.slink_last = NULL; } #endif /* SYMLINKS */ /*--------------------------------------------------------------------------- Go back through saved list of directories, sort and set times/perms/UIDs and GIDs from the deepest level on up. ---------------------------------------------------------------------------*/ #ifdef SET_DIR_ATTRIB if (num_dirs > 0) { sorted_dirlist = (direntry **)malloc(num_dirs*sizeof(direntry *)); if (sorted_dirlist == (direntry **)NULL) { Info(slide, 0x401, ((char *)slide, LoadFarString(DirlistSortNoMem))); while (dirlist != (direntry *)NULL) { direntry *d = dirlist; dirlist = dirlist->next; free(d); } } else { ulg ndirs_fail = 0; if (num_dirs == 1) sorted_dirlist[0] = dirlist; else { for (i = 0; i < num_dirs; ++i) { sorted_dirlist[i] = dirlist; dirlist = dirlist->next; } qsort((char *)sorted_dirlist, num_dirs, sizeof(direntry *), dircomp); } Trace((stderr, "setting directory times/perms/attributes\n")); for (i = 0; i < num_dirs; ++i) { direntry *d = sorted_dirlist[i]; Trace((stderr, "dir = %s\n", d->fn)); if ((error = set_direc_attribs(__G__ d)) != PK_OK) { ndirs_fail++; Info(slide, 0x201, ((char *)slide, LoadFarString(DirlistSetAttrFailed), d->fn)); if (!error_in_archive) error_in_archive = error; } free(d); } free(sorted_dirlist); if (!uO.tflag && QCOND2) { if (ndirs_fail > 0) Info(slide, 0, ((char *)slide, LoadFarString(DirlistFailAttrSum), ndirs_fail)); } } } #endif /* SET_DIR_ATTRIB */ /*--------------------------------------------------------------------------- Check for unmatched filespecs on command line and print warning if any found. Free allocated memory. (But suppress check when central dir scan was interrupted prematurely.) ---------------------------------------------------------------------------*/ if (fn_matched) { if (reached_end) for (i = 0; i < G.filespecs; ++i) if (!fn_matched[i]) { #ifdef DLL if (!G.redirect_data && !G.redirect_text) Info(slide, 0x401, ((char *)slide, LoadFarString(FilenameNotMatched), G.pfnames[i])); else setFileNotFound(__G); #else Info(slide, 1, ((char *)slide, LoadFarString(FilenameNotMatched), G.pfnames[i])); #endif if (error_in_archive <= PK_WARN) error_in_archive = PK_FIND; /* some files not found */ } free((zvoid *)fn_matched); } if (xn_matched) { if (reached_end) for (i = 0; i < G.xfilespecs; ++i) if (!xn_matched[i]) Info(slide, 0x401, ((char *)slide, LoadFarString(ExclFilenameNotMatched), G.pxnames[i])); free((zvoid *)xn_matched); } /*--------------------------------------------------------------------------- Now, all locally allocated memory has been released. When the central directory processing has been interrupted prematurely, it is safe to return immediately. All completeness checks and summary messages are skipped in this case. ---------------------------------------------------------------------------*/ if (!reached_end) return error_in_archive; /*--------------------------------------------------------------------------- Double-check that we're back at the end-of-central-directory record, and print quick summary of results, if we were just testing the archive. We send the summary to stdout so that people doing the testing in the back- ground and redirecting to a file can just do a "tail" on the output file. ---------------------------------------------------------------------------*/ #ifndef SFX if (no_endsig_found) { /* just to make sure */ Info(slide, 0x401, ((char *)slide, LoadFarString(EndSigMsg))); Info(slide, 0x401, ((char *)slide, LoadFarString(ReportMsg))); if (!error_in_archive) /* don't overwrite stronger error */ error_in_archive = PK_WARN; } #endif /* !SFX */ if (uO.tflag) { ulg num = filnum - num_bad_pwd; if (uO.qflag < 2) { /* GRR 930710: was (uO.qflag == 1) */ if (error_in_archive) Info(slide, 0, ((char *)slide, LoadFarString(ErrorInArchive), (error_in_archive == PK_WARN)? "warning-" : "", G.zipfn)); else if (num == 0L) Info(slide, 0, ((char *)slide, LoadFarString(ZeroFilesTested), G.zipfn)); else if (G.process_all_files && (num_skipped+num_bad_pwd == 0L)) Info(slide, 0, ((char *)slide, LoadFarString(NoErrInCompData), G.zipfn)); else Info(slide, 0, ((char *)slide, LoadFarString(NoErrInTestedFiles) , G.zipfn, num, (num==1L)? "":"s")); if (num_skipped > 0L) Info(slide, 0, ((char *)slide, LoadFarString(FilesSkipped), num_skipped, (num_skipped==1L)? "":"s")); #if CRYPT if (num_bad_pwd > 0L) Info(slide, 0, ((char *)slide, LoadFarString(FilesSkipBadPasswd) , num_bad_pwd, (num_bad_pwd==1L)? "":"s")); #endif /* CRYPT */ } } /* give warning if files not tested or extracted (first condition can still * happen if zipfile is empty and no files specified on command line) */ if ((filnum == 0) && error_in_archive <= PK_WARN) { if (num_skipped > 0L) error_in_archive = IZ_UNSUP; /* unsupport. compression/encryption */ else error_in_archive = PK_FIND; /* no files found at all */ } #if CRYPT else if ((filnum == num_bad_pwd) && error_in_archive <= PK_WARN) error_in_archive = IZ_BADPWD; /* bad passwd => all files skipped */ #endif else if ((num_skipped > 0L) && error_in_archive <= PK_WARN) error_in_archive = IZ_UNSUP; /* was PK_WARN; Jean-loup complained */ #if CRYPT else if ((num_bad_pwd > 0L) && !error_in_archive) error_in_archive = PK_WARN; #endif return error_in_archive; } /* end function extract_or_test_files() */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'Detect and reject a zip bomb using overlapped entries. This detects an invalid zip file that has at least one entry that overlaps with another entry or with the central directory to the end of the file. A Fifield zip bomb uses overlapped local entries to vastly increase the potential inflation ratio. Such an invalid zip file is rejected. See https://www.bamsoftware.com/hacks/zipbomb/ for David Fifield's analysis, construction, and examples of such zip bombs. The detection maintains a list of covered spans of the zip files so far, where the central directory to the end of the file and any bytes preceding the first entry at zip file offset zero are considered covered initially. Then as each entry is decompressed or tested, it is considered covered. When a new entry is about to be processed, its initial offset is checked to see if it is contained by a covered span. If so, the zip file is rejected as invalid. This commit depends on a preceding commit: "Fix bug in undefer_input() that misplaced the input state."'</s>
<s>[INST] Given the following code containing errors, provide 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 l2cap_do_start(struct l2cap_chan *chan) { struct l2cap_conn *conn = chan->conn; if (conn->hcon->type == LE_LINK) { l2cap_le_start(chan); return; } if (!(conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_SENT)) { l2cap_request_info(conn); return; } if (!(conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_DONE)) return; if (l2cap_chan_check_security(chan, true) && __l2cap_no_conn_pending(chan)) l2cap_start_connection(chan); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-327'], 'message': 'Bluetooth: Fix regression with minimum encryption key size alignment When trying to align the minimum encryption key size requirement for Bluetooth connections, it turns out doing this in a central location in the HCI connection handling code is not possible. Original Bluetooth version up to 2.0 used a security model where the L2CAP service would enforce authentication and encryption. Starting with Bluetooth 2.1 and Secure Simple Pairing that model has changed into that the connection initiator is responsible for providing an encrypted ACL link before any L2CAP communication can happen. Now connecting Bluetooth 2.1 or later devices with Bluetooth 2.0 and before devices are causing a regression. The encryption key size check needs to be moved out of the HCI connection handling into the L2CAP channel setup. To achieve this, the current check inside hci_conn_security() has been moved into l2cap_check_enc_key_size() helper function and then called from four decisions point inside L2CAP to cover all combinations of Secure Simple Pairing enabled devices and device using legacy pairing and legacy service security model. Fixes: d5bb334a8e17 ("Bluetooth: Align minimum encryption key size for LE and BR/EDR connections") Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=203643 Signed-off-by: Marcel Holtmann <marcel@holtmann.org> Cc: stable@vger.kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void CiffDirectory::readDirectory(const byte* pData, uint32_t size, ByteOrder byteOrder) { if (size < 4) throw Error(kerCorruptedMetadata); uint32_t o = getULong(pData + size - 4, byteOrder); if ( o+2 > size ) throw Error(kerCorruptedMetadata); uint16_t count = getUShort(pData + o, byteOrder); #ifdef DEBUG std::cout << "Directory at offset " << std::dec << o <<", " << count << " entries \n"; #endif o += 2; if ( (o + (count * 10)) > size ) throw Error(kerCorruptedMetadata); for (uint16_t i = 0; i < count; ++i) { uint16_t tag = getUShort(pData + o, byteOrder); CiffComponent::AutoPtr m; switch (CiffComponent::typeId(tag)) { case directory: m = CiffComponent::AutoPtr(new CiffDirectory); break; default: m = CiffComponent::AutoPtr(new CiffEntry); break; } m->setDir(this->tag()); m->read(pData, size, o, byteOrder); add(m); o += 10; } } // CiffDirectory::readDirectory ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Avoid integer overflow.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { goto LABEL_SKIP; } else { int compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': '[MJ2] To avoid divisions by zero / undefined behaviour on shift Signed-off-by: Young_X <YangX92@hotmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xsltFormatNumberConversion(xsltDecimalFormatPtr self, xmlChar *format, double number, xmlChar **result) { xmlXPathError status = XPATH_EXPRESSION_OK; xmlBufferPtr buffer; xmlChar *the_format, *prefix = NULL, *suffix = NULL; xmlChar *nprefix, *nsuffix = NULL; xmlChar pchar; int prefix_length, suffix_length = 0, nprefix_length, nsuffix_length; double scale; int j, len; int self_grouping_len; xsltFormatNumberInfo format_info; /* * delayed_multiplier allows a 'trailing' percent or * permille to be treated as suffix */ int delayed_multiplier = 0; /* flag to show no -ve format present for -ve number */ char default_sign = 0; /* flag to show error found, should use default format */ char found_error = 0; if (xmlStrlen(format) <= 0) { xsltTransformError(NULL, NULL, NULL, "xsltFormatNumberConversion : " "Invalid format (0-length)\n"); } *result = NULL; switch (xmlXPathIsInf(number)) { case -1: if (self->minusSign == NULL) *result = xmlStrdup(BAD_CAST "-"); else *result = xmlStrdup(self->minusSign); /* no-break on purpose */ case 1: if ((self == NULL) || (self->infinity == NULL)) *result = xmlStrcat(*result, BAD_CAST "Infinity"); else *result = xmlStrcat(*result, self->infinity); return(status); default: if (xmlXPathIsNaN(number)) { if ((self == NULL) || (self->noNumber == NULL)) *result = xmlStrdup(BAD_CAST "NaN"); else *result = xmlStrdup(self->noNumber); return(status); } } buffer = xmlBufferCreate(); if (buffer == NULL) { return XPATH_MEMORY_ERROR; } format_info.integer_hash = 0; format_info.integer_digits = 0; format_info.frac_digits = 0; format_info.frac_hash = 0; format_info.group = -1; format_info.multiplier = 1; format_info.add_decimal = FALSE; format_info.is_multiplier_set = FALSE; format_info.is_negative_pattern = FALSE; the_format = format; /* * First we process the +ve pattern to get percent / permille, * as well as main format */ prefix = the_format; prefix_length = xsltFormatNumberPreSuffix(self, &the_format, &format_info); if (prefix_length < 0) { found_error = 1; goto OUTPUT_NUMBER; } /* * Here we process the "number" part of the format. It gets * a little messy because of the percent/per-mille - if that * appears at the end, it may be part of the suffix instead * of part of the number, so the variable delayed_multiplier * is used to handle it */ self_grouping_len = xmlStrlen(self->grouping); while ((*the_format != 0) && (xsltUTF8Charcmp(the_format, self->decimalPoint) != 0) && (xsltUTF8Charcmp(the_format, self->patternSeparator) != 0)) { if (delayed_multiplier != 0) { format_info.multiplier = delayed_multiplier; format_info.is_multiplier_set = TRUE; delayed_multiplier = 0; } if (xsltUTF8Charcmp(the_format, self->digit) == 0) { if (format_info.integer_digits > 0) { found_error = 1; goto OUTPUT_NUMBER; } format_info.integer_hash++; if (format_info.group >= 0) format_info.group++; } else if (xsltUTF8Charcmp(the_format, self->zeroDigit) == 0) { format_info.integer_digits++; if (format_info.group >= 0) format_info.group++; } else if ((self_grouping_len > 0) && (!xmlStrncmp(the_format, self->grouping, self_grouping_len))) { /* Reset group count */ format_info.group = 0; the_format += self_grouping_len; continue; } else if (xsltUTF8Charcmp(the_format, self->percent) == 0) { if (format_info.is_multiplier_set) { found_error = 1; goto OUTPUT_NUMBER; } delayed_multiplier = 100; } else if (xsltUTF8Charcmp(the_format, self->permille) == 0) { if (format_info.is_multiplier_set) { found_error = 1; goto OUTPUT_NUMBER; } delayed_multiplier = 1000; } else break; /* while */ if ((len=xmlUTF8Strsize(the_format, 1)) < 1) { found_error = 1; goto OUTPUT_NUMBER; } the_format += len; } /* We have finished the integer part, now work on fraction */ if ( (*the_format != 0) && (xsltUTF8Charcmp(the_format, self->decimalPoint) == 0) ) { format_info.add_decimal = TRUE; if ((len = xmlUTF8Strsize(the_format, 1)) < 1) { found_error = 1; goto OUTPUT_NUMBER; } the_format += len; /* Skip over the decimal */ } while (*the_format != 0) { if (xsltUTF8Charcmp(the_format, self->zeroDigit) == 0) { if (format_info.frac_hash != 0) { found_error = 1; goto OUTPUT_NUMBER; } format_info.frac_digits++; } else if (xsltUTF8Charcmp(the_format, self->digit) == 0) { format_info.frac_hash++; } else if (xsltUTF8Charcmp(the_format, self->percent) == 0) { if (format_info.is_multiplier_set) { found_error = 1; goto OUTPUT_NUMBER; } delayed_multiplier = 100; if ((len = xmlUTF8Strsize(the_format, 1)) < 1) { found_error = 1; goto OUTPUT_NUMBER; } the_format += len; continue; /* while */ } else if (xsltUTF8Charcmp(the_format, self->permille) == 0) { if (format_info.is_multiplier_set) { found_error = 1; goto OUTPUT_NUMBER; } delayed_multiplier = 1000; if ((len = xmlUTF8Strsize(the_format, 1)) < 1) { found_error = 1; goto OUTPUT_NUMBER; } the_format += len; continue; /* while */ } else if (xsltUTF8Charcmp(the_format, self->grouping) != 0) { break; /* while */ } if ((len = xmlUTF8Strsize(the_format, 1)) < 1) { found_error = 1; goto OUTPUT_NUMBER; } the_format += len; if (delayed_multiplier != 0) { format_info.multiplier = delayed_multiplier; delayed_multiplier = 0; format_info.is_multiplier_set = TRUE; } } /* * If delayed_multiplier is set after processing the * "number" part, should be in suffix */ if (delayed_multiplier != 0) { the_format -= len; delayed_multiplier = 0; } suffix = the_format; suffix_length = xsltFormatNumberPreSuffix(self, &the_format, &format_info); if ( (suffix_length < 0) || ((*the_format != 0) && (xsltUTF8Charcmp(the_format, self->patternSeparator) != 0)) ) { found_error = 1; goto OUTPUT_NUMBER; } /* * We have processed the +ve prefix, number part and +ve suffix. * If the number is -ve, we must substitute the -ve prefix / suffix */ if (number < 0) { /* * Note that j is the number of UTF8 chars before the separator, * not the number of bytes! (bug 151975) */ j = xmlUTF8Strloc(format, self->patternSeparator); if (j < 0) { /* No -ve pattern present, so use default signing */ default_sign = 1; } else { /* Skip over pattern separator (accounting for UTF8) */ the_format = (xmlChar *)xmlUTF8Strpos(format, j + 1); /* * Flag changes interpretation of percent/permille * in -ve pattern */ format_info.is_negative_pattern = TRUE; format_info.is_multiplier_set = FALSE; /* First do the -ve prefix */ nprefix = the_format; nprefix_length = xsltFormatNumberPreSuffix(self, &the_format, &format_info); if (nprefix_length<0) { found_error = 1; goto OUTPUT_NUMBER; } while (*the_format != 0) { if ( (xsltUTF8Charcmp(the_format, (self)->percent) == 0) || (xsltUTF8Charcmp(the_format, (self)->permille)== 0) ) { if (format_info.is_multiplier_set) { found_error = 1; goto OUTPUT_NUMBER; } format_info.is_multiplier_set = TRUE; delayed_multiplier = 1; } else if (IS_SPECIAL(self, the_format)) delayed_multiplier = 0; else break; /* while */ if ((len = xmlUTF8Strsize(the_format, 1)) < 1) { found_error = 1; goto OUTPUT_NUMBER; } the_format += len; } if (delayed_multiplier != 0) { format_info.is_multiplier_set = FALSE; the_format -= len; } /* Finally do the -ve suffix */ if (*the_format != 0) { nsuffix = the_format; nsuffix_length = xsltFormatNumberPreSuffix(self, &the_format, &format_info); if (nsuffix_length < 0) { found_error = 1; goto OUTPUT_NUMBER; } } else nsuffix_length = 0; if (*the_format != 0) { found_error = 1; goto OUTPUT_NUMBER; } /* * Here's another Java peculiarity: * if -ve prefix/suffix == +ve ones, discard & use default */ if ((nprefix_length != prefix_length) || (nsuffix_length != suffix_length) || ((nprefix_length > 0) && (xmlStrncmp(nprefix, prefix, prefix_length) !=0 )) || ((nsuffix_length > 0) && (xmlStrncmp(nsuffix, suffix, suffix_length) !=0 ))) { prefix = nprefix; prefix_length = nprefix_length; suffix = nsuffix; suffix_length = nsuffix_length; } /* else { default_sign = 1; } */ } } OUTPUT_NUMBER: if (found_error != 0) { xsltTransformError(NULL, NULL, NULL, "xsltFormatNumberConversion : " "error in format string '%s', using default\n", format); default_sign = (number < 0.0) ? 1 : 0; prefix_length = suffix_length = 0; format_info.integer_hash = 0; format_info.integer_digits = 1; format_info.frac_digits = 1; format_info.frac_hash = 4; format_info.group = -1; format_info.multiplier = 1; format_info.add_decimal = TRUE; } /* Ready to output our number. First see if "default sign" is required */ if (default_sign != 0) xmlBufferAdd(buffer, self->minusSign, xmlUTF8Strsize(self->minusSign, 1)); /* Put the prefix into the buffer */ for (j = 0; j < prefix_length; j++) { if ((pchar = *prefix++) == SYMBOL_QUOTE) { len = xmlUTF8Strsize(prefix, 1); xmlBufferAdd(buffer, prefix, len); prefix += len; j += len - 1; /* length of symbol less length of quote */ } else xmlBufferAdd(buffer, &pchar, 1); } /* Next do the integer part of the number */ number = fabs(number) * (double)format_info.multiplier; scale = pow(10.0, (double)(format_info.frac_digits + format_info.frac_hash)); number = floor((scale * number + 0.5)) / scale; if ((self->grouping != NULL) && (self->grouping[0] != 0)) { len = xmlStrlen(self->grouping); pchar = xsltGetUTF8Char(self->grouping, &len); xsltNumberFormatDecimal(buffer, floor(number), self->zeroDigit[0], format_info.integer_digits, format_info.group, pchar, len); } else xsltNumberFormatDecimal(buffer, floor(number), self->zeroDigit[0], format_info.integer_digits, format_info.group, ',', 1); /* Special case: java treats '.#' like '.0', '.##' like '.0#', etc. */ if ((format_info.integer_digits + format_info.integer_hash + format_info.frac_digits == 0) && (format_info.frac_hash > 0)) { ++format_info.frac_digits; --format_info.frac_hash; } /* Add leading zero, if required */ if ((floor(number) == 0) && (format_info.integer_digits + format_info.frac_digits == 0)) { xmlBufferAdd(buffer, self->zeroDigit, xmlUTF8Strsize(self->zeroDigit, 1)); } /* Next the fractional part, if required */ if (format_info.frac_digits + format_info.frac_hash == 0) { if (format_info.add_decimal) xmlBufferAdd(buffer, self->decimalPoint, xmlUTF8Strsize(self->decimalPoint, 1)); } else { number -= floor(number); if ((number != 0) || (format_info.frac_digits != 0)) { xmlBufferAdd(buffer, self->decimalPoint, xmlUTF8Strsize(self->decimalPoint, 1)); number = floor(scale * number + 0.5); for (j = format_info.frac_hash; j > 0; j--) { if (fmod(number, 10.0) >= 1.0) break; /* for */ number /= 10.0; } xsltNumberFormatDecimal(buffer, floor(number), self->zeroDigit[0], format_info.frac_digits + j, 0, 0, 0); } } /* Put the suffix into the buffer */ for (j = 0; j < suffix_length; j++) { if ((pchar = *suffix++) == SYMBOL_QUOTE) { len = xmlUTF8Strsize(suffix, 1); xmlBufferAdd(buffer, suffix, len); suffix += len; j += len - 1; /* length of symbol less length of escape */ } else xmlBufferAdd(buffer, &pchar, 1); } *result = xmlStrdup(xmlBufferContent(buffer)); xmlBufferFree(buffer); return status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-843'], 'message': 'Fix uninitialized read with UTF-8 grouping chars The character type in xsltFormatNumberConversion was too narrow and an invalid character/length combination could be passed to xsltNumberFormatDecimal, resulting in an uninitialized read. Found by OSS-Fuzz.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: compile_length_bag_node(BagNode* node, regex_t* reg) { int len; int tlen; if (node->type == BAG_OPTION) return compile_length_option_node(node, reg); if (NODE_BAG_BODY(node)) { tlen = compile_length_tree(NODE_BAG_BODY(node), reg); if (tlen < 0) return tlen; } else tlen = 0; switch (node->type) { case BAG_MEMORY: #ifdef USE_CALL if (node->m.regnum == 0 && NODE_IS_CALLED(node)) { len = tlen + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN; return len; } if (NODE_IS_CALLED(node)) { len = SIZE_OP_MEMORY_START_PUSH + tlen + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN; if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)) len += (NODE_IS_RECURSION(node) ? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_PUSH); else len += (NODE_IS_RECURSION(node) ? SIZE_OP_MEMORY_END_REC : SIZE_OP_MEMORY_END); } else if (NODE_IS_RECURSION(node)) { len = SIZE_OP_MEMORY_START_PUSH; len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum) ? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_REC); } else #endif { if (MEM_STATUS_AT0(reg->bt_mem_start, node->m.regnum)) len = SIZE_OP_MEMORY_START_PUSH; else len = SIZE_OP_MEMORY_START; len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum) ? SIZE_OP_MEMORY_END_PUSH : SIZE_OP_MEMORY_END); } break; case BAG_STOP_BACKTRACK: if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) { int v; QuantNode* qn; qn = QUANT_(NODE_BAG_BODY(node)); tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg); if (tlen < 0) return tlen; v = onig_positive_int_multiply(qn->lower, tlen); if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; len = v + SIZE_OP_PUSH + tlen + SIZE_OP_POP_OUT + SIZE_OP_JUMP; } else { len = SIZE_OP_ATOMIC_START + tlen + SIZE_OP_ATOMIC_END; } break; case BAG_IF_ELSE: { Node* cond = NODE_BAG_BODY(node); Node* Then = node->te.Then; Node* Else = node->te.Else; len = compile_length_tree(cond, reg); if (len < 0) return len; len += SIZE_OP_PUSH; len += SIZE_OP_ATOMIC_START + SIZE_OP_ATOMIC_END; if (IS_NOT_NULL(Then)) { tlen = compile_length_tree(Then, reg); if (tlen < 0) return tlen; len += tlen; } if (IS_NOT_NULL(Else)) { len += SIZE_OP_JUMP; tlen = compile_length_tree(Else, reg); if (tlen < 0) return tlen; len += tlen; } } break; case BAG_OPTION: /* never come here, but set for escape warning */ len = 0; break; } return len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'Fix CVE-2019-13225: problem in converting if-then-else pattern to bytecode.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info, const int argc,const char **argv,Image **images,ExceptionInfo *exception) { const char *option; ImageInfo *mogrify_info; MagickStatusType status; PixelInterpolateMethod interpolate_method; QuantizeInfo *quantize_info; register ssize_t i; ssize_t count, index; /* Apply options to the image list. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image **) NULL); assert((*images)->previous == (Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); if ((argc <= 0) || (*argv == (char *) NULL)) return(MagickTrue); interpolate_method=UndefinedInterpolatePixel; mogrify_info=CloneImageInfo(image_info); quantize_info=AcquireQuantizeInfo(mogrify_info); status=MagickTrue; for (i=0; i < (ssize_t) argc; i++) { if (*images == (Image *) NULL) break; option=argv[i]; if (IsCommandOption(option) == MagickFalse) continue; count=ParseCommandOption(MagickCommandOptions,MagickFalse,option); count=MagickMax(count,0L); if ((i+count) >= (ssize_t) argc) break; status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception); switch (*(option+1)) { case 'a': { if (LocaleCompare("affinity",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare("append",option+1) == 0) { Image *append_image; (void) SyncImagesSettings(mogrify_info,*images,exception); append_image=AppendImages(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (append_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=append_image; break; } if (LocaleCompare("average",option+1) == 0) { Image *average_image; /* Average an image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); average_image=EvaluateImages(*images,MeanEvaluateOperator, exception); if (average_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=average_image; break; } break; } case 'c': { if (LocaleCompare("channel-fx",option+1) == 0) { Image *channel_image; (void) SyncImagesSettings(mogrify_info,*images,exception); channel_image=ChannelFxImage(*images,argv[i+1],exception); if (channel_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=channel_image; break; } if (LocaleCompare("clut",option+1) == 0) { Image *clut_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); clut_image=RemoveFirstImageFromList(images); if (clut_image == (Image *) NULL) { status=MagickFalse; break; } (void) ClutImage(image,clut_image,interpolate_method,exception); clut_image=DestroyImage(clut_image); *images=DestroyImageList(*images); *images=image; break; } if (LocaleCompare("coalesce",option+1) == 0) { Image *coalesce_image; (void) SyncImagesSettings(mogrify_info,*images,exception); coalesce_image=CoalesceImages(*images,exception); if (coalesce_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=coalesce_image; break; } if (LocaleCompare("combine",option+1) == 0) { ColorspaceType colorspace; Image *combine_image; (void) SyncImagesSettings(mogrify_info,*images,exception); colorspace=(*images)->colorspace; if ((*images)->number_channels < GetImageListLength(*images)) colorspace=sRGBColorspace; if (*option == '+') colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,argv[i+1]); combine_image=CombineImages(*images,colorspace,exception); if (combine_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=combine_image; break; } if (LocaleCompare("compare",option+1) == 0) { double distortion; Image *difference_image, *image, *reconstruct_image; MetricType metric; /* Mathematically and visually annotate the difference between an image and its reconstruction. */ (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); reconstruct_image=RemoveFirstImageFromList(images); if (reconstruct_image == (Image *) NULL) { status=MagickFalse; break; } metric=UndefinedErrorMetric; option=GetImageOption(mogrify_info,"metric"); if (option != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,option); difference_image=CompareImages(image,reconstruct_image,metric, &distortion,exception); if (difference_image == (Image *) NULL) break; if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=difference_image; break; } if (LocaleCompare("complex",option+1) == 0) { ComplexOperator op; Image *complex_images; (void) SyncImageSettings(mogrify_info,*images,exception); op=(ComplexOperator) ParseCommandOption(MagickComplexOptions, MagickFalse,argv[i+1]); complex_images=ComplexImages(*images,op,exception); if (complex_images == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=complex_images; break; } if (LocaleCompare("composite",option+1) == 0) { CompositeOperator compose; const char* value; MagickBooleanType clip_to_self; Image *mask_image, *new_images, *source_image; RectangleInfo geometry; /* Compose value from "-compose" option only */ (void) SyncImageSettings(mogrify_info,*images,exception); value=GetImageOption(mogrify_info,"compose"); if (value == (const char *) NULL) compose=OverCompositeOp; /* use Over not source_image->compose */ else compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,value); /* Get "clip-to-self" expert setting (false is normal) */ clip_to_self=GetCompositeClipToSelf(compose); value=GetImageOption(mogrify_info,"compose:clip-to-self"); if (value != (const char *) NULL) clip_to_self=IsStringTrue(value); value=GetImageOption(mogrify_info,"compose:outside-overlay"); if (value != (const char *) NULL) clip_to_self=IsStringFalse(value); /* deprecated */ new_images=RemoveFirstImageFromList(images); source_image=RemoveFirstImageFromList(images); if (source_image == (Image *) NULL) break; /* FUTURE - produce Exception, rather than silent fail */ /* FUTURE: this should not be here! - should be part of -geometry */ if (source_image->geometry != (char *) NULL) { RectangleInfo resize_geometry; (void) ParseRegionGeometry(source_image,source_image->geometry, &resize_geometry,exception); if ((source_image->columns != resize_geometry.width) || (source_image->rows != resize_geometry.height)) { Image *resize_image; resize_image=ResizeImage(source_image,resize_geometry.width, resize_geometry.height,source_image->filter,exception); if (resize_image != (Image *) NULL) { source_image=DestroyImage(source_image); source_image=resize_image; } } } SetGeometry(source_image,&geometry); (void) ParseAbsoluteGeometry(source_image->geometry,&geometry); GravityAdjustGeometry(new_images->columns,new_images->rows, new_images->gravity,&geometry); mask_image=RemoveFirstImageFromList(images); if (mask_image == (Image *) NULL) status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); else { if ((compose == DisplaceCompositeOp) || (compose == DistortCompositeOp)) { status&=CompositeImage(source_image,mask_image, CopyGreenCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); } else { Image *clone_image; clone_image=CloneImage(new_images,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) break; status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); status&=CompositeImage(new_images,mask_image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(clone_image,new_images, OverCompositeOp,clip_to_self,0,0,exception); new_images=DestroyImageList(new_images); new_images=clone_image; } mask_image=DestroyImage(mask_image); } source_image=DestroyImage(source_image); *images=DestroyImageList(*images); *images=new_images; break; } if (LocaleCompare("copy",option+1) == 0) { Image *source_image; OffsetInfo offset; RectangleInfo geometry; /* Copy image pixels. */ (void) SyncImageSettings(mogrify_info,*images,exception); (void) ParsePageGeometry(*images,argv[i+2],&geometry,exception); offset.x=geometry.x; offset.y=geometry.y; source_image=(*images); if (source_image->next != (Image *) NULL) source_image=source_image->next; (void) ParsePageGeometry(source_image,argv[i+1],&geometry, exception); status=CopyImagePixels(*images,source_image,&geometry,&offset, exception); break; } break; } case 'd': { if (LocaleCompare("deconstruct",option+1) == 0) { Image *deconstruct_image; (void) SyncImagesSettings(mogrify_info,*images,exception); deconstruct_image=CompareImagesLayers(*images,CompareAnyLayer, exception); if (deconstruct_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=deconstruct_image; break; } if (LocaleCompare("delete",option+1) == 0) { if (*option == '+') DeleteImages(images,"-1",exception); else DeleteImages(images,argv[i+1],exception); break; } if (LocaleCompare("dither",option+1) == 0) { if (*option == '+') { quantize_info->dither_method=NoDitherMethod; break; } quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare("duplicate",option+1) == 0) { Image *duplicate_images; if (*option == '+') duplicate_images=DuplicateImages(*images,1,"-1",exception); else { const char *p; size_t number_duplicates; number_duplicates=(size_t) StringToLong(argv[i+1]); p=strchr(argv[i+1],','); if (p == (const char *) NULL) duplicate_images=DuplicateImages(*images,number_duplicates, "-1",exception); else duplicate_images=DuplicateImages(*images,number_duplicates,p, exception); } AppendImageToList(images, duplicate_images); (void) SyncImagesSettings(mogrify_info,*images,exception); break; } break; } case 'e': { if (LocaleCompare("evaluate-sequence",option+1) == 0) { Image *evaluate_image; MagickEvaluateOperator op; (void) SyncImageSettings(mogrify_info,*images,exception); op=(MagickEvaluateOperator) ParseCommandOption( MagickEvaluateOptions,MagickFalse,argv[i+1]); evaluate_image=EvaluateImages(*images,op,exception); if (evaluate_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=evaluate_image; break; } break; } case 'f': { if (LocaleCompare("fft",option+1) == 0) { Image *fourier_image; /* Implements the discrete Fourier transform (DFT). */ (void) SyncImageSettings(mogrify_info,*images,exception); fourier_image=ForwardFourierTransformImage(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("flatten",option+1) == 0) { Image *flatten_image; (void) SyncImagesSettings(mogrify_info,*images,exception); flatten_image=MergeImageLayers(*images,FlattenLayer,exception); if (flatten_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=flatten_image; break; } if (LocaleCompare("fx",option+1) == 0) { Image *fx_image; (void) SyncImagesSettings(mogrify_info,*images,exception); fx_image=FxImage(*images,argv[i+1],exception); if (fx_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=fx_image; break; } break; } case 'h': { if (LocaleCompare("hald-clut",option+1) == 0) { Image *hald_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); hald_image=RemoveFirstImageFromList(images); if (hald_image == (Image *) NULL) { status=MagickFalse; break; } (void) HaldClutImage(image,hald_image,exception); hald_image=DestroyImage(hald_image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=image; break; } break; } case 'i': { if (LocaleCompare("ift",option+1) == 0) { Image *fourier_image, *magnitude_image, *phase_image; /* Implements the inverse fourier discrete Fourier transform (DFT). */ (void) SyncImagesSettings(mogrify_info,*images,exception); magnitude_image=RemoveFirstImageFromList(images); phase_image=RemoveFirstImageFromList(images); if (phase_image == (Image *) NULL) { status=MagickFalse; break; } fourier_image=InverseFourierTransformImage(magnitude_image, phase_image,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("insert",option+1) == 0) { Image *p, *q; index=0; if (*option != '+') index=(ssize_t) StringToLong(argv[i+1]); p=RemoveLastImageFromList(images); if (p == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } q=p; if (index == 0) PrependImageToList(images,q); else if (index == (ssize_t) GetImageListLength(*images)) AppendImageToList(images,q); else { q=GetImageFromList(*images,index-1); if (q == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } InsertImageInList(&q,p); } *images=GetFirstImageInList(q); break; } if (LocaleCompare("interpolate",option+1) == 0) { interpolate_method=(PixelInterpolateMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,argv[i+1]); break; } break; } case 'l': { if (LocaleCompare("layers",option+1) == 0) { Image *layers; LayerMethod method; (void) SyncImagesSettings(mogrify_info,*images,exception); layers=(Image *) NULL; method=(LayerMethod) ParseCommandOption(MagickLayerOptions, MagickFalse,argv[i+1]); switch (method) { case CoalesceLayer: { layers=CoalesceImages(*images,exception); break; } case CompareAnyLayer: case CompareClearLayer: case CompareOverlayLayer: default: { layers=CompareImagesLayers(*images,method,exception); break; } case MergeLayer: case FlattenLayer: case MosaicLayer: case TrimBoundsLayer: { layers=MergeImageLayers(*images,method,exception); break; } case DisposeLayer: { layers=DisposeImages(*images,exception); break; } case OptimizeImageLayer: { layers=OptimizeImageLayers(*images,exception); break; } case OptimizePlusLayer: { layers=OptimizePlusImageLayers(*images,exception); break; } case OptimizeTransLayer: { OptimizeImageTransparency(*images,exception); break; } case RemoveDupsLayer: { RemoveDuplicateLayers(images,exception); break; } case RemoveZeroLayer: { RemoveZeroDelayLayers(images,exception); break; } case OptimizeLayer: { /* General Purpose, GIF Animation Optimizer. */ layers=CoalesceImages(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=OptimizeImageLayers(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=(Image *) NULL; OptimizeImageTransparency(*images,exception); (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } case CompositeLayer: { CompositeOperator compose; Image *source; RectangleInfo geometry; /* Split image sequence at the first 'NULL:' image. */ source=(*images); while (source != (Image *) NULL) { source=GetNextImageInList(source); if ((source != (Image *) NULL) && (LocaleCompare(source->magick,"NULL") == 0)) break; } if (source != (Image *) NULL) { if ((GetPreviousImageInList(source) == (Image *) NULL) || (GetNextImageInList(source) == (Image *) NULL)) source=(Image *) NULL; else { /* Separate the two lists, junk the null: image. */ source=SplitImageList(source->previous); DeleteImageFromList(&source); } } if (source == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"MissingNullSeparator","layers Composite"); status=MagickFalse; break; } /* Adjust offset with gravity and virtual canvas. */ SetGeometry(*images,&geometry); (void) ParseAbsoluteGeometry((*images)->geometry,&geometry); geometry.width=source->page.width != 0 ? source->page.width : source->columns; geometry.height=source->page.height != 0 ? source->page.height : source->rows; GravityAdjustGeometry((*images)->page.width != 0 ? (*images)->page.width : (*images)->columns, (*images)->page.height != 0 ? (*images)->page.height : (*images)->rows,(*images)->gravity,&geometry); compose=OverCompositeOp; option=GetImageOption(mogrify_info,"compose"); if (option != (const char *) NULL) compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,option); CompositeLayers(*images,compose,source,geometry.x,geometry.y, exception); source=DestroyImageList(source); break; } } if (layers == (Image *) NULL) break; *images=DestroyImageList(*images); *images=layers; break; } break; } case 'm': { if (LocaleCompare("map",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare("maximum",option+1) == 0) { Image *maximum_image; /* Maximum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception); if (maximum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=maximum_image; break; } if (LocaleCompare("minimum",option+1) == 0) { Image *minimum_image; /* Minimum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception); if (minimum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=minimum_image; break; } if (LocaleCompare("morph",option+1) == 0) { Image *morph_image; (void) SyncImagesSettings(mogrify_info,*images,exception); morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]), exception); if (morph_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=morph_image; break; } if (LocaleCompare("mosaic",option+1) == 0) { Image *mosaic_image; (void) SyncImagesSettings(mogrify_info,*images,exception); mosaic_image=MergeImageLayers(*images,MosaicLayer,exception); if (mosaic_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=mosaic_image; break; } break; } case 'p': { if (LocaleCompare("poly",option+1) == 0) { char *args, token[MagickPathExtent]; const char *p; double *arguments; Image *polynomial_image; register ssize_t x; size_t number_arguments; /* Polynomial image. */ (void) SyncImageSettings(mogrify_info,*images,exception); args=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (args == (char *) NULL) break; p=(char *) args; for (x=0; *p != '\0'; x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); } number_arguments=(size_t) x; arguments=(double *) AcquireQuantumMemory(number_arguments, sizeof(*arguments)); if (arguments == (double *) NULL) ThrowWandFatalException(ResourceLimitFatalError, "MemoryAllocationFailed",(*images)->filename); (void) memset(arguments,0,number_arguments* sizeof(*arguments)); p=(char *) args; for (x=0; (x < (ssize_t) number_arguments) && (*p != '\0'); x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arguments[x]=StringToDouble(token,(char **) NULL); } args=DestroyString(args); polynomial_image=PolynomialImage(*images,number_arguments >> 1, arguments,exception); arguments=(double *) RelinquishMagickMemory(arguments); if (polynomial_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=polynomial_image; } if (LocaleCompare("print",option+1) == 0) { char *string; (void) SyncImagesSettings(mogrify_info,*images,exception); string=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (string == (char *) NULL) break; (void) FormatLocaleFile(stdout,"%s",string); string=DestroyString(string); } if (LocaleCompare("process",option+1) == 0) { char **arguments; int j, number_arguments; (void) SyncImagesSettings(mogrify_info,*images,exception); arguments=StringToArgv(argv[i+1],&number_arguments); if (arguments == (char **) NULL) break; if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL)) { char breaker, quote, *token; const char *argument; int next, token_status; size_t length; TokenInfo *token_info; /* Support old style syntax, filter="-option arg". */ length=strlen(argv[i+1]); token=(char *) NULL; if (~length >= (MagickPathExtent-1)) token=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*token)); if (token == (char *) NULL) break; next=0; argument=argv[i+1]; token_info=AcquireTokenInfo(); token_status=Tokenizer(token_info,0,token,length,argument,"", "=","\"",'\0',&breaker,&next,&quote); token_info=DestroyTokenInfo(token_info); if (token_status == 0) { const char *arg; arg=(&(argument[next])); (void) InvokeDynamicImageFilter(token,&(*images),1,&arg, exception); } token=DestroyString(token); break; } (void) SubstituteString(&arguments[1],"-",""); (void) InvokeDynamicImageFilter(arguments[1],&(*images), number_arguments-2,(const char **) arguments+2,exception); for (j=0; j < number_arguments; j++) arguments[j]=DestroyString(arguments[j]); arguments=(char **) RelinquishMagickMemory(arguments); break; } break; } case 'r': { if (LocaleCompare("reverse",option+1) == 0) { ReverseImageList(images); break; } break; } case 's': { if (LocaleCompare("smush",option+1) == 0) { Image *smush_image; ssize_t offset; (void) SyncImagesSettings(mogrify_info,*images,exception); offset=(ssize_t) StringToLong(argv[i+1]); smush_image=SmushImages(*images,*option == '-' ? MagickTrue : MagickFalse,offset,exception); if (smush_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=smush_image; break; } if (LocaleCompare("swap",option+1) == 0) { Image *p, *q, *u, *v; ssize_t swap_index; index=(-1); swap_index=(-2); if (*option != '+') { GeometryInfo geometry_info; MagickStatusType flags; swap_index=(-1); flags=ParseGeometry(argv[i+1],&geometry_info); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) != 0) swap_index=(ssize_t) geometry_info.sigma; } p=GetImageFromList(*images,index); q=GetImageFromList(*images,swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",(*images)->filename); status=MagickFalse; break; } if (p == q) break; u=CloneImage(p,0,0,MagickTrue,exception); if (u == (Image *) NULL) break; v=CloneImage(q,0,0,MagickTrue,exception); if (v == (Image *) NULL) { u=DestroyImage(u); break; } ReplaceImageInList(&p,v); ReplaceImageInList(&q,u); *images=GetFirstImageInList(q); break; } break; } case 'w': { if (LocaleCompare("write",option+1) == 0) { char key[MagickPathExtent]; Image *write_images; ImageInfo *write_info; (void) SyncImagesSettings(mogrify_info,*images,exception); (void) FormatLocaleString(key,MagickPathExtent,"cache:%s", argv[i+1]); (void) DeleteImageRegistry(key); write_images=(*images); if (*option == '+') write_images=CloneImageList(*images,exception); write_info=CloneImageInfo(mogrify_info); status&=WriteImages(write_info,write_images,argv[i+1],exception); write_info=DestroyImageInfo(write_info); if (*option == '+') write_images=DestroyImageList(write_images); break; } break; } default: break; } i+=count; } quantize_info=DestroyQuantizeInfo(quantize_info); mogrify_info=DestroyImageInfo(mogrify_info); status&=MogrifyImageInfo(image_info,argc,argv,exception); return(status != 0 ? MagickTrue : MagickFalse); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1616'</s>
<s>[INST] Given the following code containing errors, provide 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 MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MagickPathExtent], format, magick[MagickPathExtent]; const char *value; MagickBooleanType status; MagickOffsetType scene; Quantum index; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *q; size_t extent, imageListLength, packet_size; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { QuantumAny max_value; /* Write PNM file header. */ packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MagickPathExtent); max_value=GetQuantumRange(image->depth); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MagickPathExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MagickPathExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MagickPathExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent); if (IdentifyImageMonochrome(image,exception) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent); break; } default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MagickPathExtent); break; } } if (image->alpha_trait != UndefinedPixelTrait) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "TUPLTYPE %s\nENDHDR\n",type); (void) WriteBlobString(image,buffer); } /* Convert runextent encoded to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); *q++=' '; if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToLong(index)); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)), ScaleQuantumToChar(GetPixelGreen(image,p)), ScaleQuantumToChar(GetPixelBlue(image,p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)), ScaleQuantumToShort(GetPixelGreen(image,p)), ScaleQuantumToShort(GetPixelBlue(image,p))); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)), ScaleQuantumToLong(GetPixelGreen(image,p)), ScaleQuantumToLong(GetPixelBlue(image,p))); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { register unsigned char *pixels; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { register unsigned char *pixels; /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)), max_value); else { if (image->depth == 16) pixel=ScaleQuantumToLong(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { register unsigned char *pixels; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { register unsigned char *pixels; /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { register unsigned char *pixels; (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1613'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const double bias, ExceptionInfo *exception) { #define AdaptiveThresholdImageTag "AdaptiveThreshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickSizeType number_pixels; ssize_t y; /* Initialize threshold image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); status=SetImageStorageClass(threshold_image,DirectClass,exception); if (status == MagickFalse) { threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Threshold image. */ status=MagickTrue; progress=0; number_pixels=(MagickSizeType) width*height; image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_bias[MaxPixelChannels], channel_sum[MaxPixelChannels]; register const Quantum *magick_restrict p, *magick_restrict pixels; register Quantum *magick_restrict q; register ssize_t i, x; ssize_t center, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (height/2L),image->columns+width,height,exception); q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ GetPixelChannels(image)*(width/2); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } pixels=p; channel_bias[channel]=0.0; channel_sum[channel]=0.0; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) channel_bias[channel]+=pixels[i]; channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double mean; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } channel_sum[channel]-=channel_bias[channel]; channel_bias[channel]=0.0; pixels=p; for (v=0; v < (ssize_t) height; v++) { channel_bias[channel]+=pixels[i]; pixels+=(width-1)*GetPixelChannels(image); channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image)*(image->columns+1); } mean=(double) (channel_sum[channel]/number_pixels+bias); SetPixelChannel(threshold_image,channel,(Quantum) ((double) p[center+i] <= mean ? 0 : QuantumRange),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(threshold_image); } if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_image->type=image->type; threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1608'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadPCLImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CropBox "CropBox" #define DeviceCMYK "DeviceCMYK" #define MediaBox "MediaBox" #define RenderPCLText " Rendering PCL... " char command[MaxTextExtent], *density, filename[MaxTextExtent], geometry[MaxTextExtent], *options, input_filename[MaxTextExtent]; const DelegateInfo *delegate_info; Image *image, *next_image; ImageInfo *read_info; int c; MagickBooleanType cmyk, status; PointInfo delta; RectangleInfo bounding_box, page; register char *p; SegmentInfo bounds; size_t height, width; ssize_t count; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); /* Open image file. */ image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0)) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } /* Determine page geometry from the PCL media box. */ cmyk=image->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; count=0; (void) memset(&bounding_box,0,sizeof(bounding_box)); (void) memset(&bounds,0,sizeof(bounds)); (void) memset(&page,0,sizeof(page)); (void) memset(command,0,sizeof(command)); p=command; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { if (image_info->page != (char *) NULL) continue; /* Note PCL elements. */ *p++=(char) c; if ((c != (int) '/') && (c != '\n') && ((size_t) (p-command) < (MaxTextExtent-1))) continue; *p='\0'; p=command; /* Is this a CMYK document? */ if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0) cmyk=MagickTrue; if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0) { /* Note region defined by crop box. */ count=(ssize_t) sscanf(command,"CropBox [%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,"CropBox[%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0) { /* Note region defined by media box. */ count=(ssize_t) sscanf(command,"MediaBox [%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,"MediaBox[%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } if (count != 4) continue; /* Set PCL render geometry. */ width=(size_t) floor(bounds.x2-bounds.x1+0.5); height=(size_t) floor(bounds.y2-bounds.y1+0.5); if (width > page.width) page.width=width; if (height > page.height) page.height=height; } (void) CloseBlob(image); /* Render PCL with the GhostPCL delegate. */ if ((page.width == 0) || (page.height == 0)) (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); (void) FormatLocaleString(geometry,MaxTextExtent,"%.20gx%.20g",(double) page.width,(double) page.height); if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo("pcl:mono",(char *) NULL,exception); else if (cmyk != MagickFalse) delegate_info=GetDelegateInfo("pcl:cmyk",(char *) NULL,exception); else delegate_info=GetDelegateInfo("pcl:color",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) return((Image *) NULL); if ((page.width == 0) || (page.height == 0)) (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); density=AcquireString(""); options=AcquireString(""); (void) FormatLocaleString(density,MaxTextExtent,"%gx%g", image->x_resolution,image->y_resolution); page.width=(size_t) floor((double) page.width*image->x_resolution/delta.x+ 0.5); page.height=(size_t) floor((double) page.height*image->y_resolution/delta.y+ 0.5); (void) FormatLocaleString(options,MaxTextExtent,"-g%.20gx%.20g ",(double) page.width,(double) page.height); image=DestroyImage(image); read_info=CloneImageInfo(image_info); *read_info->magick='\0'; if (read_info->number_scenes != 0) { if (read_info->number_scenes != 1) (void) FormatLocaleString(options,MaxTextExtent,"-dLastPage=%.20g", (double) (read_info->scene+read_info->number_scenes)); else (void) FormatLocaleString(options,MaxTextExtent, "-dFirstPage=%.20g -dLastPage=%.20g",(double) read_info->scene+1, (double) (read_info->scene+read_info->number_scenes)); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\0'; } (void) CopyMagickString(filename,read_info->filename,MaxTextExtent); (void) AcquireUniqueFilename(read_info->filename); (void) FormatLocaleString(command,MaxTextExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options, read_info->filename,input_filename); options=DestroyString(options); density=DestroyString(density); status=ExternalDelegateCommand(MagickFalse,read_info->verbose,command, (char *) NULL,exception) != 0 ? MagickTrue : MagickFalse; image=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); (void) RelinquishUniqueFileResource(input_filename); read_info=DestroyImageInfo(read_info); if (image == (Image *) NULL) ThrowReaderException(DelegateError,"PCLDelegateFailed"); if (LocaleCompare(image->magick,"BMP") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(image,&image->exception); if (cmyk_image != (Image *) NULL) { image=DestroyImageList(image); image=cmyk_image; } } do { (void) CopyMagickString(image->filename,filename,MaxTextExtent); image->page=page; next_image=SyncNextImageInList(image); if (next_image != (Image *) NULL) image=next_image; } while (next_image != (Image *) NULL); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1520'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: copy_to_fd (const char *from, int tofd) { int fromfd; ssize_t i; if ((fromfd = safe_open (from, O_RDONLY | O_BINARY, 0)) < 0) pfatal ("Can't reopen file %s", quotearg (from)); while ((i = read (fromfd, buf, bufsize)) != 0) { if (i == (ssize_t) -1) read_fatal (); if (full_write (tofd, buf, i) != i) write_fatal (); } if (close (fromfd) != 0) read_fatal (); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'Don't follow symlinks unless --follow-symlinks is given * src/inp.c (plan_a, plan_b), src/util.c (copy_to_fd, copy_file, append_to_file): Unless the --follow-symlinks option is given, open files with the O_NOFOLLOW flag to avoid following symlinks. So far, we were only doing that consistently for input files. * src/util.c (create_backup): When creating empty backup files, (re)create them with O_CREAT | O_EXCL to avoid following symlinks in that case as well.'</s>
<s>[INST] Given the following code containing errors, provide 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 set_geometry(unsigned int cmd, struct floppy_struct *g, int drive, int type, struct block_device *bdev) { int cnt; /* sanity checking for parameters. */ if (g->sect <= 0 || g->head <= 0 || g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) || /* check if reserved bits are set */ (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0) return -EINVAL; if (type) { if (!capable(CAP_SYS_ADMIN)) return -EPERM; mutex_lock(&open_lock); if (lock_fdc(drive)) { mutex_unlock(&open_lock); return -EINTR; } floppy_type[type] = *g; floppy_type[type].name = "user format"; for (cnt = type << 2; cnt < (type << 2) + 4; cnt++) floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] = floppy_type[type].size + 1; process_fd_request(); for (cnt = 0; cnt < N_DRIVE; cnt++) { struct block_device *bdev = opened_bdev[cnt]; if (!bdev || ITYPE(drive_state[cnt].fd_device) != type) continue; __invalidate_device(bdev, true); } mutex_unlock(&open_lock); } else { int oldStretch; if (lock_fdc(drive)) return -EINTR; if (cmd != FDDEFPRM) { /* notice a disk change immediately, else * we lose our settings immediately*/ if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) return -EINTR; } oldStretch = g->stretch; user_params[drive] = *g; if (buffer_drive == drive) SUPBOUND(buffer_max, user_params[drive].sect); current_type[drive] = &user_params[drive]; floppy_sizes[drive] = user_params[drive].size; if (cmd == FDDEFPRM) DRS->keep_data = -1; else DRS->keep_data = 1; /* invalidation. Invalidate only when needed, i.e. * when there are already sectors in the buffer cache * whose number will change. This is useful, because * mtools often changes the geometry of the disk after * looking at the boot block */ if (DRS->maxblock > user_params[drive].sect || DRS->maxtrack || ((user_params[drive].sect ^ oldStretch) & (FD_SWAPSIDES | FD_SECTBASEMASK))) invalidate_drive(bdev); else process_fd_request(); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'floppy: fix div-by-zero in setup_format_params This fixes a divide by zero error in the setup_format_params function of the floppy driver. Two consecutive ioctls can trigger the bug: The first one should set the drive geometry with such .sect and .rate values for the F_SECT_PER_TRACK to become zero. Next, the floppy format operation should be called. A floppy disk is not required to be inserted. An unprivileged user could trigger the bug if the device is accessible. The patch checks F_SECT_PER_TRACK for a non-zero value in the set_geometry function. The proper check should involve a reasonable upper limit for the .sect and .rate fields, but it could change the UAPI. The patch also checks F_SECT_PER_TRACK in the setup_format_params, and cancels the formatting operation in case of zero. The bug was found by syzkaller. Signed-off-by: Denis Efremov <efremov@ispras.ru> Tested-by: Willy Tarreau <w@1wt.eu> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int cx24116_send_diseqc_msg(struct dvb_frontend *fe, struct dvb_diseqc_master_cmd *d) { struct cx24116_state *state = fe->demodulator_priv; int i, ret; /* Dump DiSEqC message */ if (debug) { printk(KERN_INFO "cx24116: %s(", __func__); for (i = 0 ; i < d->msg_len ;) { printk(KERN_INFO "0x%02x", d->msg[i]); if (++i < d->msg_len) printk(KERN_INFO ", "); } printk(") toneburst=%d\n", toneburst); } /* Validate length */ if (d->msg_len > (CX24116_ARGLEN - CX24116_DISEQC_MSGOFS)) return -EINVAL; /* DiSEqC message */ for (i = 0; i < d->msg_len; i++) state->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i]; /* DiSEqC message length */ state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len; /* Command length */ state->dsec_cmd.len = CX24116_DISEQC_MSGOFS + state->dsec_cmd.args[CX24116_DISEQC_MSGLEN]; /* DiSEqC toneburst */ if (toneburst == CX24116_DISEQC_MESGCACHE) /* Message is cached */ return 0; else if (toneburst == CX24116_DISEQC_TONEOFF) /* Message is sent without burst */ state->dsec_cmd.args[CX24116_DISEQC_BURST] = 0; else if (toneburst == CX24116_DISEQC_TONECACHE) { /* * Message is sent with derived else cached burst * * WRITE PORT GROUP COMMAND 38 * * 0/A/A: E0 10 38 F0..F3 * 1/B/B: E0 10 38 F4..F7 * 2/C/A: E0 10 38 F8..FB * 3/D/B: E0 10 38 FC..FF * * databyte[3]= 8421:8421 * ABCD:WXYZ * CLR :SET * * WX= PORT SELECT 0..3 (X=TONEBURST) * Y = VOLTAGE (0=13V, 1=18V) * Z = BAND (0=LOW, 1=HIGH(22K)) */ if (d->msg_len >= 4 && d->msg[2] == 0x38) state->dsec_cmd.args[CX24116_DISEQC_BURST] = ((d->msg[3] & 4) >> 2); if (debug) dprintk("%s burst=%d\n", __func__, state->dsec_cmd.args[CX24116_DISEQC_BURST]); } /* Wait for LNB ready */ ret = cx24116_wait_for_lnb(fe); if (ret != 0) return ret; /* Wait for voltage/min repeat delay */ msleep(100); /* Command */ ret = cx24116_cmd_execute(fe, &state->dsec_cmd); if (ret != 0) return ret; /* * Wait for send * * Eutelsat spec: * >15ms delay + (XXX determine if FW does this, see set_tone) * 13.5ms per byte + * >15ms delay + * 12.5ms burst + * >15ms delay (XXX determine if FW does this, see set_tone) */ msleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) + ((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60)); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-119', 'CWE-125'], 'message': '[media] cx24116: fix a buffer overflow when checking userspace params The maximum size for a DiSEqC command is 6, according to the userspace API. However, the code allows to write up much more values: drivers/media/dvb-frontends/cx24116.c:983 cx24116_send_diseqc_msg() error: buffer overflow 'd->msg' 6 <= 23 Cc: stable@vger.kernel.org Signed-off-by: Mauro Carvalho Chehab <mchehab@osg.samsung.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: asn1_get_string( unsigned char **buffer, /* IO - Pointer in buffer */ unsigned char *bufend, /* I - End of buffer */ unsigned length, /* I - Value length */ char *string, /* I - String buffer */ size_t strsize) /* I - String buffer size */ { if (length > (unsigned)(bufend - *buffer)) length = (unsigned)(bufend - *buffer); if (length < strsize) { /* * String is smaller than the buffer... */ if (length > 0) memcpy(string, *buffer, length); string[length] = '\0'; } else { /* * String is larger than the buffer... */ memcpy(string, *buffer, strsize - 1); string[strsize - 1] = '\0'; } if (length > 0) (*buffer) += length; return (string); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'Fix multiple security/disclosure issues: - CVE-2019-8696 and CVE-2019-8675: Fixed SNMP buffer overflows (rdar://51685251) - Fixed IPP buffer overflow (rdar://50035411) - Fixed memory disclosure issue in the scheduler (rdar://51373853) - Fixed DoS issues in the scheduler (rdar://51373929)'</s>
<s>[INST] Given the following code containing errors, provide 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 exif_scan_thumbnail(image_info_type *ImageInfo) { uchar c, *data = (uchar*)ImageInfo->Thumbnail.data; int n, marker; size_t length=2, pos=0; jpeg_sof_info sof_info; if (!data) { return FALSE; /* nothing to do here */ } if (memcmp(data, "\xFF\xD8\xFF", 3)) { if (!ImageInfo->Thumbnail.width && !ImageInfo->Thumbnail.height) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Thumbnail is not a JPEG image"); } return FALSE; } for (;;) { pos += length; if (pos>=ImageInfo->Thumbnail.size) return FALSE; c = data[pos++]; if (pos>=ImageInfo->Thumbnail.size) return FALSE; if (c != 0xFF) { return FALSE; } n = 8; while ((c = data[pos++]) == 0xFF && n--) { if (pos+3>=ImageInfo->Thumbnail.size) return FALSE; /* +3 = pos++ of next check when reaching marker + 2 bytes for length */ } if (c == 0xFF) return FALSE; marker = c; if (pos>=ImageInfo->Thumbnail.size) return FALSE; length = php_jpg_get16(data+pos); if (length > ImageInfo->Thumbnail.size || pos >= ImageInfo->Thumbnail.size - length) { return FALSE; } #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: process section(x%02X=%s) @ x%04X + x%04X", marker, exif_get_markername(marker), pos, length); #endif switch (marker) { case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: /* handle SOFn block */ if (length < 8 || ImageInfo->Thumbnail.size - 8 < pos) { /* exif_process_SOFn needs 8 bytes */ return FALSE; } exif_process_SOFn(data+pos, marker, &sof_info); ImageInfo->Thumbnail.height = sof_info.height; ImageInfo->Thumbnail.width = sof_info.width; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: size: %d * %d", sof_info.width, sof_info.height); #endif return TRUE; case M_SOS: case M_EOI: exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Could not compute size of thumbnail"); return FALSE; break; default: /* just skip */ break; } } exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Could not compute size of thumbnail"); return FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #78222 (heap-buffer-overflow on exif_scan_thumbnail) (cherry picked from commit dea2989ab8ba87a6180af497b2efaf0527e985c5)'</s>
<s>[INST] Given the following code containing errors, provide 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 h2_mplx_awaits_data(h2_mplx *m) { int waiting = 1; H2_MPLX_ENTER_ALWAYS(m); if (h2_ihash_empty(m->streams)) { waiting = 0; } else if (!m->tasks_active && !h2_ififo_count(m->readyq) && h2_iq_empty(m->q)) { waiting = 0; } H2_MPLX_LEAVE(m); return waiting; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now, mpm event backport to 2.4.x up for vote). * Fixes stream cleanup when connection throttling is in place. * Counts stream resets by client on streams initiated by client as cause for connection throttling. * Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann) * Header length is checked also on the merged value from several header instances and results in a 431 response.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static h2_stream *get_timed_out_busy_stream(h2_mplx *m) { stream_iter_ctx ctx; ctx.m = m; ctx.stream = NULL; ctx.now = apr_time_now(); h2_ihash_iter(m->streams, timed_out_busy_iter, &ctx); return ctx.stream; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now, mpm event backport to 2.4.x up for vote). * Fixes stream cleanup when connection throttling is in place. * Counts stream resets by client on streams initiated by client as cause for connection throttling. * Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann) * Header length is checked also on the merged value from several header instances and results in a 431 response.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int pdf_load_xrefs(FILE *fp, pdf_t *pdf) { int i, ver, is_linear; long pos, pos_count; char x, *c, buf[256]; c = NULL; /* Count number of xrefs */ pdf->n_xrefs = 0; fseek(fp, 0, SEEK_SET); while (get_next_eof(fp) >= 0) ++pdf->n_xrefs; if (!pdf->n_xrefs) return 0; /* Load in the start/end positions */ fseek(fp, 0, SEEK_SET); pdf->xrefs = calloc(1, sizeof(xref_t) * pdf->n_xrefs); ver = 1; for (i=0; i<pdf->n_xrefs; i++) { /* Seek to %%EOF */ if ((pos = get_next_eof(fp)) < 0) break; /* Set and increment the version */ pdf->xrefs[i].version = ver++; /* Rewind until we find end of "startxref" */ pos_count = 0; while (SAFE_F(fp, ((x = fgetc(fp)) != 'f'))) fseek(fp, pos - (++pos_count), SEEK_SET); /* Suck in end of "startxref" to start of %%EOF */ if (pos_count >= sizeof(buf)) { ERR("Failed to locate the startxref token. " "This might be a corrupt PDF.\n"); return -1; } memset(buf, 0, sizeof(buf)); SAFE_E(fread(buf, 1, pos_count, fp), pos_count, "Failed to read startxref.\n"); c = buf; while (*c == ' ' || *c == '\n' || *c == '\r') ++c; /* xref start position */ pdf->xrefs[i].start = atol(c); /* If xref is 0 handle linear xref table */ if (pdf->xrefs[i].start == 0) get_xref_linear_skipped(fp, &pdf->xrefs[i]); /* Non-linear, normal operation, so just find the end of the xref */ else { /* xref end position */ pos = ftell(fp); fseek(fp, pdf->xrefs[i].start, SEEK_SET); pdf->xrefs[i].end = get_next_eof(fp); /* Look for next EOF and xref data */ fseek(fp, pos, SEEK_SET); } /* Check validity */ if (!is_valid_xref(fp, pdf, &pdf->xrefs[i])) { is_linear = pdf->xrefs[i].is_linear; memset(&pdf->xrefs[i], 0, sizeof(xref_t)); pdf->xrefs[i].is_linear = is_linear; rewind(fp); get_next_eof(fp); continue; } /* Load the entries from the xref */ load_xref_entries(fp, &pdf->xrefs[i]); } /* Now we have all xref tables, if this is linearized, we need * to make adjustments so that things spit out properly */ if (pdf->xrefs[0].is_linear) resolve_linearized_pdf(pdf); /* Ok now we have all xref data. Go through those versions of the * PDF and try to obtain creator information */ load_creator(fp, pdf); return pdf->n_xrefs; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Zero and sanity check all dynamic allocs. This addresses the memory issues in Issue #6 expressed in calloc_some.pdf and malloc_some.pdf'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int f_midi_set_alt(struct usb_function *f, unsigned intf, unsigned alt) { struct f_midi *midi = func_to_midi(f); unsigned i; int err; /* we only set alt for MIDIStreaming interface */ if (intf != midi->ms_id) return 0; err = f_midi_start_ep(midi, f, midi->in_ep); if (err) return err; err = f_midi_start_ep(midi, f, midi->out_ep); if (err) return err; /* pre-allocate write usb requests to use on f_midi_transmit. */ while (kfifo_avail(&midi->in_req_fifo)) { struct usb_request *req = midi_alloc_ep_req(midi->in_ep, midi->buflen); if (req == NULL) return -ENOMEM; req->length = 0; req->complete = f_midi_complete; kfifo_put(&midi->in_req_fifo, req); } /* allocate a bunch of read buffers and queue them all at once. */ for (i = 0; i < midi->qlen && err == 0; i++) { struct usb_request *req = midi_alloc_ep_req(midi->out_ep, midi->buflen); if (req == NULL) return -ENOMEM; req->complete = f_midi_complete; err = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC); if (err) { ERROR(midi, "%s: couldn't enqueue request: %d\n", midi->out_ep->name, err); free_ep_req(midi->out_ep, req); return err; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'USB: gadget: f_midi: fixing a possible double-free in f_midi It looks like there is a possibility of a double-free vulnerability on an error path of the f_midi_set_alt function in the f_midi driver. If the path is feasible then free_ep_req gets called twice: req->complete = f_midi_complete; err = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC); => ... usb_gadget_giveback_request => f_midi_complete (CALLBACK) (inside f_midi_complete, for various cases of status) free_ep_req(ep, req); // first kfree if (err) { ERROR(midi, "%s: couldn't enqueue request: %d\n", midi->out_ep->name, err); free_ep_req(midi->out_ep, req); // second kfree return err; } The double-free possibility was introduced with commit ad0d1a058eac ("usb: gadget: f_midi: fix leak on failed to enqueue out requests"). Found by MOXCAFE tool. Signed-off-by: Tuba Yavuz <tuba@ece.ufl.edu> Fixes: ad0d1a058eac ("usb: gadget: f_midi: fix leak on failed to enqueue out requests") Acked-by: Felipe Balbi <felipe.balbi@linux.intel.com> Cc: stable <stable@vger.kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int check_input_term(struct mixer_build *state, int id, struct usb_audio_term *term) { int protocol = state->mixer->protocol; int err; void *p1; memset(term, 0, sizeof(*term)); while ((p1 = find_audio_control_unit(state, id)) != NULL) { unsigned char *hdr = p1; term->id = id; if (protocol == UAC_VERSION_1 || protocol == UAC_VERSION_2) { switch (hdr[2]) { case UAC_INPUT_TERMINAL: if (protocol == UAC_VERSION_1) { struct uac_input_terminal_descriptor *d = p1; term->type = le16_to_cpu(d->wTerminalType); term->channels = d->bNrChannels; term->chconfig = le16_to_cpu(d->wChannelConfig); term->name = d->iTerminal; } else { /* UAC_VERSION_2 */ struct uac2_input_terminal_descriptor *d = p1; /* call recursively to verify that the * referenced clock entity is valid */ err = check_input_term(state, d->bCSourceID, term); if (err < 0) return err; /* save input term properties after recursion, * to ensure they are not overriden by the * recursion calls */ term->id = id; term->type = le16_to_cpu(d->wTerminalType); term->channels = d->bNrChannels; term->chconfig = le32_to_cpu(d->bmChannelConfig); term->name = d->iTerminal; } return 0; case UAC_FEATURE_UNIT: { /* the header is the same for v1 and v2 */ struct uac_feature_unit_descriptor *d = p1; id = d->bSourceID; break; /* continue to parse */ } case UAC_MIXER_UNIT: { struct uac_mixer_unit_descriptor *d = p1; term->type = UAC3_MIXER_UNIT << 16; /* virtual type */ term->channels = uac_mixer_unit_bNrChannels(d); term->chconfig = uac_mixer_unit_wChannelConfig(d, protocol); term->name = uac_mixer_unit_iMixer(d); return 0; } case UAC_SELECTOR_UNIT: case UAC2_CLOCK_SELECTOR: { struct uac_selector_unit_descriptor *d = p1; /* call recursively to retrieve the channel info */ err = check_input_term(state, d->baSourceID[0], term); if (err < 0) return err; term->type = UAC3_SELECTOR_UNIT << 16; /* virtual type */ term->id = id; term->name = uac_selector_unit_iSelector(d); return 0; } case UAC1_PROCESSING_UNIT: /* UAC2_EFFECT_UNIT */ if (protocol == UAC_VERSION_1) term->type = UAC3_PROCESSING_UNIT << 16; /* virtual type */ else /* UAC_VERSION_2 */ term->type = UAC3_EFFECT_UNIT << 16; /* virtual type */ /* fall through */ case UAC1_EXTENSION_UNIT: /* UAC2_PROCESSING_UNIT_V2 */ if (protocol == UAC_VERSION_1 && !term->type) term->type = UAC3_EXTENSION_UNIT << 16; /* virtual type */ else if (protocol == UAC_VERSION_2 && !term->type) term->type = UAC3_PROCESSING_UNIT << 16; /* virtual type */ /* fall through */ case UAC2_EXTENSION_UNIT_V2: { struct uac_processing_unit_descriptor *d = p1; if (protocol == UAC_VERSION_2 && hdr[2] == UAC2_EFFECT_UNIT) { /* UAC2/UAC1 unit IDs overlap here in an * uncompatible way. Ignore this unit for now. */ return 0; } if (d->bNrInPins) { id = d->baSourceID[0]; break; /* continue to parse */ } if (!term->type) term->type = UAC3_EXTENSION_UNIT << 16; /* virtual type */ term->channels = uac_processing_unit_bNrChannels(d); term->chconfig = uac_processing_unit_wChannelConfig(d, protocol); term->name = uac_processing_unit_iProcessing(d, protocol); return 0; } case UAC2_CLOCK_SOURCE: { struct uac_clock_source_descriptor *d = p1; term->type = UAC3_CLOCK_SOURCE << 16; /* virtual type */ term->id = id; term->name = d->iClockSource; return 0; } default: return -ENODEV; } } else { /* UAC_VERSION_3 */ switch (hdr[2]) { case UAC_INPUT_TERMINAL: { struct uac3_input_terminal_descriptor *d = p1; /* call recursively to verify that the * referenced clock entity is valid */ err = check_input_term(state, d->bCSourceID, term); if (err < 0) return err; /* save input term properties after recursion, * to ensure they are not overriden by the * recursion calls */ term->id = id; term->type = le16_to_cpu(d->wTerminalType); err = get_cluster_channels_v3(state, le16_to_cpu(d->wClusterDescrID)); if (err < 0) return err; term->channels = err; /* REVISIT: UAC3 IT doesn't have channels cfg */ term->chconfig = 0; term->name = le16_to_cpu(d->wTerminalDescrStr); return 0; } case UAC3_FEATURE_UNIT: { struct uac3_feature_unit_descriptor *d = p1; id = d->bSourceID; break; /* continue to parse */ } case UAC3_CLOCK_SOURCE: { struct uac3_clock_source_descriptor *d = p1; term->type = UAC3_CLOCK_SOURCE << 16; /* virtual type */ term->id = id; term->name = le16_to_cpu(d->wClockSourceStr); return 0; } case UAC3_MIXER_UNIT: { struct uac_mixer_unit_descriptor *d = p1; err = uac_mixer_unit_get_channels(state, d); if (err <= 0) return err; term->channels = err; term->type = UAC3_MIXER_UNIT << 16; /* virtual type */ return 0; } case UAC3_SELECTOR_UNIT: case UAC3_CLOCK_SELECTOR: { struct uac_selector_unit_descriptor *d = p1; /* call recursively to retrieve the channel info */ err = check_input_term(state, d->baSourceID[0], term); if (err < 0) return err; term->type = UAC3_SELECTOR_UNIT << 16; /* virtual type */ term->id = id; term->name = 0; /* TODO: UAC3 Class-specific strings */ return 0; } case UAC3_PROCESSING_UNIT: { struct uac_processing_unit_descriptor *d = p1; if (!d->bNrInPins) return -EINVAL; /* call recursively to retrieve the channel info */ err = check_input_term(state, d->baSourceID[0], term); if (err < 0) return err; term->type = UAC3_PROCESSING_UNIT << 16; /* virtual type */ term->id = id; term->name = 0; /* TODO: UAC3 Class-specific strings */ return 0; } default: return -ENODEV; } } } return -ENODEV; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-674'], 'message': 'ALSA: usb-audio: Fix a stack buffer overflow bug in check_input_term `check_input_term` recursively calls itself with input from device side (e.g., uac_input_terminal_descriptor.bCSourceID) as argument (id). In `check_input_term`, if `check_input_term` is called with the same `id` argument as the caller, it triggers endless recursive call, resulting kernel space stack overflow. This patch fixes the bug by adding a bitmap to `struct mixer_build` to keep track of the checked ids and stop the execution if some id has been checked (similar to how parse_audio_unit handles unitid argument). Reported-by: Hui Peng <benquike@gmail.com> Reported-by: Mathias Payer <mathias.payer@nebelwelt.net> Signed-off-by: Hui Peng <benquike@gmail.com> Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void dvb_usb_device_exit(struct usb_interface *intf) { struct dvb_usb_device *d = usb_get_intfdata(intf); const char *name = "generic DVB-USB module"; usb_set_intfdata(intf, NULL); if (d != NULL && d->desc != NULL) { name = d->desc->name; dvb_usb_exit(d); } info("%s successfully deinitialized and disconnected.", name); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'media: dvb: usb: fix use after free in dvb_usb_device_exit dvb_usb_device_exit() frees and uses the device name in that order. Fix by storing the name in a buffer before freeing it. Signed-off-by: Oliver Neukum <oneukum@suse.com> Reported-by: syzbot+26ec41e9f788b3eba396@syzkaller.appspotmail.com Signed-off-by: Sean Young <sean@mess.org> Signed-off-by: Mauro Carvalho Chehab <mchehab+samsung@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void cpia2_usb_disconnect(struct usb_interface *intf) { struct camera_data *cam = usb_get_intfdata(intf); usb_set_intfdata(intf, NULL); DBG("Stopping stream\n"); cpia2_usb_stream_stop(cam); mutex_lock(&cam->v4l2_lock); DBG("Unregistering camera\n"); cpia2_unregister_camera(cam); v4l2_device_disconnect(&cam->v4l2_dev); mutex_unlock(&cam->v4l2_lock); v4l2_device_put(&cam->v4l2_dev); if(cam->buffers) { DBG("Wakeup waiting processes\n"); cam->curbuff->status = FRAME_READY; cam->curbuff->length = 0; wake_up_interruptible(&cam->wq_stream); } LOG("CPiA2 camera disconnected.\n"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'media: cpia2_usb: first wake up, then free in disconnect Kasan reported a use after free in cpia2_usb_disconnect() It first freed everything and then woke up those waiting. The reverse order is correct. Fixes: 6c493f8b28c67 ("[media] cpia2: major overhaul to get it in a working state again") Signed-off-by: Oliver Neukum <oneukum@suse.com> Reported-by: syzbot+0c90fc937c84f97d0aa6@syzkaller.appspotmail.com Signed-off-by: Hans Verkuil <hverkuil-cisco@xs4all.nl> Signed-off-by: Mauro Carvalho Chehab <mchehab+samsung@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: const std::array<unsigned char, 16> md5() const { int len = 0; const char* data = nullptr; if (type() == BinData && binDataType() == BinDataType::MD5Type) data = binData(len); uassert(40437, "md5 must be a 16-byte binary field with MD5 (5) subtype", len == 16); std::array<unsigned char, 16> result; memcpy(&result, data, len); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-613'], 'message': 'SERVER-38984 Validate unique User ID on UserCache hit'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Status V2UserDocumentParser::checkValidUserDocument(const BSONObj& doc) const { BSONElement userElement = doc[AuthorizationManager::USER_NAME_FIELD_NAME]; BSONElement userDBElement = doc[AuthorizationManager::USER_DB_FIELD_NAME]; BSONElement credentialsElement = doc[CREDENTIALS_FIELD_NAME]; BSONElement rolesElement = doc[ROLES_FIELD_NAME]; // Validate the "user" element. if (userElement.type() != String) return _badValue("User document needs 'user' field to be a string", 0); if (userElement.valueStringData().empty()) return _badValue("User document needs 'user' field to be non-empty", 0); // Validate the "db" element if (userDBElement.type() != String || userDBElement.valueStringData().empty()) { return _badValue("User document needs 'db' field to be a non-empty string", 0); } StringData userDBStr = userDBElement.valueStringData(); if (!NamespaceString::validDBName(userDBStr, NamespaceString::DollarInDbNameBehavior::Allow) && userDBStr != "$external") { return _badValue(mongoutils::str::stream() << "'" << userDBStr << "' is not a valid value for the db field.", 0); } // Validate the "credentials" element if (credentialsElement.eoo()) { return _badValue("User document needs 'credentials' object", 0); } if (credentialsElement.type() != Object) { return _badValue("User document needs 'credentials' field to be an object", 0); } BSONObj credentialsObj = credentialsElement.Obj(); if (credentialsObj.isEmpty()) { return _badValue("User document needs 'credentials' field to be a non-empty object", 0); } if (userDBStr == "$external") { BSONElement externalElement = credentialsObj[MONGODB_EXTERNAL_CREDENTIAL_FIELD_NAME]; if (externalElement.eoo() || externalElement.type() != Bool || !externalElement.Bool()) { return _badValue( "User documents for users defined on '$external' must have " "'credentials' field set to {external: true}", 0); } } else { BSONElement scramElement = credentialsObj[SCRAM_CREDENTIAL_FIELD_NAME]; BSONElement mongoCRElement = credentialsObj[MONGODB_CR_CREDENTIAL_FIELD_NAME]; if (!mongoCRElement.eoo()) { if (mongoCRElement.type() != String || mongoCRElement.valueStringData().empty()) { return _badValue( "MONGODB-CR credential must to be a non-empty string" ", if present", 0); } } else if (!scramElement.eoo()) { if (scramElement.type() != Object) { return _badValue("SCRAM credential must be an object, if present", 0); } } else { return _badValue( "User document must provide credentials for all " "non-external users", 0); } } // Validate the "roles" element. Status status = _checkV2RolesArray(rolesElement); if (!status.isOK()) return status; return Status::OK(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-613'], 'message': 'SERVER-38984 Validate unique User ID on UserCache hit (cherry picked from commit e55d6e2292e5dbe2f97153251d8193d1cc89f5d7)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct domain_device *sas_ex_discover_expander( struct domain_device *parent, int phy_id) { struct sas_expander_device *parent_ex = rphy_to_expander_device(parent->rphy); struct ex_phy *phy = &parent->ex_dev.ex_phy[phy_id]; struct domain_device *child = NULL; struct sas_rphy *rphy; struct sas_expander_device *edev; struct asd_sas_port *port; int res; if (phy->routing_attr == DIRECT_ROUTING) { pr_warn("ex %016llx:%02d:D <--> ex %016llx:0x%x is not allowed\n", SAS_ADDR(parent->sas_addr), phy_id, SAS_ADDR(phy->attached_sas_addr), phy->attached_phy_id); return NULL; } child = sas_alloc_device(); if (!child) return NULL; phy->port = sas_port_alloc(&parent->rphy->dev, phy_id); /* FIXME: better error handling */ BUG_ON(sas_port_add(phy->port) != 0); switch (phy->attached_dev_type) { case SAS_EDGE_EXPANDER_DEVICE: rphy = sas_expander_alloc(phy->port, SAS_EDGE_EXPANDER_DEVICE); break; case SAS_FANOUT_EXPANDER_DEVICE: rphy = sas_expander_alloc(phy->port, SAS_FANOUT_EXPANDER_DEVICE); break; default: rphy = NULL; /* shut gcc up */ BUG(); } port = parent->port; child->rphy = rphy; get_device(&rphy->dev); edev = rphy_to_expander_device(rphy); child->dev_type = phy->attached_dev_type; kref_get(&parent->kref); child->parent = parent; child->port = port; child->iproto = phy->attached_iproto; child->tproto = phy->attached_tproto; memcpy(child->sas_addr, phy->attached_sas_addr, SAS_ADDR_SIZE); sas_hash_addr(child->hashed_sas_addr, child->sas_addr); sas_ex_get_linkrate(parent, child, phy); edev->level = parent_ex->level + 1; parent->port->disc.max_level = max(parent->port->disc.max_level, edev->level); sas_init_dev(child); sas_fill_in_rphy(child, rphy); sas_rphy_add(rphy); spin_lock_irq(&parent->port->dev_list_lock); list_add_tail(&child->dev_list_node, &parent->port->dev_list); spin_unlock_irq(&parent->port->dev_list_lock); res = sas_discover_expander(child); if (res) { sas_rphy_delete(rphy); spin_lock_irq(&parent->port->dev_list_lock); list_del(&child->dev_list_node); spin_unlock_irq(&parent->port->dev_list_lock); sas_put_device(child); return NULL; } list_add_tail(&child->siblings, &parent->ex_dev.children); return child; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'scsi: libsas: delete sas port if expander discover failed The sas_port(phy->port) allocated in sas_ex_discover_expander() will not be deleted when the expander failed to discover. This will cause resource leak and a further issue of kernel BUG like below: [159785.843156] port-2:17:29: trying to add phy phy-2:17:29 fails: it's already part of another port [159785.852144] ------------[ cut here ]------------ [159785.856833] kernel BUG at drivers/scsi/scsi_transport_sas.c:1086! [159785.863000] Internal error: Oops - BUG: 0 [#1] SMP [159785.867866] CPU: 39 PID: 16993 Comm: kworker/u96:2 Tainted: G W OE 4.19.25-vhulk1901.1.0.h111.aarch64 #1 [159785.878458] Hardware name: Huawei Technologies Co., Ltd. Hi1620EVBCS/Hi1620EVBCS, BIOS Hi1620 CS B070 1P TA 03/21/2019 [159785.889231] Workqueue: 0000:74:02.0_disco_q sas_discover_domain [159785.895224] pstate: 40c00009 (nZcv daif +PAN +UAO) [159785.900094] pc : sas_port_add_phy+0x188/0x1b8 [159785.904524] lr : sas_port_add_phy+0x188/0x1b8 [159785.908952] sp : ffff0001120e3b80 [159785.912341] x29: ffff0001120e3b80 x28: 0000000000000000 [159785.917727] x27: ffff802ade8f5400 x26: ffff0000681b7560 [159785.923111] x25: ffff802adf11a800 x24: ffff0000680e8000 [159785.928496] x23: ffff802ade8f5728 x22: ffff802ade8f5708 [159785.933880] x21: ffff802adea2db40 x20: ffff802ade8f5400 [159785.939264] x19: ffff802adea2d800 x18: 0000000000000010 [159785.944649] x17: 00000000821bf734 x16: ffff00006714faa0 [159785.950033] x15: ffff0000e8ab4ecf x14: 7261702079646165 [159785.955417] x13: 726c612073277469 x12: ffff00006887b830 [159785.960802] x11: ffff00006773eaa0 x10: 7968702079687020 [159785.966186] x9 : 0000000000002453 x8 : 726f702072656874 [159785.971570] x7 : 6f6e6120666f2074 x6 : ffff802bcfb21290 [159785.976955] x5 : ffff802bcfb21290 x4 : 0000000000000000 [159785.982339] x3 : ffff802bcfb298c8 x2 : 337752b234c2ab00 [159785.987723] x1 : 337752b234c2ab00 x0 : 0000000000000000 [159785.993108] Process kworker/u96:2 (pid: 16993, stack limit = 0x0000000072dae094) [159786.000576] Call trace: [159786.003097] sas_port_add_phy+0x188/0x1b8 [159786.007179] sas_ex_get_linkrate.isra.5+0x134/0x140 [159786.012130] sas_ex_discover_expander+0x128/0x408 [159786.016906] sas_ex_discover_dev+0x218/0x4c8 [159786.021249] sas_ex_discover_devices+0x9c/0x1a8 [159786.025852] sas_discover_root_expander+0x134/0x160 [159786.030802] sas_discover_domain+0x1b8/0x1e8 [159786.035148] process_one_work+0x1b4/0x3f8 [159786.039230] worker_thread+0x54/0x470 [159786.042967] kthread+0x134/0x138 [159786.046269] ret_from_fork+0x10/0x18 [159786.049918] Code: 91322300 f0004402 91178042 97fe4c9b (d4210000) [159786.056083] Modules linked in: hns3_enet_ut(OE) hclge(OE) hnae3(OE) hisi_sas_test_hw(OE) hisi_sas_test_main(OE) serdes(OE) [159786.067202] ---[ end trace 03622b9e2d99e196 ]--- [159786.071893] Kernel panic - not syncing: Fatal exception [159786.077190] SMP: stopping secondary CPUs [159786.081192] Kernel Offset: disabled [159786.084753] CPU features: 0x2,a2a00a38 Fixes: 2908d778ab3e ("[SCSI] aic94xx: new driver") Reported-by: Jian Luo <luojian5@huawei.com> Signed-off-by: Jason Yan <yanaijie@huawei.com> CC: John Garry <john.garry@huawei.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int p54u_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *udev = interface_to_usbdev(intf); struct ieee80211_hw *dev; struct p54u_priv *priv; int err; unsigned int i, recognized_pipes; dev = p54_init_common(sizeof(*priv)); if (!dev) { dev_err(&udev->dev, "(p54usb) ieee80211 alloc failed\n"); return -ENOMEM; } priv = dev->priv; priv->hw_type = P54U_INVALID_HW; SET_IEEE80211_DEV(dev, &intf->dev); usb_set_intfdata(intf, dev); priv->udev = udev; priv->intf = intf; skb_queue_head_init(&priv->rx_queue); init_usb_anchor(&priv->submitted); usb_get_dev(udev); /* really lazy and simple way of figuring out if we're a 3887 */ /* TODO: should just stick the identification in the device table */ i = intf->altsetting->desc.bNumEndpoints; recognized_pipes = 0; while (i--) { switch (intf->altsetting->endpoint[i].desc.bEndpointAddress) { case P54U_PIPE_DATA: case P54U_PIPE_MGMT: case P54U_PIPE_BRG: case P54U_PIPE_DEV: case P54U_PIPE_DATA | USB_DIR_IN: case P54U_PIPE_MGMT | USB_DIR_IN: case P54U_PIPE_BRG | USB_DIR_IN: case P54U_PIPE_DEV | USB_DIR_IN: case P54U_PIPE_INT | USB_DIR_IN: recognized_pipes++; } } priv->common.open = p54u_open; priv->common.stop = p54u_stop; if (recognized_pipes < P54U_PIPE_NUMBER) { #ifdef CONFIG_PM /* ISL3887 needs a full reset on resume */ udev->reset_resume = 1; #endif /* CONFIG_PM */ err = p54u_device_reset(dev); priv->hw_type = P54U_3887; dev->extra_tx_headroom += sizeof(struct lm87_tx_hdr); priv->common.tx_hdr_len = sizeof(struct lm87_tx_hdr); priv->common.tx = p54u_tx_lm87; priv->upload_fw = p54u_upload_firmware_3887; } else { priv->hw_type = P54U_NET2280; dev->extra_tx_headroom += sizeof(struct net2280_tx_hdr); priv->common.tx_hdr_len = sizeof(struct net2280_tx_hdr); priv->common.tx = p54u_tx_net2280; priv->upload_fw = p54u_upload_firmware_net2280; } err = p54u_load_firmware(dev, intf); if (err) { usb_put_dev(udev); p54_free_common(dev); } return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'p54usb: Fix race between disconnect and firmware loading The syzbot fuzzer found a bug in the p54 USB wireless driver. The issue involves a race between disconnect and the firmware-loader callback routine, and it has several aspects. One big problem is that when the firmware can't be loaded, the callback routine tries to unbind the driver from the USB _device_ (by calling device_release_driver) instead of from the USB _interface_ to which it is actually bound (by calling usb_driver_release_interface). The race involves access to the private data structure. The driver's disconnect handler waits for a completion that is signalled by the firmware-loader callback routine. As soon as the completion is signalled, you have to assume that the private data structure may have been deallocated by the disconnect handler -- even if the firmware was loaded without errors. However, the callback routine does access the private data several times after that point. Another problem is that, in order to ensure that the USB device structure hasn't been freed when the callback routine runs, the driver takes a reference to it. This isn't good enough any more, because now that the callback routine calls usb_driver_release_interface, it has to ensure that the interface structure hasn't been freed. Finally, the driver takes an unnecessary reference to the USB device structure in the probe function and drops the reference in the disconnect handler. This extra reference doesn't accomplish anything, because the USB core already guarantees that a device structure won't be deallocated while a driver is still bound to any of its interfaces. To fix these problems, this patch makes the following changes: Call usb_driver_release_interface() rather than device_release_driver(). Don't signal the completion until after the important information has been copied out of the private data structure, and don't refer to the private data at all thereafter. Lock udev (the interface's parent) before unbinding the driver instead of locking udev->parent. During the firmware loading process, take a reference to the USB interface instead of the USB device. Don't take an unnecessary reference to the device during probe (and then don't drop it during disconnect). Signed-off-by: Alan Stern <stern@rowland.harvard.edu> Reported-and-tested-by: syzbot+200d4bb11b23d929335f@syzkaller.appspotmail.com CC: <stable@vger.kernel.org> Acked-by: Christian Lamparter <chunkeey@gmail.com> Signed-off-by: Kalle Valo <kvalo@codeaurora.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, struct kvec *iov, int n_vec) { struct smb_rqst rqst; int rc = 0; struct smb2_write_req *req = NULL; struct smb2_write_rsp *rsp = NULL; int resp_buftype; struct kvec rsp_iov; int flags = 0; unsigned int total_len; *nbytes = 0; if (n_vec < 1) return rc; rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, (void **) &req, &total_len); if (rc) return rc; if (io_parms->tcon->ses->server == NULL) return -ECONNABORTED; if (smb3_encryption_required(io_parms->tcon)) flags |= CIFS_TRANSFORM_REQ; req->sync_hdr.ProcessId = cpu_to_le32(io_parms->pid); req->PersistentFileId = io_parms->persistent_fid; req->VolatileFileId = io_parms->volatile_fid; req->WriteChannelInfoOffset = 0; req->WriteChannelInfoLength = 0; req->Channel = 0; req->Length = cpu_to_le32(io_parms->length); req->Offset = cpu_to_le64(io_parms->offset); req->DataOffset = cpu_to_le16( offsetof(struct smb2_write_req, Buffer)); req->RemainingBytes = 0; trace_smb3_write_enter(xid, io_parms->persistent_fid, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, io_parms->length); iov[0].iov_base = (char *)req; /* 1 for Buffer */ iov[0].iov_len = total_len - 1; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = n_vec + 1; rc = cifs_send_recv(xid, io_parms->tcon->ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_write_rsp *)rsp_iov.iov_base; if (rc) { trace_smb3_write_err(xid, req->PersistentFileId, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, io_parms->length, rc); cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE); cifs_dbg(VFS, "Send error in write = %d\n", rc); } else { *nbytes = le32_to_cpu(rsp->DataLength); trace_smb3_write_done(xid, req->PersistentFileId, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, *nbytes); } free_rsp_buf(resp_buftype, rsp); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-200'], 'message': 'cifs: Fix use-after-free in SMB2_write There is a KASAN use-after-free: BUG: KASAN: use-after-free in SMB2_write+0x1342/0x1580 Read of size 8 at addr ffff8880b6a8e450 by task ln/4196 Should not release the 'req' because it will use in the trace. Fixes: eccb4422cf97 ("smb3: Add ftrace tracepoints for improved SMB3 debugging") Signed-off-by: ZhangXiaoxu <zhangxiaoxu5@huawei.com> Signed-off-by: Steve French <stfrench@microsoft.com> CC: Stable <stable@vger.kernel.org> 4.18+ Reviewed-by: Pavel Shilovsky <pshilov@microsoft.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool HaarEvaluator::Feature :: read( const FileNode& node ) { FileNode rnode = node[CC_RECTS]; FileNodeIterator it = rnode.begin(), it_end = rnode.end(); int ri; for( ri = 0; ri < RECT_NUM; ri++ ) { rect[ri].r = Rect(); rect[ri].weight = 0.f; } for(ri = 0; it != it_end; ++it, ri++) { FileNodeIterator it2 = (*it).begin(); it2 >> rect[ri].r.x >> rect[ri].r.y >> rect[ri].r.width >> rect[ri].r.height >> rect[ri].weight; } tilted = (int)node[CC_TILTED] != 0; return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'objdetect: validate feature rectangle on reading'</s>